Colorful Wires

エンジニアリングの勉強の記録

Create an executable file containing icecream with pyinstaller

When attempting to convert a Python script that utilizes the icecream library into an executable using pyinstaller, an error may occur. The error message states that a FileNotFoundError occurred, specifically for the file 'icecream/version.py'.

This error is caused by the icecream library running the icecream/version.py file with the exec() function, and therefore this file needs to be included in the executable.

A solution to this issue is to edit the .spec file for pyinstaller. First, add the following code at the top of the file:

import os
import icecream
icecream_path = os.path.abspath(icecream.__path__[0])

Then, add the Tree() function as an argument to the COLLECT() function like so:

coll = COLLECT(exe,
               a.binaries,
               Tree(icecream_path, prefix="icecream"),
               a.zipfiles,

By implementing these changes, the icecream library will be properly included in the executable, and the error should be resolved.

einsum の使い方

numpy.einsum の使い方を学ぶべく、マニュアルを翻訳する。まだ未完成。

以下に numpy.einsumシグネチャを記載します。

einsum(*operands, out=None, optimize=False, **kwargs)
    einsum(subscripts, *operands, out=None, dtype=None, order='K',
           casting='safe', optimize=False)

Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion.

アインシュタインの縮約表記を使うことで、 複数の共通する多次元の線形代数配列の演算をシンプルに表現することができます。

In implicit mode einsum computes these values.

implicit モードでは einsum は以下の値を計算します。

In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.

explicit モードでは、einsum は 指定した添え字に対する総和を無効にしたり強制することにより、 古典的なアインシュタイン縮約表記の範疇から外れる ほかの配列演算に対するさらなる柔軟性を提供します。

See the notes and examples for clarification.

明確化のためのノートと例を参照してください。

Parameters

パラメーター

subscripts : str

添え字: str

Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator '->' is included as well as subscript labels of the precise output form.

カンマでセパレートされた添え字ラベルのリストを指定します。 正確な出力書式の添え字ラベルと同様に、 explicit な indicator -> が含まれていなくても、 implicit (古典的なアインシュタイン縮約表記) の計算は実行されます。

operands : list of array_like These are the arrays for the operation. If provided, the calculation is done into this array.

演算子 : 配列のリストです。 演算の対象となる複数の配列です。 与えられればこれらの配列に対して演算が適用されます。

dtype : {data-type, None}, optional If provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal casting parameter to allow the conversions. Default is None.

与えられた場合、計算において指定されたデータ タイプを使うことを強制します。 変換を許すように自由にパラメータをキャストすることができるかもしれません。

order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the output. 'C' means it should be C contiguous. 'F' means it should be Fortran contiguous, 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise. 'K' means it should be as close to the layout as the inputs as is possible, including arbitrarily permuted axes. Default is 'K'.

出力のメモリーのレイアウトを制御します。 C は C contigious です。 FFortran contigious です。 A は すべての入力が F なら F、そうでなければ C です。 K は、任意の順序の軸も含めて、可能な限り入力の形式と同じにします。 デフォルトは K です。

casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Setting this to 'unsafe' is not recommended, as it can adversely affect accumulations.

データキャスティングを許可するかを制御します。 これを unsafe に設定することは非推奨。

'no' means the data types should not be cast at all. 'equiv' means only byte-order changes are allowed. 'safe' means only casts which can preserve values are allowed. 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. 'unsafe' means any data conversions may be done. Default is 'safe'.

no はデータタイプはキャストされないようにします。 equiv はバイトオーダーの変換だけ許します。 safe は値が保持されるだけキャストを許します。 same kindfloat64 から float32 のような安全なキャストだけ許します。 unsafe はどんなデータ変換も起こりうることを意味します。 デフォルトは safe です。

optimize : {False, True, 'greedy', 'optimal'}, optional Controls if intermediate optimization should occur. No optimization will occur if False and True will default to the 'greedy' algorithm. Also accepts an explicit contraction list from the np.einsum_path function. See np.einsum_path for more details. Defaults to False.

中間の最適化が行われるべきかを示します。 False では最適化せず、 True では既定では greedy アルゴリズムが使われます。 np.einsum_path で生成した明示的な contraction list も受け付けます。 デフォルトは False です。

本当?このあたりはいっぱい See Also に書いてある。

相互相関関数を正規化する

概要

相互相関関数のスケールは、入力信号のスケールに依存します。 入力信号のスケールに依存しない、正規化された相互相関関数は、 入力信号をそれぞれ正規化してから相互相関関数を求めることで得られます。 このようにして得られたものは、正規化相互相関関数と呼びます。

詳細

相互相関関数は、以下の畳み込みの式に、一方の信号を逆向きにして入力することで求められます。


(f * g)(m) = \sum_{n} f(n) g(m-n)

相互相関関数は元の信号のスケールに依存しますが、どのようにスケールを正規化すればよいのでしょうか。

以下のリンクに相互相関関数の使用例が記載されていますが、値は 0 から 1 に正規化されていません。 bsd.neuroinf.jp

相互相関関数は、スケーリングされていなくてもいいようです。


C_{XY} (\tau) = \sum_{t=1}^{T} X(t) Y(t+\tau)

相互相関は、正規化すると、正規化相互相関係数という指標になるようです。

では具体的な正規化の手順を探してみます。

自己相関関数では、最大値が 1 になるようにすることを正規化と呼ぶらしいです。
http://www.slp.k.hosei.ac.jp/~itou/lecture/2011/DigitalData/06_text.pdf

正規化は、画像のレジストレーションでよく使われています。 レジストレーションとは、似た画像をピッタリ重ね合わせる位置や角度を見つけることです。 http://www.cfme.chiba-u.jp/~haneishi/class/digitalgazo/12Registration.pdf

正規化相互相関係数の定義は、上記の資料の 6 頁を参考にします。 以下に一部を引用します。

f:id:moge560:20210705165545p:plain
画像工学入門 - パターン認識:マッチング・レジストレーション - 6 頁

正規化相互相関は、元の波形から、平均値を引き、標準偏差で割った信号に対して相関の計算を行うことで可能です。 ただし NumPy の numpy.correlate は各要素の和を行うため、入力ベクトルの長さで除算することが必要です。

以下に正規化相互相関係数Python で求めるサンプルコードを記載します。

import numpy as np
# ベクトル a を正規化しておきます。
# ベクトル b を正規化しておきます。
assert len(a) == len(b)

# 高々 1 に正規化された相互相関は以下で得られます。
np.correlate(a, b) / len(a)

gather in R

tidyr の gather 関数の使い方をいつも忘れるので自分用にメモします。

gather はデータセットを wide 型から long 型に変換します。

 gather(iris, key=newKeyColumnName, value=newValueColumnName, Sepal.Length, Petal.Length, Sepal.Width, Petal.Width) %>% head()

とすると

  Species newKeyColumnName newValueColumnName
1  setosa     Sepal.Length                5.1
2  setosa     Sepal.Length                4.9
3  setosa     Sepal.Length                4.7
4  setosa     Sepal.Length                4.6
5  setosa     Sepal.Length                5.0
6  setosa     Sepal.Length                5.4

入力データフレームの列を以下の 2 種類に分けます。

  1. gather の最後の可変長変数に入れられた列
  2. A 以外の列

そして以下のように新しいデータフレームを作ります。

B1, B2, ... , newKeyColumnName, newValueColumnName
B1, B2,      Aの列名,                       Aの列の値
B1, B2,      Aの列名,                       Aの列の値
B1, B2,      Aの列名,                       Aの列の値

指定した仮想環境で Python スクリプトを起動するショートカットの作り方 (Windows)

概要

 この記事では、Python で実装した Windows 用のスクリプトを、利用する仮想環境を指定して実行するためのショートカットの作成方法を説明します。

事前に確認しておくこと

  1. CUIGUI どちらで実行したいか (コマンドプロンプトを画面に表示するかしないか)
  2. 使用したい仮想環境の pythonw.exe (または python.exe) のパス
  3. venv を使う場合は、仮想環境フォルダの中の Scripts\pythonw.exe です。
  4. 実行したい Python スクリプトが格納されたフォルダのパス
  5. 実行したい Python スクリプトのファイル名

手順

f:id:moge560:20210304104015p:plain
Python 実行用ショートカットの作成画面

  1. エクスプローラ上でショートカットを作成します。
  2. リンク先欄に、使用したい仮想環境の pythonw.exe (CUI の場合) または python.exe (GUI の場合) のパスと、実行したい Python スクリプトのファイル名を、スペースで結合したものを入力します。
  3. 作業フォルダー欄に、実行したい Python スクリプトが格納されたフォルダのパスを入力します。