建议使用 virtualenv 安装。virtualenv 是一个和其它 Python 项目开发隔离的虚拟 Python 环境,在同一台机器上不会干扰也不会被其它程序影响。virtualenv 安装过程中,你不仅仅安装了 TensorFlow 还有它的所有依赖包。(事实上这很简单)要开始使用 TensorFlow,你需要“启动” virtualenv 环境。总而言之,virtualenv 提供了一个安全可靠的 TensorFlow 安装和运行机制。
1、通过终端pip命令安装:
sudo pip install --upgrade virtualenv
2、执行以下任一命令创建虚拟环境:
virtualenv --system-site-packages targetDirectory # for Python 2.7
virtualenv --system-site-packages -p python3 targetDirectory # for Python 3.n
targetDirectory 因虚拟环境根路径而异,我们的命令假使 targetDirectory 是 ~/tensorflow,但你可以选择任一目录。
本机在执行创建虚拟环境时报错:
unning virtualenv with interpreter /System/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
Using base prefix '/System/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/fangzhongming/Documents/python/tensorflow/bin/python3
Also creating executable in /Users/fangzhongming/Documents/python/tensorflow/bin/python
ERROR: The executable /Users/fangzhongming/Documents/python/tensorflow/bin/python3 is not functioning
ERROR: It thinks sys.prefix is '/System/Library/Frameworks/Python.framework/Versions/3.6' (should be '/Users/fangzhongming/Documents/python/tensorflow')
ERROR: virtualenv is not compatible with this system or executable
找了好久原因,才发现是在上一篇文章《mac python从2.7版本升级至3.6》中将python从2.7升级到3.6时,将Library/Frameworks/Python.framework/Versions/3.6整个移到了/System/…中,导致无法成功,重新拷贝一份回去,成功!
3、执行命令,激活虚拟环境
$source ~/tensorflow/bin/activate
上面的 source 命令应该将提示符改成了下面这样:shell (tensorflow)$
注意,每打开一个新的 shell 使用 TensorFlow 都必须激活虚拟环境。
4、如果你不再使用 TensorFlow,可以通过下面命令退出环境:
(tensorflow)$ deactivate
5、卸载TensorFlow
如果你想卸载TensorFlow,直接删除上面创建的targetDirectory就行
$ rm -r ~/tensorflow
6、验证安装是否成功
开启一个终端,通过步骤3激活环境,在Terminal输入python,在交互式的shell窗口输入下面简单的程序
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
>>> print(sess.run(hello))
如果你看到下面的输出就表示安装成功了,可以开始学习TensorFlow了
Hello, TensorFlow!
7、本机进行import tensorflow as tf 时,报错:
>>> import tensorflow as tf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tensorflow'
需要在虚拟环境下安装tensorflow
pip install --upgrade tensorflow