内容へ移動
Saki Wiki
ユーザ用ツール
ログイン
サイト用ツール
検索
ツール
文書の表示
以前のリビジョン
バックリンク
最近の変更
メディアマネージャー
サイトマップ
ログイン
>
最近の変更
メディアマネージャー
サイトマップ
トレース:
プログラム:python
この文書は読取専用です。文書のソースを閲覧することは可能ですが、変更はできません。もし変更したい場合は管理者に連絡してください。
=====python忘備録===== ====install (MacOS)==== ===brew install (非推奨)=== <file> $ brew install python3 </file> で最新のpythonが入る。 <file> $ python3 --version Python 3.9.13 </file> pythonはよく複数のバージョンを使いたくなることがあるので、以下のパッケージ管理ソフトを利用して複数の仮想環境を作成することが多い。 ===MiniForge=== Pythonのパッケージ管理ソフトにはpip, pipenv, pyenv, anacondaなどたくさんある。M1チップの場合はMiniForgeを使うとよいらしい。\\ MiniForgeのインストール <file> $ wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh $ bash Miniforge3-MacOSX-arm64.sh </file> 色々聞かれるので、yes (or Enter)で良い。\\ 仮想環境の構築+アクティベーション <file> $ conda create --name hogeenv python=3.8 $ conda activate hogeenv </file> これでpython3.8の仮想環境''hogeenv''ができた。 <file> $ conda deactivate </file> で仮想環境を終了。\\ デフォルトで''base''という環境がactiveになるので <file> conda config --set auto_activate_base False </file> で無効化できる。作った仮想環境のリストは <file> conda env list </file> で見ることができる。 ===Jupyter Notebook=== 仮想環境をアクティベートした状態で以下のコマンドで起動。 <file> $ conda install jupyter $ jupyter notebook </file> Notebook上でのモジュールのインストールの仕方。\\ <file> !pip install module </file> importできない時はpathの確認 <file> !pip show module </file> をして、追加\\ <file> import sys sys.path.append('path') </file> 便利なコマンド\\ cellをdeactivate : esc + r\\ cellをactivate : esc + y ====文法==== ===スコープ=== indentの位置でスコープが決まる(?)。\\ コメントであってもindentの位置を変えることは許されない。(),[],{}内は改行が許されている。 ===宣言=== 変数の宣言時に型の指定は不要(?)。 函数の引数にも不要(?)。 注:組み込み関数を上書きしようとしても何もエラーを吐かず、そのまま上書きする(?)。\\ 例:print = 0などとしてしまうと、何もエラーを吐かずprintが関数でなくintになり、print()がエラーを吐くようになる。\\ 対処法:del printでリセット可能。 ===文字列=== <nowiki>''</nowiki>と""どちらも可(!?) 変数を文字列にして出力 <code> print("Process %s type %d : progress %.3f %%"%(hoge,huga,piyo)) </code> %s : 文字, %d : 整数, %.3f : float3桁まで表示。 %% : %のエスケープ ===ライブラリの読み込み方=== カレントディレクトリのhoge.pyを読み込むとき <file> import hoge </file> この時、hoge.pyは実行される。ライブラリの場合は定義のみ書いてある(コマンドの実行を含まない)ことも多い。 *特別な変数<nowiki>__name__</nowiki>について。\\ hoge.pyがpython3コマンドによって直接実行された場合、<nowiki>__name__=__main__</nowiki>となる。importによって呼び出されて実行された場合は<nowiki>__name__=__hoge__</nowiki>となる。これを利用して、直接実行されたときにしか実行されない部分を用意できる。 <file> if __name__ == '__main__': #ファイルを直接実行したときTrue main() </file> hoge.pyのクラスHogeを呼びたい場合は <file> from hoge import Hoge </file> ===関数=== 以下のように宣言する。返り値を複数設定可能で、配列で渡される。 <file> def hoge(huga,piyo): foo = huga + piyo bar = huga - piyo return foo, piyo </file> 配列の各要素に関数を作用させたいとき\\ 例:shapeが(1000,2)のnumpy.array num_arrayの二つ目の軸の要素の和と差のnumpu.arrayを作りたい <file> new_array = np.apply_along_axis(lambda element: hoge(*element), 1, num_array) </file> lambda : ラムダ式。ここでだけ使う関数を宣言できる。 ===クラス=== <file> class Hoge(Fuga): #Fugaを継承したHogeクラス def __init__(self): #__init__はコンストラクタ super().__init__() #Fugaのコンストラクタが呼ばれる self.hoge = 0 #メンバ変数hogeはここで定義される def __init__(self, piyo): #引数違いのコンストラクタ super().__init__() self.hoge = piyo def hogehoge(self, foo, bar): ...... </file> 以下のインデントが揃っている部分がそのクラスの定義。()を付けるとクラスを継承できる(省略可)。 クラスの中で変数や函数を定義するとそのメンバになる。 コンストラクタの中で(self.hogeの形で)宣言した変数はメンバ変数になる。 classの函数は第一引数に''self''を必ず持たなくてはならない。メンバ変数hogeを呼ぶときはself.hogeの形で呼ぶ。 コンストラクタは<nowiki>__init__()</nowiki>、デストラクタは<nowiki>__del__()</nowiki>。引数が違うコンストラクタを複数定義できる。 super().で継承前のクラスのメンバを呼び出せる。 ===コメントアウト=== 一行は先頭に#を置く。複数行は''<nowiki>"""</nowiki>''(ダブルクオート三つ)で囲む。 ===for文=== <file> for i in range(0,nstep,1) : ### for文の中身 ### </file> ''range(start,stop,step)''は$\mathrm{start}\leqq i<\mathrm{stop}$の間で''step''ずつカウンターを増やす。 ===組み込み関数など=== type() : 型を表示する。 ====デバッグ==== pdbモジュールを使うとよい。 <file> import pdb </file> pdb.set_trace()した行からデバッグが始まる。 ^コマンド^説明^ |l|コード確認| |s|現在の行を実行。次の関数の前で止まる| |p var|変数varの中身を確認| ====Numpy==== 数値の操作をするためのpythonのモジュール ===array=== Numpyの配列は2次元から。つまり、一次元配列には"縦"と"横"がある。 ^関数^説明^ |.shape|配列(テンソル)の形状を確認できる| |.flatten()|"横"1次元配列になる| |.concatenate() | 既存の次元に対して結合| |.stack() | 新たな次元を作って結合| ===hist=== a,b,c=hist a=value of each bin, b=bin ====2軸plot==== <code> run_index = 0 fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax2.plot(histories2[run_index].history['lr'],label='learning rate',linestyle='--',color='green') ax1.plot(histories2[run_index].history['loss'],label='training loss') ax1.plot(histories2[run_index].history['val_loss'],label='validation loss') plt.title('1st iteration, step 1, batch : 8192 lr : 1e-6, 1st trials') ax1.set_xlabel('epoch') ax1.set_ylabel('Loss') ax2.set_ylabel('Learning Rate') handler1, label1 = ax1.get_legend_handles_labels() handler2, label2 = ax2.get_legend_handles_labels() ax1.legend(handler1 + handler2, label1 + label2) #plt.legend() plt.figure() </code> ====機械学習==== ===tensorflow=== 機械学習のためのモジュール。 installの手順 <file> $ wget https://github.com/apple/tensorflow_macos/releases/download/v0.1alpha2/tensorflow_macos-0.1alpha2.tar.gz $ tar xvzf tensorflow_macos-0.1alpha2.tar.gz $ env="$HOME/miniforge3/envs/python38" $ libs="$PWD/tensorflow_macos/arm64/" $ pip install --upgrade -t "$env/lib/python3.8/site-packages/" --no-dependencies --force "$libs/grpcio-1.33.2-cp38-cp38-macosx_11_0_arm64.whl" $ pip install --upgrade -t "$env/lib/python3.8/site-packages/" --no-dependencies --force "$libs/h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl" $ pip install --upgrade -t "$env/lib/python3.8/site-packages/" --no-dependencies --force "$libs/tensorflow_addons_macos-0.1a2-cp38-cp38-macosx_11_0_arm64.whl" $ conda install -c conda-forge -y absl-py $ conda install -c conda-forge -y astunparse $ conda install -c conda-forge -y gast $ conda install -c conda-forge -y opt_einsum $ conda install -c conda-forge -y termcolor $ conda install -c conda-forge -y typing_extensions $ conda install -c conda-forge -y wheel $ conda install -c conda-forge -y typeguard $ pip install wrapt flatbuffers tensorflow_estimator google_pasta keras_preprocessing protobuf $ pip install tensorboard $ pip install --upgrade -t "$env/lib/python3.8/site-packages/" --no-dependencies --force "$libs/tensorflow_macos-0.1a2-cp38-cp38-macosx_11_0_arm64.whl" </file> バージョンが確認できれば成功 <file> $ python >>> import tensorflow as tf >>> tf.__version__ '2.4.0-rc0' </file> ====Condaの使い方==== 環境の複製 <code> conda create --name new_environment_name --clone existing_environment_name </code> 環境の削除 <code> conda env remove --name myenv </code>
プログラム/python.txt
· 最終更新: 2025/08/14 09:23 by
kawaue
ページ用ツール
文書の表示
以前のリビジョン
バックリンク
文書の先頭へ