TensorFlow 介绍及安装

来源:互联网 发布:什么是淘宝旺旺号啊 编辑:程序博客网 时间:2024/05/18 02:29

深度学习框架对比:https://en.wikipedia.org/wiki/Comparison_of_deep_learning_software
知乎问答:https://www.zhihu.com/question/41667903?from=profile_question_card

综述

TensorFlow 是一个编程系统, 使用图来表示计算任务. 图中的节点被称之为 op(operation 的缩写). 一个 op获得 0 个或多个 Tensor , 执行计算, 产生 0 个或多个Tensor . 每个 Tensor 是一个类型化的多维数组. 例如, 你可以将一小组图像集表示为一个四维浮点数数组, 这四个维度分别是 [batch, height, width, channels] .一个 TensorFlow 图描述了计算的过程. 为了进行计算, 图必须在 会话 里被启动. 会话 将图的op 分发到诸如 CPU 或 GPU 之类的 设备 上, 同时提供执行 op 的方法. 这些方法执行后, 将产生的 tensor 返回. 在 Python 语言中, 返回的 tensor 是 numpy ndarray 对象; 在 C和 C++ 语言中, 返回的 tensor 是 tensorflow::Tensor 实例.

张量tensor

一个张量就是一个N维数组。

0维的张量就是标量,数字1维的张量就是向量,[1,2,3]2维度的张量就是矩阵[1,2                3,4]

Tensorflow支持平台

Tensorflow 支持 Python 2.7和 Python 3.3+.但是对于 Windows, TensorFlow 只支持 64-bit的 Python 3.5.
requirements.txt

tensorflow==1.2.1scipy==0.19.1scikit-learn==0.18.2matplotlib==2.0.2xlrd==1.0.0ipdb==0.10.1Pillow==4.2.1lxml==3.8.0

TensorFlow安装

Mac OS
1. 安装需要pip或者pip3(python 3)

sudo easy_install pip sudo easy_install --upgrade sixsudo pip install virtualenv

2.设置工程目录,这这个目录下进行操作

mkdir [my project]

3.为工程目录设置虚拟环境

$ cd [my project]$ virtualenv venv --distribute

4.环境变量生效

$ source venv/bin/activate

5.检查是否安装在虚拟环境

$ pip install tensorflow$ pip freeze > requirements.txt

6.退出虚拟环境

$ deactivate

windows

安装Anaconda:https://zhuanlan.zhihu.com/p/25198543
Anaconda介绍:http://python.jobbole.com/86236/
安装tensorflow:https://zhuanlan.zhihu.com/p/24055668

ubuntu
官网:https://www.tensorflow.org/install/
安装的方式也有好几种,通过pip,docker,Anacodnda等,因为ubuntu是自带Python和pip的,因此这里给出的是pip的安装方式。

确定python及pip

python -V

python2.x对应的是pip,python3.x对应的是pip3
更新pip

sudo apt-get install python-pip python-dev

确保python 和pip安装好后,接下来就开始安装tensorflow
根据自己的情况选择以下命令之一进行安装:

 $ pip install tensorflow      # Python 2.7; 仅支持CPU $ pip3 install tensorflow     # Python 3.n; 仅支持CPU $ pip install tensorflow-gpu  # Python 2.7; 支持CPU $ pip3 install tensorflow-gpu # Python 3.n; 支持CPU 

或者用
Tensorflow Installation
http://tflearn.org/installation/
1 首先根据平台选择正确的版本,支持linux mac os 平台,根据自己的平台选择一个,执行后,执行第2步骤。

1 Ubuntu/Linux 64-bit, CPU only, Python 2.7$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp27-none-linux_x86_64.whl2 Ubuntu/Linux 64-bit, GPU enabled, Python 2.7# Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below.$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp27-none-linux_x86_64.whl3 Mac OS X, CPU only, Python 2.7:$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.1.0-py2-none-any.whl4 # Mac OS X, GPU enabled, Python 2.7:$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow_gpu-1.1.0-py2-none-any.whl5 # Ubuntu/Linux 64-bit, CPU only, Python 3.3$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp33-cp33m-linux_x86_64.whl6 # Ubuntu/Linux 64-bit, GPU enabled, Python 3.3# Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below.$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp33-cp33m-linux_x86_64.whl7 # Ubuntu/Linux 64-bit, CPU only, Python 3.4$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp34-cp34m-linux_x86_64.whl8 # Ubuntu/Linux 64-bit, GPU enabled, Python 3.4# Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below.$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp34-cp34m-linux_x86_64.whl9 # Ubuntu/Linux 64-bit, CPU only, Python 3.5$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp35-cp35m-linux_x86_64.whl10 # Ubuntu/Linux 64-bit, GPU enabled, Python 3.5# Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below.$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-linux_x86_64.whl11 # Ubuntu/Linux 64-bit, CPU only, Python 3.6$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.1.0-cp36-cp36m-linux_x86_64.whl12 # Ubuntu/Linux 64-bit, GPU enabled, Python 3.6# Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below.$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp36-cp36m-linux_x86_64.whl13 # Mac OS X, CPU only, Python 3.4 or 3.5:$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.1.0-py3-none-any.whl14 # Mac OS X, GPU enabled, Python 3.4 or 3.5:$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow_gpu-1.1.0-py3-none-any.whl

