在 Mac OS X 上安装 TensorFlow

建议使用 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值