2018年6月26日 星期二

[Python/Package] macOS安裝keras與TensorFlow(搭配Virtualenv與jupyter notebook)

前言:
Keras與TensorFlow都是machine learning的套件,
Keras較適合入門,並可選擇run在TensorFlow、CNTK或Theano上。
該例使用Python 3,另TensorFlow website推薦macOS在10.12.6(Sierra)或以上。

安裝步驟:
打開Terminal,打指令:
virtualenv --system-site-packages -p python3 targetDirectory

~/keras代表在使用者下建立keras資料夾。

接著打指令:
cd targetDirectory

再來打指令:
$ source ./bin/activate # If using bash, sh, ksh, or zsh

繼續打指令:
(targetDirectory)$ pip3 install --upgrade keras # for Python 3.n
(targetDirectory)$ pip3 install --upgrade tensorflow # for Python 3.n


此時已將keras跟TensorFlow安裝在Virtualenv內了。
安裝後,可以做個簡單的測試,是否有成功安裝:
(targetDirectory)$ python
(targetDirectory)$ import tensorflow as tf



執行import後,沒有錯誤訊息,代表有安裝進去。
最後在Virtualenv安裝jupyter notebook的kernel:
(targetDirectory)$ pip3 install ipykernel
(targetDirectory)$ python -m ipykernel install --user --name=virtualenv-name


最後,啟動jupyter notebook:
(targetDirectory)$ jupyter notebook
點選jupyter notebook主畫面右上角的New,選擇剛建立在Virtualenv的kernel即可:



最後,執行畫面如下 :


參考資料:
https://www.tensorflow.org/install/install_mac
https://stackoverflow.com/questions/42449814/running-jupyter-notebook-in-a-virtualenv-installed-sklearn-module-not-available