2 安装指令

$ sudo pip  install --upgrade TF_PYTHON_URL   # Python 2.7$ sudo pip3 install --upgrade TF_PYTHON_URL   # Python 3.N 

3 测试

`>>> import tensorflow as tf>>> hello = tf.constant('Hello, TensorFlow!')>>> sess = tf.Session()>>> sess.run(hello)'Hello, TensorFlow!'>>> a = tf.constant(10)>>> b = tf.constant(32)>>> sess.run(a + b)42>>> sess.close()`

例子:

import tensorflow as tfimport numpy as npx_data=np.float32(np.random.rand(2,100))#random data with 2 rows 100 colsy_data=np.dot([0.100,0.200],x_data)+0.300b=tf.Variable(tf.zeros([1]))W=tf.Variable(tf.random_uniform([1,2],-1.0,1.0))y=tf.matmul(W,x_data)+bloss=tf.reduce_mean(tf.square(y-y_data))optimizer=tf.train.GradientDescentOptimizer(0.5)train =optimizer.minimize(loss)init = tf.initialize_all_variables()ssess = tf. Session()sess.run(init)for step in xrange(0,201):    sess.run(train)    if step % 20 == 0:        print step,sess.run(W), sess.run(b)

这里写图片描述

计算图-数据流图

import tensorflow as tfa=tf.add(3,5)sess = tf.Session()#输出a的值方法1print sess.run(a)#tensorflow默认是32位的数据,而不是8位,功过sess来获得a的值,最后就关闭会话sess.close()#输出a的值方法2with tf.Session() as sess:    print sess.run(a)

节点Nodes: operators,variables,constants
Edges:tensors
TensorFlow 程序通常被组织成一个构建阶段和一个执行阶段. 在构建阶段, op 的执行步骤 被描述成一个图. 在执行阶段, 使用会话执行执行图中的 op.例如, 通常在构建阶段创建一个图来表示和训练神经网络, 然后在执行阶段反复执行图中的训练 op.
TensorFlow 支持 C, C++, Python 编程语言. 目前, TensorFlow 的 Python 库更加易用, 它提供了大量的辅助函数来简化构建图的工作, 这些函数尚未被 C 和 C++ 库支持.
三种语言的会话库 (session libraries) 是一致的.

构建图

构建图的第一步, 是创建源 op (source op). 源 op 不需要任何输入, 例如 常量 (Constant) . 源 op 的输出
被传递给其它 op 做运算.
Python 库中, op 构造器的返回值代表被构造出的 op 的输出, 这些返回值可以传递给其它 op 构造器作为输入.
TensorFlow Python 库有一个默认图 (default graph), op 构造器可以为其增加节点. 这个默认图对 许多程序
来说已经足够用了. 阅读 Graph 类 文档 来了解如何管理多个图.

import tensorflow as tf 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点 加到默认图中.

#构造器的返回值代表该常量 op 的返回值.
matrix1 = tf.constant([[3., 3.]])
#创建另外一个常量 op, 产生一个 2x1 矩阵.
matrix2 = tf.constant([[2.],[2.]])
#创建一个矩阵乘法 matmul op , 把 ‘matrix1’ 和 ‘matrix2’ 作为输入.
#返回值 ‘product’ 代表矩阵乘法的结果.
product = tf.matmul(matrix1, matrix2)

上述代码定义了两个矩阵常量,并进行矩阵乘法运算默认图现在有三个节点, 两个 constant() op, 和一个 matmul() op. 为了真正进行矩阵相乘运算, 并得到矩阵乘法的 结果, 你必须在会话里启动这个图.在一个会话中启动图构造阶段完成后, 才能启动图. 启动图的第一步是创建一个 Session 对象, 如果无任何创建参数, 会话构造器将启动默认图.启动默认图.`sess = tf.Session()` 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数. 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回# 矩阵乘法 op 的输出.## 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.## 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.## 返回值 'result' 是一个 numpy `ndarray` 对象.result = sess.run(product)print result# ==> [[ 12.]]# 任务完成, 关闭会话.sess.close()

Session 对象在使用完后需要关闭以释放资源. 除了显式调用 close 外, 也可以使用 “with” 代码块 来自动完
成关闭动作.

with tf.Session() as sess:    result = sess.run([product])    print result

