我爱编程

2018.05.21-安装TensorFlow

2018-05-21  本文已影响0人  余番茄

根据TensorFlow官网的指引和推荐在macOS,使用Virtualenv安装:在 macOS 上安装 TensorFlow

1. 环境

macOS High Sierra:10.13.4

python: 2.7.15(系统自带)

2. 安装

2.1 安装Virtualenv

$ sudo easy_install pip

$ pip install --upgrade virtualenv

安装版本virtualenv-16.0.0

2.2 创建Virtualenv环境

$ virtualenv --system-site-packages /targetdir

“/targetdir”——指定创建tensorflow虚拟环境的根目录

创建成功后,在目录下会自动生成以下内容:

2.3 激活环境

创建tensorflow虚拟环境后,需要激活该环境。激活后,即可在该环境下运行tensorflow程序,或更新其他安装包。

$ cd /targetdir

$ source ./bin/activate

此时,终端提示符会变为:

(tensorflow) xxxx$

2.4 安装所需其他软件包

(tensorflow) xxxx$ pip install  --upgrade tensorflow

将 TensorFlow 及其需要的所有软件包安装到处于活动状态的 Virtualenv 环境。

2.5 使用

请注意,每次在新的终端中使用 TensorFlow 时,您都必须激活 tensorflow的Virtualenv环境。

用完 TensorFlow 后,可以通过发出以下命令来停用此环境:

(tensorflow) xxxx$ deactivate

2.6 验证

可用文本编辑器等工具编写以下python程序,保存为.py格式,来验证tensorflow是否安装成功。

import tensorflow as tf

hello = tf.constant('Hello, TensorFlow!')

sees = tf.Session()

print (sees.run(hello))

在终端上用python运行该程序,结果如下:

2018-05-21 12:49:54.361903: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA

Hello, TensorFlow!

程序成功运行,但有一个warning。在google找了下,这个warning的解释和处理:

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

简单解释下:

现代CPU除了常用的算术和逻辑,还提供许多低级指令,称为扩展,如SSE2、SSE4、AVX等。

实际上,AVX采用FMA操作,可加速线性方程计算,即点积、矩阵乘法、矩阵反转、卷积等。几乎每个机器学习训练都包括大量这些操作,因此如果CPU支持AVX和FMA,运算速度可以大大加快,最多3倍。

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA

这个warning表示我的CPU可以支持AVX2!!!(由于使用“pip install tensorflow”,安装的都是cpu only版本,这里也是针对CPU only版本)

为了兼容更多CPU,CPU only版本tensorflow默认使用无CPU扩展进行构建。另一个理由是即使CPU具有这些扩展,也会比GPU慢很多。

如果你已经有一个GPU,你可以不用关注这个AVX支持。

如果你没有一个GPU但想充分利用CPU,你可以针对你的CPU具有的AVX、AVX2和FMA扩展重新构建源码来优化。具体的构建方法在TensorFlow官网上有说明:

从源代码安装 TensorFlow


如果你不想扩展,保持tensorflow对CPU的兼容,可以在程序中加入以下代码直接屏蔽该告警:

import OS

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

上一篇 下一篇

猜你喜欢

热点阅读