在之前的文章介紹了如何在Docker安裝Tensorflow和運行代碼,但是遇到的問題也很顯著,我們編寫的代碼沒有無法直觀看到靜態(tài)錯誤,無法得知語法是否錯誤,必須運行過后才可以看到,同時也無法Debug代碼。PyCharm是一個非常給力的Python開發(fā)工具,提供代碼提示、代碼靜態(tài)錯誤提示,還有Debug等功能。所以在我們的Mac環(huán)境安裝Tensorflow是很有必要的。
我是使用官網(wǎng)推薦的Virtualenv方式,基于Python 2.7。
安裝步驟
- 啟動一個終端(即一個 shell)
- 通過發(fā)出以下命令來安裝 pip 和 Virtualenv
$ sudo easy_install pip
$ pip install --upgrade virtualenv
- 通過使用以下命令來創(chuàng)建一個 Virtualenv 環(huán)境:
$ virtualenv --system-site-packages targetDirectory
激活 Virtualenv 環(huán)境
- 通過以下命令來激活該 Virtualenv 環(huán)境:
$ cd targetDirectory
$ source ./bin/activate
執(zhí)行上述 source 命令后,您的提示符應(yīng)該會變成如下內(nèi)容:
(targetDirectory)$
- 確保已安裝了 pip 8.1 版或更高版本:
(targetDirectory)$ easy_install -U pip
- 發(fā)出以下某個命令,將 TensorFlow 及其需要的所有軟件包安裝到處于活動狀態(tài)的 Virtualenv 環(huán)境中:
(targetDirectory)$ pip install --upgrade tensorflow
當(dāng) Virtualenv 環(huán)境處于活動狀態(tài)時,您就可以從該 shell 運行 TensorFlow 程序了。
用完 TensorFlow 后,可以通過發(fā)出以下命令來停用此環(huán)境:
(targetDirectory)$ deactivate
驗證安裝環(huán)境:運行一個簡短的 TensorFlow 程序
從 shell 中調(diào)用 Python,如下所示:
$ python
在 Python 交互式 shell 中輸入以下幾行簡短的程序代碼:
# Python
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
如果系統(tǒng)輸出以下內(nèi)容,則說明您可以開始編寫 TensorFlow 程序了:
Hello, TensorFlow!
配置PyCharm開發(fā)環(huán)境
PyCharm的安裝教程這里就不再介紹了,自行Google,很簡單。PyCharm已經(jīng)集成了VirtualEnv,在PyCharm即可快速的創(chuàng)建出虛擬環(huán)境并用于開發(fā)。
- 執(zhí)行命令輸出Python在Virtualenv的路徑,一會兒需要用到
(targetDirectory)$ which python
/Users/Wiki/targetDirectory/bin/python
-
創(chuàng)建Python項目
image.png -
進(jìn)入
Preferences菜單,選擇對于的項目的選項Project Interpreter,
image.png



- 運行代碼:HelloWorld
通過步驟3,那么環(huán)境就已經(jīng)配置好了,創(chuàng)建一個hello.py的文件,輸入以下代碼:
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
右擊Run 'hello',或者點擊右上角的按鈕,就完成運行了。