指定 CPU 或者GPU计算
在实现上, TensorFlow 将图形定义转换成分布式执行的操作, 以充分利用可用的计算资源(如 CPU 或 GPU). 一
般你不需要显式指定使用 CPU 还是 GPU, TensorFlow 能自动检测. 如果检测到 GPU, TensorFlow 会尽可能地利
用找到的第一个 GPU 来执行操作.
如果机器上有超过一个可用的 GPU, 除第一个外的其它 GPU 默认是不参与计算的. 为了让 TensorFlow 使用这些
GPU, 你必须将 op 明确指派给它们执行. with…Device 语句用来指派特定的 CPU 或 GPU 执行操作:

with tf.Session() as sess:    with tf.device("/gpu:1"):        matrix1 = tf.constant([[3., 3.]])        matrix2 = tf.constant([[2.],[2.]])        product = tf.matmul(matrix1, matrix2)...

设备用字符串进行标识. 目前支持的设备包括:
"/cpu:0" : 机器的 CPU.
"/gpu:0" : 机器的第一个 GPU, 如果有的话.
"/gpu:1" : 机器的第二个 GPU, 以此类推.

分布计算

# Creates a graph.with tf.device('/gpu:2'):  a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')  b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')  c = tf.matmul(a, b)# Creates a session with log_device_placement set to True.sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))# Runs the op.print sess.run(c)

以上例子中没有使用分布式计算模式,session是运行默认的图,那么怎么在建议一个图的情况下实现分布式计算呢?

多个图就需要多个session,每个都要使用所有默认的变量通过python/numpy不能在多个图中传递这些数据,numpy不支持分布计算最好的方法就是不要将子图连接成一个图

tf.Graph()

#create a graph:g = tf.Graph()#定义一个图对象,对图进行操作,可以在图上定义节点以及操作,在session中指定在哪个graph上操作。with g.as_default():    x = tf.add(3, 5)sess = tf.Session(graph=g)with tf.Session() as sess:    sess.run(x)

想要处理默认的图:

g = tf.get_default_graph()

注意不要混淆默认graph和自定义graph

#自定义了一个graph,gg = tf.Graph()# add ops to the default graph在默认图上添加操作a = tf.constant(3)# add ops to the user created graph在自定义图上添加操作with g.as_default():    b = tf.constant(5)

以上定义方法容易出错,下面列子将默认graph也定义了,分别操作,比上一个列子好了点,但是仍然有多个图,容易出错。

g1 = tf.get_default_graph()g2 = tf.Graph()# add ops to the default graphwith g1.as_default():    a = tf.Constant(3)# add ops to the user created graphwith g2.as_default():    b = tf.Constant(5)

那怎么定义才是做好的,不容易出错呢?想想为什么要定义graph呢?

1 保存计算结果,只运行你需要的结果,中间结果不需要可以不输出2 将计算分成多个小的计算,便于分块计算3 可以在多个设备上计算CPUs, GPUs4 许多常见的机器学习模型已经一般化和图形化

交互式使用
Python 示例使用一个会话 Session 来 启动图, 并调用 Session.run() 方法执行操作.为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用 InteractiveSession 代替 Session 类, 使用Tensor.eval() 和 Operation.run() 方法代替 Session.run() . 这样可以避免使用一个变量来持有会话.

# 进入一个交互式 TensorFlow 会话.import tensorflow as tfsess = tf.InteractiveSession()#下面的貌似都没有变化 就只开启的交互式的session了,意思可以用ipython之类的编译了?x = tf.Variable([1.0, 2.0])a = tf.constant([3.0, 3.0])# 使用初始化器 initializer op 的 run() 方法初始化 'x'x.initializer.run()# 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果sub = tf.sub(x, a)print sub.eval()# ==> [-2. -1.]

Tensor
TensorFlow 张量流,程序使用 tensor 数据结构来代表所有的数据, 计算图中, 操作间传递的数据都是 tensor. 可以把 TensorFlow tensor 看作是一个 n 维的数组或列表. 一个 tensor 包含一个静态类型 rank, 和 一个 shape.

变量

Variables for more details. 变量维护图执行过程中的状态信息. 下面的例子演示了如何使用变量实现一个简单的计数器.

import tensorflow as tfstate = tf.Variable(0, name="counter")one = tf.constant(1)new_value = tf.add(state, one)update = tf.assign(state, new_value)init_op = tf.initialize_all_variables()with tf.Session() as sess:    sess.run(init_op)    print sess.run(state)    for _ in range(3):        sess.run(update)        print sess.run(state)# 输出:# 0# 1# 2# 3

代码中 assign() 操作是图所描绘的表达式的一部分, 正如 add() 操作一样. 所以在调用 run() 执行表达式
之前, 它并不会真正执行赋值操作.
通常会将一个统计模型中的参数表示为一组变量. 例如, 你可以将一个神经网络的权重作为某个变量存储在一个
tensor 中. 在训练过程中, 通过重复运行训练图, 更新这个 tensor

