Ubuntu系统---以virtualenv方式安装Tensorflow-CPU
一、安装环境
环境:Ubuntu18.04+CPU+python2.7
本文介绍:如何在ubuntu上以virtualenv方式安装tensorflow。
采用virtualenv方式安装的原因?系统中的多个python混用会导致$PYTHONPATH
混乱,或者各个工程对于package的版本要求不同等等情况。有一个简单的解决方案就是用virtualenv来隔离多个python,其本质只是实现隔离不同python中$PYTHONPATH
的路径,当然也可以衍生到隔离多个$PATH
。
二、安装步骤
2.1 准备
如果你有两个项目,一个需要python2.7
开发,一个需要python3.5
开发,那么virtualenv
是一个很好的选择。如果你想创建一个python2.7
和python3.5
的虚拟环境的话。首先你的电脑上得装有python2.7
和python3.5
,而且需要装好pip
和pip3
。
2.2 安装pip和virtualenv
# Ubuntu/Linux 64-bit
$ sudo apt-get install python-pip python-dev python-virtualenv
# Mac OS X
$ sudo easy_install pip
$ sudo pip install --upgrade virtualenv
2.3 创建 Virtualenv 虚拟环境
进入你想安装tensorflow的父目录下,然后执行下面命令建立虚拟环境:
$ cd TF-virtualenv
$ virtualenv --system-site-packages tensorflow
2.4 激活虚拟环境并安装tensorflow
对于python2.7,则执行如下命令:
$ source
.
/tensorflow/bin/activate
# If using bash
$ source
.
/tensorflow/bin/activate
.csh
# If using csh
(tensorflow)$
# Your prompt should change
# Ubuntu/Linux 64-bit, CPU only:
$ pip
install
--upgrade https:
//storage
.googleapis.com
/tensorflow/linux/cpu/tensorflow-0
.6.0-cp27-none-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled:
$ pip
install
--upgrade https:
//storage
.googleapis.com
/tensorflow/linux/gpu/tensorflow-0
.6.0-cp27-none-linux_x86_64.whl
# Mac OS X, CPU only:
$ pip
install
--upgrade https:
//storage
.googleapis.com
/tensorflow/mac/tensorflow-0
.6.0-py2-none-any.whl
对于python3则执行如下命令:
$ source
.
/tensorflow/bin/activate
# If using bash
$ source
.
/tensorflow/bin/activate
.csh
# If using csh
(tensorflow)$
# Your prompt should change
# Ubuntu/Linux 64-bit, CPU only:
$ pip3
install
--upgrade https:
//storage
.googleapis.com
/tensorflow/linux/cpu/tensorflow-0
.6.0-cp34-none-linux_x86_64.whl
# Ubuntu/Linux 64-bit, GPU enabled:
$ pip3
install
--upgrade https:
//storage
.googleapis.com
/tensorflow/linux/gpu/tensorflow-0
.6.0-cp34-none-linux_x86_64.whl
# Mac OS X, CPU only:
$ pip3
install
--upgrade https:
//storage
.googleapis.com
/tensorflow/mac/tensorflow-0
.6.0-py3-none-any.whl
2.4 验证Tensorflow CPU版本
在终端执行如下命令进入python shell环境:
$ cd TF-virtualenv
$
cd
tensorflow
$
python
>>>
import
tensorflow as tf
>>> hello
=
tf.constant(
'Hello, TensorFlow!'
)
>>> sess
=
tf.Session()
>>>
print
(sess.run(hello))
Hello, TensorFlow!
>>> a
=
tf.constant(
10
)
>>> b
=
tf.constant(
32
)
>>>
print
(sess.run(a
+
b))
总结使用过程:
2.4.1 virtualenv中激活tensorflow
当环境创建好了,我们必须在每次使用tensorflow时激活它。
$ source ~/tensorflow/bin/activate
在同一个环境中,这意味着你会在你的shell中看到它。
(tensorflow)$
2.4.2 使用tensorflow
键入python和下面的python代码。
python
# Python
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
这是我的结果。虽然它与官方验证结果不同,但是应该没问题。
>>> print(sess.run(hello)) b'Hello, TensorFlow!' >>>也可以, 使用类似命令运行 TensorFlow 程序:
退出Python环境
>>> exit()
(tensorflow)$ cd tensorflow/models/image/mnist
(tensorflow)$ python convolutional.py
2.4.3 停用virtualenv
# 当使用完 TensorFlow
(tensorflow)$ deactivate # 停用 virtualenv
$ # 你的命令提示符会恢复原样