= 機械学習環境を個人用PCにセットアップする = [[PageOutline]] 加速器機械学習フォーラムでの話題がきっかけで書きました。 初心者向けの環境構築の一例として活用いただけますと幸いです。 このセットアップ手順はWindowsPCで簡単に環境を構築する例となっていますが、WSL2を除けばUbuntu環境や多くのLinux環境でそのまま使えるはずです。その場合はpython3のところから読んでください。 概略 * WSL2+Ubuntuをインストール * python3をソースからインストール * venv 設定 * !TensorFlow インストール、動作確認 * !PyTorch インストール、動作確認 == WSL2のインストール == 最初に__管理者権限で__コマンドプロンプトを開く。wslコマンドで、インストール可能なディストリビューションを検索・確認する。 (wslコマンドが無い場合は、適当にGoogleで検索してください) {{{ C:\>wsl --list --online インストールできる有効なディストリビューションの一覧を次に示します。 'wsl --install -d ' を使用してインストールします。 NAME FRIENDLY NAME Ubuntu Ubuntu Debian Debian GNU/Linux kali-linux Kali Linux Rolling Ubuntu-18.04 Ubuntu 18.04 LTS Ubuntu-20.04 Ubuntu 20.04 LTS Ubuntu-22.04 Ubuntu 22.04 LTS OracleLinux_7_9 Oracle Linux 7.9 OracleLinux_8_7 Oracle Linux 8.7 OracleLinux_9_1 Oracle Linux 9.1 SUSE-Linux-Enterprise-Server-15-SP4 SUSE Linux Enterprise Server 15 SP4 openSUSE-Leap-15.4 openSUSE Leap 15.4 openSUSE-Tumbleweed openSUSE Tumbleweed }}} [[Image(wsl_install1.png, 40%)]] ここではUbuntu22.04をインストールすることにする。 {{{ C:\>wsl --install --d Ubuntu-22.04 インストール中: Ubuntu 22.04 LTS Ubuntu 22.04 LTS はインストールされました。 Ubuntu 22.04 LTS を起動しています... }}} 自動的にUbuntuのターミナルが起動して、ユーザー名を入れるプロンプトが出るので、ユーザー名とパスワードを設定する。 (最初は少し時間がかかるかもしれない) {{{ Installing, this may take a few minutes... Please create a default UNIX user account. The username does not need to match your Windows username. For more information visit: https://aka.ms/wslusers Enter new UNIX username: obina New password: Retype new password: passwd: password updated successfully Installation successful! To run a command as administrator (user "root"), use "sudo ". See "man sudo_root" for details. Welcome to Ubuntu 22.04.2 LTS (GNU/Linux 5.10.60.1-microsoft-standard-WSL2 x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage This message is shown once a day. To disable it please create the /home/obina/.hushlogin file. obina@notepc:~$ }}} [[Image(wsl_install2.png, 40%)]] いちおう確認 {{{ obina@notepc:~$ cat /etc/os-release PRETTY_NAME="Ubuntu 22.04.2 LTS" NAME="Ubuntu" VERSION_ID="22.04" VERSION="22.04.2 LTS (Jammy Jellyfish)" VERSION_CODENAME=jammy ID=ubuntu ID_LIKE=debian HOME_URL="https://www.ubuntu.com/" SUPPORT_URL="https://help.ubuntu.com/" BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" UBUNTU_CODENAME=jammy obina@notepc:~$ uname -a Linux notepc 5.10.60.1-microsoft-standard-WSL2 #1 SMP Wed Aug 25 23:20:18 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux }}} パッケージのアップデート。先ほど入力したパスワードを入れる {{{ obina@notepc:~$ sudo apt update Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB] ..... Fetched 26.5 MB in 6s (4327 kB/s) Reading package lists... Done Building dependency tree... Done Reading state information... Done 19 packages can be upgraded. Run 'apt list --upgradable' to see them. }}} {{{ obina@notepc:~$ sudo apt upgrade Reading package lists... Done Building dependency tree... Done Reading state information... Done Calculating upgrade... Done The following packages will be upgraded: apt apt-utils distro-info-data git git-man libapt-pkg6.0 libglib2.0-0 libglib2.0-bin libglib2.0-data libssl3 libxml2 openssl tzdata ubuntu-advantage-tools vim vim-common vim-runtime vim-tiny xxd 19 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. 10 standard LTS security updates Need to get 21.9 MB of archives. After this operation, 348 kB of additional disk space will be used. Do you want to continue? [Y/n] Y .... obina@notepc:~$ }}} [[Image(wsl_install3.png, 40%)]] とりあえずここまでで十分。 == python3インストール == 今回はpython公式サイトから、現時点(2023/05)の最新版であるPython3.11.3を入れる。 機械学習環境を構築する目的からは必ずしも最新版が良いとは限らない(ときどき最新バージョンに対応できていないことがある)が、今回はこれで問題なさそう。 あらかじめインストール先として /opt/python/3.11.3 を作成しておく。 ownerを自分に設定することで、後の作業は一般ユーザー権限で行う。 {{{ obina@notepc:~$ cd /opt obina@notepc:/opt$ ls obina@notepc:/opt$ sudo mkdir python obina@notepc:/opt$ sudo chown obina:obina python obina@notepc:/opt$ cd python obina@notepc:/opt/python$ mkdir 3.11.3 obina@notepc:/opt/python$ ls 3.11.3 }}} ホームディレクトリに戻って、作業用のディレクトリ作成。ソースをダウンロード。URLは上の公式サイトから最新のモノを探す。今回の場合は以下の通りとなった。 {{{ obina@notepc:~$ mkdir work obina@notepc:~$ cd work obina@notepc:~/work$ wget https://www.python.org/ftp/python/3.11.3/Python-3.11.3.tgz --2023-05-09 20:11:15-- https://www.python.org/ftp/python/3.11.3/Python-3.11.3.tgz Resolving www.python.org (www.python.org)... 151.101.108.223, 2a04:4e42:1a::223 Connecting to www.python.org (www.python.org)|151.101.108.223|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 26455738 (25M) [application/octet-stream] Saving to: ‘Python-3.11.3.tgz’ Python-3.11.3.tgz 100%[=================================================>] 25.23M 19.5MB/s in 1.3s 2023-05-09 20:11:17 (19.5 MB/s) - ‘Python-3.11.3.tgz’ saved [26455738/26455738] }}} configureでインストール先として /opt/python/3.11.3 を指定する。 lto (Link time optimization) はリンク時間が長くなる替わりに実行速度が上がる...らしい。(自分では未検証) {{{ obina@notepc:~/work$ tar xvfz Python-3.11.3.tgz obina@notepc:~/work$ cd Python-3.11.3/ obina@notepc:~/work/Python-3.11.3$ ls Doc LICENSE Makefile.pre.in Objects Parser README.rst config.guess configure.ac setup.py Grammar Lib Misc PC Programs Tools config.sub install-sh Include Mac Modules PCbuild Python aclocal.m4 configure pyconfig.h.in obina@notepc:~/work/Python-3.11.3$ ./configure --prefix=/opt/python/3.11.3 --enable-optimizations --with-lto obina@notepc:~/work/Python-3.11.3$ make -j8 # 並列化の数はCPU数に応じて適当に .... obina@notepc:~/work/Python-3.11.3$ make install .... }}} 環境設定用のスクリプトを作成。WSLの場合はユーザーが自分だけなので~/.bashrcに直接書いても良いのだが、今後pythonのバージョンによって切り分けたいこともあると思うので/opt/python以下につくっておく {{{ $ vi /opt/python/setup_py3.11.3.sh export PATH=/opt/python/3.11.3/bin:$PATH }}} 念のため確認. 上のスクリプトを source する前後で使うpythonをチェック。 {{{ obina@notepc:~$ which python3 /usr/bin/python3 obina@notepc:~$ source /opt/python/3.11.3/setup_py3.11.3.sh obina@notepc:~$ which python3 /opt/python/3.11.3/bin/python3 }}} 問題ない。 {{{ obina@notepc:~$ which pip3 /opt/python/3.11.3/bin/pip3 obina@notepc:~$ obina@notepc:~$ pip3 list Package Version ---------- ------- pip 22.3.1 setuptools 65.5.0 [notice] A new release of pip available: 22.3.1 -> 23.1.2 [notice] To update, run: pip3 install --upgrade pip }}} pip3を確認して、アップデートする {{{ obina@notepc:~$ pip3 install --upgrade pip Requirement already satisfied: pip in /opt/python/3.11.3/lib/python3.11/site-packages (22.3.1) Collecting pip Downloading pip-23.1.2-py3-none-any.whl (2.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 1.8 MB/s eta 0:00:00 Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 22.3.1 Uninstalling pip-22.3.1: Successfully uninstalled pip-22.3.1 Successfully installed pip-23.1.2 }}} これで基本環境はOK。次はvenvを使って個別のパッケージを入れていく。 == venv 設定 == 次にTensorFlowやPyTorchを入れていく。それぞれでnumpyのバージョンなど、要求されるものが異なることが多いため別の仮想環境を作る方が良い。 ここではvenvを使うのでその設定を行う 基本方針: ホームディレクトリ直下に ".venv" というディレクトリを作成。 ~/.venv/以下に個別の仮想環境用のディレクトリを作成していく。 例えば - TensorFlow用は ~/.venv/tf2.12 - PyTorch用は ~/.venv/torch2.0 のような感じでディレクトリを作っていく 仮にあとで仮想環境を消したいときにはディレクトリ(上の例ではtf2.12とかtorch2.0とか)を削除すれば良いだけ。実際には.venvの下に作る必要はなく、どのディレクトリでも良いし隠しディレクトリである必然性も無いが、慣例に従う。 python.jpサイトの仮想環境構築ガイド - [windows](https://www.python.jp/install/windows/venv.html) - [ubuntu](https://www.python.jp/install/ubuntu/virtualenv.html) === !TensorFlow 用のvenv環境準備 === まずはTensorFlowのバージョンを確認 [tensorflow・PyPI](https://pypi.org/project/tensorflow/) をみると、python3.11に対応したTF2.12.0があることがわかる → venv名称をtf2.12とする方針とする ファイル名を確認する https://pypi.org/project/tensorflow/#files をみると、 tensorflow-2.12.0-cp311-cp311-manylinux_2_17_x86_64....whl というファイルがあるのでCPython3.11に対応しているようだ。 使用するpythonの場所が/opt以下であることを確認してから、venvを構築。このときに指定する名前がプロンプトの先頭に付くので、あまり長い名前を付けると面倒かもしれない(jupyter notebookを使うことが前提ならあまり気にならないが) {{{ obina@notepc:~$ which python3 /opt/python/3.11.3/bin/python3 obina@notepc:~$ python3 -m venv ~/.venv/tf2.12 }}} 念のためディレクトリを確認 {{{ obina@notepc:~$ ls ~/.venv/tf2.12/ bin include lib lib64 pyvenv.cfg obina@notepc:~$ ls ~/.venv/tf2.12/bin/ Activate.ps1 activate activate.csh activate.fish pip pip3 pip3.11 python python3 python3.11 }}} 仮想環境を起動; これ以降はプロンプトの先頭に (tf2.12)が付く {{{ obina@notepc:~$ source ~/.venv/tf2.12/bin/activate (tf2.12) obina@notepc:~$ }}} 終了するのは"deactivate"コマンドで良い {{{ (tf2.12) obina@notepc:~$ which python3 /home/obina/.venv/tf2.12/bin/python3 (tf2.12) obina@notepc:~$ which pip /home/obina/.venv/tf2.12/bin/pip (tf2.12) obina@notepc:~$ deactivate obina@notepc:~$ obina@notepc:~$ which python3 /opt/python/3.11.3/bin/python3 }}} == !TensorFlow インストール == 例によって(念のため)使うpip確認しておく {{{ obina@notepc:~$ source ~/.venv/tf2.12/bin/activate # venv環境を開始 (tf2.12) obina@notepc:~$ which pip3 /home/obina/.venv/tf2.12/bin/pip3 (tf2.12) obina@notepc:~$ pip3 install --upgrade pip # pipの更新 ..... Successfully installed pip-23.1.2 (tf2.12) obina@notepc:~$ pip3 list Package Version ---------- ------- pip 23.1.2 setuptools 65.5.0 (tf2.12) obina@notepc:~$ pip3 install tensorflow ..... Successfully installed MarkupSafe-2.1.2 absl-py-1.4.0 astunparse-1.6.3 cachetools-5.3.0 certifi-2023.5.7 charset-normalizer-3.1.0 flatbuffers-23.3.3 gast-0.4.0 google-auth-2.17.3 google-auth-oauthlib-1.0.0 google-pasta-0.2.0 grpcio-1.54.0 h5py-3.8.0 idna-3.4 jax-0.4.8 keras-2.12.0 libclang-16.0.0 markdown-3.4.3 ml-dtypes-0.1.0 numpy-1.23.5 oauthlib-3.2.2 opt-einsum-3.3.0 packaging-23.1 protobuf-4.23.0 pyasn1-0.5.0 pyasn1-modules-0.3.0 requests-2.30.0 requests-oauthlib-1.3.1 rsa-4.9 scipy-1.10.1 six-1.16.0 tensorboard-2.12.3 tensorboard-data-server-0.7.0 tensorflow-2.12.0 tensorflow-estimator-2.12.0 tensorflow-io-gcs-filesystem-0.32.0 termcolor-2.3.0 typing-extensions-4.5.0 urllib3-2.0.2 werkzeug-2.3.4 wheel-0.40.0 wrapt-1.14.1 (tf2.12) obina@notepc:~$ }}} これだけでOK.次に動作確認は公式サイトにあるコマンドで、 {{{ (tf2.12) obina@notepc:~$ python3 Python 3.11.3 (main, May 9 2023, 20:29:30) [GCC 11.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> import tensorflow as tf ....(((いろいろとwarning))).... >>> >>> print(tf.reduce_sum(tf.random.normal([1000, 1000]))) tf.Tensor(-182.7671, shape=(), dtype=float32) >>> print(tf.reduce_sum(tf.random.normal([1000, 1000]))) tf.Tensor(-268.51474, shape=(), dtype=float32) }}} とりあえず動く。 もう1つ、kereasを使ったサンプル。 https://www.tensorflow.org/tutorials/quickstart/beginner をそのまま実行 {{{ import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5) model.evaluate(x_test, y_test) }}} 評価結果をみる {{{ >>> model.evaluate(x_test, y_test) 313/313 [==============================] - 0s 778us/step - loss: 0.0758 - accuracy: 0.9757 [0.07577536255121231, 0.9757000207901001] }}} ちゃんと学習出来ているので、インストール自体は問題なさそう。 === Jupyter Notebook, ipython のセットアップ === 次に、利便性のためにipythonやjupyter notebookを入れておく; 依存関係もあるがまとめてnotebookを入れるのが簡単。詳しくは https://jupyter.org/install を参照。 {{{ (tf2.12) obina@notepc:~$ pip3 install notebook .... (tf2.12) obina@notepc:~$ which ipython3 /home/obina/.venv/tf2.12/bin/ipython3 (tf2.12) obina@notepc:~$ (tf2.12) obina@notepc:~$ ipython3 --nosep Python 3.11.3 (main, May 9 2023, 20:29:30) [GCC 11.3.0] Type 'copyright', 'credits' or 'license' for more information IPython 8.13.2 -- An enhanced Interactive Python. Type '?' for help. In [1]: }}} 問題なし。 ノートブックの起動。デフォルトではOS内のブラウザを立ち上がようとしてしまうので、--no-browserオプションを付けて起動し、Windows側のブラウザで接続する。 {{{ (tf2.12) obina@notepc:~$ jupyter notebook --no-browser [I 21:30:41.014 NotebookApp] Writing notebook server cookie secret to /home/obina/.local/share/jupyter/runtime/notebook_cookie_secret _ _ _ _ | | | |_ __ __| |__ _| |_ ___ | |_| | '_ \/ _` / _` | _/ -_) \___/| .__/\__,_\__,_|\__\___| |_| Read the migration plan to Notebook 7 to learn about the new features and the actions to take if you are using extensions. https://jupyter-notebook.readthedocs.io/en/latest/migrate_to_notebook7.html Please note that updating to Notebook 7 might break some of your extensions. [I 21:30:41.133 NotebookApp] Serving notebooks from local directory: /home/obina [I 21:30:41.133 NotebookApp] Jupyter Notebook 6.5.4 is running at: [I 21:30:41.133 NotebookApp] http://localhost:8888/?token=50b97522fe665b6862193efe85be7fe5c703dcbe13116e45 [I 21:30:41.133 NotebookApp] or http://127.0.0.1:8888/?token=50b97522fe665b6862193efe85be7fe5c703dcbe13116e45 [I 21:30:41.133 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 21:30:41.135 NotebookApp] To access the notebook, open this file in a browser: file:///home/obina/.local/share/jupyter/runtime/nbserver-19189-open.html Or copy and paste one of these URLs: http://localhost:8888/?token=50b97522fe665b6862193efe85be7fe5c703dcbe13116e45 or http://127.0.0.1:8888/?token=50b97522fe665b6862193efe85be7fe5c703dcbe13116e45 }}} と出るので、Windowsで起動したブラウザに上のURLを貼り付ける。ブラウザで動くことを確認。たとえばこんな感じで。 [[Image(wsl_python_notebook1.png, 30%)]] ※ Notebook 7 なるものがあるとは知らなかった.... 上のコマンドではmatplotlibが入らなかったので、手動で入れた。plotlyやseabornはお好みで。 {{{ (tf2.12) obina@notepc:~$ pip install matplotlib }}} 参考のため、pip list 確認(pip freeze 結果ファイルはこちら) {{{ (tf2.12) obina@notepc:~$ pip list Package Version ---------------------------- -------- absl-py 1.4.0 anyio 3.6.2 argon2-cffi 21.3.0 argon2-cffi-bindings 21.2.0 arrow 1.2.3 asttokens 2.2.1 astunparse 1.6.3 attrs 23.1.0 backcall 0.2.0 beautifulsoup4 4.12.2 bleach 6.0.0 cachetools 5.3.0 certifi 2023.5.7 cffi 1.15.1 charset-normalizer 3.1.0 comm 0.1.3 contourpy 1.0.7 cycler 0.11.0 debugpy 1.6.7 decorator 5.1.1 defusedxml 0.7.1 executing 1.2.0 fastjsonschema 2.16.3 flatbuffers 23.3.3 fonttools 4.39.3 fqdn 1.5.1 gast 0.4.0 google-auth 2.17.3 google-auth-oauthlib 1.0.0 google-pasta 0.2.0 grpcio 1.54.0 h5py 3.8.0 idna 3.4 ipykernel 6.23.0 ipython 8.13.2 ipython-genutils 0.2.0 isoduration 20.11.0 jax 0.4.8 jedi 0.18.2 Jinja2 3.1.2 jsonpointer 2.3 jsonschema 4.17.3 jupyter_client 8.2.0 jupyter_core 5.3.0 jupyter-events 0.6.3 jupyter_server 2.5.0 jupyter_server_terminals 0.4.4 jupyterlab-pygments 0.2.2 keras 2.12.0 kiwisolver 1.4.4 libclang 16.0.0 Markdown 3.4.3 MarkupSafe 2.1.2 matplotlib 3.7.1 matplotlib-inline 0.1.6 mistune 2.0.5 ml-dtypes 0.1.0 nbclassic 1.0.0 nbclient 0.7.4 nbconvert 7.4.0 nbformat 5.8.0 nest-asyncio 1.5.6 notebook 6.5.4 notebook_shim 0.2.3 numpy 1.23.5 oauthlib 3.2.2 opt-einsum 3.3.0 packaging 23.1 pandocfilters 1.5.0 parso 0.8.3 pexpect 4.8.0 pickleshare 0.7.5 Pillow 9.5.0 pip 23.1.2 platformdirs 3.5.0 prometheus-client 0.16.0 prompt-toolkit 3.0.38 protobuf 4.23.0 psutil 5.9.5 ptyprocess 0.7.0 pure-eval 0.2.2 pyasn1 0.5.0 pyasn1-modules 0.3.0 pycparser 2.21 Pygments 2.15.1 pyparsing 3.0.9 pyrsistent 0.19.3 python-dateutil 2.8.2 python-json-logger 2.0.7 PyYAML 6.0 pyzmq 25.0.2 requests 2.30.0 requests-oauthlib 1.3.1 rfc3339-validator 0.1.4 rfc3986-validator 0.1.1 rsa 4.9 scipy 1.10.1 Send2Trash 1.8.2 setuptools 65.5.0 six 1.16.0 sniffio 1.3.0 soupsieve 2.4.1 stack-data 0.6.2 tensorboard 2.12.3 tensorboard-data-server 0.7.0 tensorflow 2.12.0 tensorflow-estimator 2.12.0 tensorflow-io-gcs-filesystem 0.32.0 termcolor 2.3.0 terminado 0.17.1 tinycss2 1.2.1 tornado 6.3.1 traitlets 5.9.0 typing_extensions 4.5.0 uri-template 1.2.0 urllib3 2.0.2 wcwidth 0.2.6 webcolors 1.13 webencodings 0.5.1 websocket-client 1.5.1 Werkzeug 2.3.4 wheel 0.40.0 wrapt 1.14.1 }}} 再掲:venv環境を抜けるのはdeactivate コマンドで終了するか、システムから抜ける。 == !PyTorch インストール == 次にPyTorchを入れていく。やはり公式サイトからスタート https://pytorch.org/get-started/locally/ PyTorchのOSやバージョン、GPUの有無などを選択。 [[Image(wsl_python_torch1.png, 40%)]] ここではGPUが無い環境なので {{{ PyTorch Build: Stable(2.0.1) Your OS: Linux Package: Pip Language: Python Compute Platform: CPU }}} を選択する。コマンドは {{{ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu }}} となったので、これをいれる。 まずは venv として設定するときのバージョンは2.0.1とする。 最初にどのpythonを使っているのかを確認してから。 {{{ obina@notepc:~$ which python3 /opt/python/3.11.3/bin/python3 obina@notepc:~$ python3 -m venv ~/.venv/torch2.0 obina@notepc:~$ source ~/.venv/torch2.0/bin/activate (torch2.0) obina@notepc:~$ }}} ここからは先ほどと同様にpipの更新を行った後で、torch入れる。 {{{ (torch2.0) obina@notepc:~$ which pip /home/obina/.venv/torch2.0/bin/pip (torch2.0) obina@notepc:~$ pip install --upgrade pip .... Successfully installed pip-23.1.2 (torch2.0) obina@notepc:~$ (torch2.0) obina@notepc:~$ pip list Package Version ---------- ------- pip 23.1.2 setuptools 65.5.0 (torch2.0) obina@notepc:~$ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu .... Installing collected packages: mpmath, urllib3, typing-extensions, sympy, pillow, numpy, networkx, MarkupSafe, idna, filelock, charset-normalizer, certifi, requests, jinja2, torch, torchvision, torchaudio Successfully installed MarkupSafe-2.1.2 certifi-2022.12.7 charset-normalizer-2.1.1 filelock-3.9.0 idna-3.4 jinja2-3.1.2 mpmath-1.2.1 networkx-3.0 numpy-1.24.1 pillow-9.3.0 requests-2.28.1 sympy-1.11.1 torch-2.0.1+cpu torchaudio-2.0.2+cpu torchvision-0.15.2+cpu typing-extensions-4.4.0 urllib3-1.26.13 }}} 動作確認 {{{ (torch2.0) obina@notepc:~$ python Python 3.11.3 (main, May 9 2023, 20:29:30) [GCC 11.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> >>> import torch >>> x = torch.rand(5,3) >>> print(x) tensor([[0.1193, 0.9816, 0.3111], [0.8966, 0.0651, 0.5655], [0.5590, 0.1083, 0.6464], [0.7477, 0.3680, 0.5885], [0.8389, 0.1438, 0.8069]]) >>> }}} 問題無さそう。あとはチュートリアルから適当に選んで動作確認すれば良い。 https://pytorch.org/tutorials/beginner/basics/quickstart_tutorial.html この段階でのパッケージ一覧 {{{ (torch2.0) obina@notepc:~$ pip3 list Package Version ------------------ ---------- certifi 2022.12.7 charset-normalizer 2.1.1 filelock 3.9.0 idna 3.4 Jinja2 3.1.2 MarkupSafe 2.1.2 mpmath 1.2.1 networkx 3.0 numpy 1.24.1 Pillow 9.3.0 pip 23.1.2 requests 2.28.1 setuptools 65.5.0 sympy 1.11.1 torch 2.0.1+cpu torchaudio 2.0.2+cpu torchvision 0.15.2+cpu typing_extensions 4.4.0 urllib3 1.26.13 }}} あとはjupyter notebook, matplotlib, plotly, seabornなど、お好みで。 お手軽に使うには ax-platformを入れるのも楽。 ※ PyTorchでは numpy 1.24.1, TensorFlowでは 1.23.5 を使用している ここでは、!BoTorch, Ax を入れる。notebook, matplotlibも。 {{{ (torch2.0) obina@notepc:~$ pip install botorch ax-platform (torch2.0) obina@notepc:~$ pip install notebook matplotlib }}} BoTorchのgetting startedを実行 https://botorch.org/docs/getting_started 乱数でデータを作成 {{{ import torch from botorch.models import SingleTaskGP from botorch.fit import fit_gpytorch_mll from gpytorch.mlls import ExactMarginalLogLikelihood train_X = torch.rand(10, 2) Y = 1 - (train_X - 0.5).norm(dim=-1, keepdim=True) # explicit output dimension Y += 0.1 * torch.rand_like(Y) train_Y = (Y - Y.mean()) / Y.std() }}} 続いてガウス過程モデル(SingleTaskGP)を定義し、周辺尤度最大化(ExactMarginalLongLikelihood) によってカーネルパラメータを推定します。 {{{ gp = SingleTaskGP(train_X, train_Y) mll = ExactMarginalLogLikelihood(gp.likelihood, gp) fit_gpytorch_mll(mll); }}} 獲得関数としてUCBを使う {{{ from botorch.acquisition import UpperConfidenceBound UCB = UpperConfidenceBound(gp, beta=0.1) }}} 最適化 {{{ from botorch.optim import optimize_acqf bounds = torch.stack([torch.zeros(2), torch.ones(2)]) candidate, acq_value = optimize_acqf( UCB, bounds=bounds, q=1, num_restarts=5, raw_samples=20, ) }}} 結果表示 {{{ print(candidate) }}} そのほか、簡単に確認するにはAxのサンプルを実行するのも良いだろう [Ax ・ Adaptive Experimentation Platform](https://ax.dev/) == 今後 == ここから先はまだ書いていない * GPU環境 (CUDA)でのセットアップ例 * GPyOptの使用例 * BOTorch, Axの使用例 * EPICS連携