输出Fetch

为了取回操作的输出内容, 可以在使用 Session 对象的 run() 调用 执行图时, 传入一些 tensor, 这些 tens
or 会帮助你取回结果. 在之前的例子里, 我们只取回了单个节点 state , 但是你也可以取回多个 tensor:需要获取的多个 tensor 值,在 op 的一次运行中一起获得(而不是逐个去获取 tensor)。

input1 = tf.constant(3.0)input2 = tf.constant(2.0)input3 = tf.constant(5.0)intermed = tf.add(input2, input3)mul = tf.mul(input1, intermed)with tf.Session() as sess:    result = sess.run([mul, intermed])#输出多个结果    print result

Feed

上述示例在计算图中引入了 tensor, 以常量或变量的形式存储. TensorFlow 还提供了 feed 机制, 该机制 可以
临时替代图中的任意操作中的 tensor 可以对图中任何操作提交补丁, 直接插入一个 tensor.
feed 使用一个 tensor 值临时替换一个操作的输出结果. 你可以提供 feed 数据作为 run() 调用的参数. feed
只在调用它的方法内有效, 方法结束, feed 就会消失. 最常见的用例是将某些特殊的操作指定为 “feed” 操作,标记的方法是使用 tf.placeholder() 为这些操作创建占位符.

input1 = tf.placeholder(tf.types.float32)input2 = tf.placeholder(tf.types.float32)output = tf.mul(input1, input2)with tf.Session() as sess:print sess.run([output], feed_dict={input1:[7.], input2:[2.]})# 输出:# [array([ 14.], dtype=float32)]

tf.Variable:主要在于一些可训练变量(trainable variables),比如模型的权重(weights,W)或者偏执值(bias),声明时,必须提供初始值;
名称的真实含义,在于变量,也即在真实训练时,其值是会改变的,自然事先需要指定初始值;

weights = tf.Variable(tf.truncated_normal([IMAGE_PIXELS, hidden1_units],stddev=1./math.sqrt(float(IMAGE_PIXELS)), name='weights'))biases = tf.Variable(tf.zeros([hidden1_units]), name='biases')

tf.placeholder:用于得到传递进来的真实的训练样本: 不必指定初始值,可在运行时,通过 Session.run 的函数的 feed_dict 参数指定;这也是其命名的原因所在,仅仅作为一种占位符;

x = tf.placeholder(tf.float32, shape=(1024, 1024))  y = tf.matmul(x, x)  with tf.Session() as sess:    print(sess.run(y))  # ERROR: 此处x还没有赋值.    rand_array = np.random.rand(1024, 1024)    print(sess.run(y, feed_dict={x: rand_array}))  # Will succeed. 

如下则是二者真实的使用场景:

for step in range(FLAGS.max_steps):    feed_dict = {        images_placeholder = images_feed,        labels_placeholder = labels_feed    }    _, loss_value = sess.run([train_op, loss], feed_dict=feed_dict)

当执行这些操作时,tf.Variable 的值将会改变,也即被修改,这也是其名称的来源(variable,变量)。

例子:02_feed_dict.py

""" Example to demonstrate the use of feed_dictAuthor: Chip HuyenPrepared for the class CS 20SI: "TensorFlow for Deep Learning Research"cs20si.stanford.edu"""import osos.environ['TF_CPP_MIN_LOG_LEVEL']='2'import tensorflow as tf# Example 1: feed_dict with placeholder用字典填充占位符# create a placeholder of type float 32-bit, value is a vector of 3 elements定义了一个32位浮点型的占位符,值是一个有3个元素的向量a = tf.placeholder(tf.float32, shape=[3])# create a constant of type float 32-bit, value is a vector of 3 elements定义了一个常量b = tf.constant([5, 5, 5], tf.float32)# use the placeholder as you would a constant占位符和常量相加,这里a还没有值呢c = a + b  # short for tf.add(a, b)with tf.Session() as sess:    # print(sess.run(c)) # InvalidArgumentError because a doesn’t have any value这里不能直接运行c,因为a只是一个占位符还没有具体的值,得给他feed个值    # feed [1, 2, 3] to placeholder a via the dict {a: [1, 2, 3]}    # fetch value of c    print(sess.run(c, {a: [1, 2, 3]})) # >> [6. 7. 8.]# Example 2: feed_dict with variablesa = tf.add(2, 5)b = tf.multiply(a, 3)with tf.Session() as sess:    # define a dictionary that says to replace the value of 'a' with 15    replace_dict = {a: 15}    # Run the session, passing in 'replace_dict' as the value to 'feed_dict'    print(sess.run(b, feed_dict=replace_dict)) # >> 45
原创粉丝点击