您的位置:首页 > 其它

TensorFlow官方教程学习 基本使用

2016-11-22 13:06 701 查看
为了使用TensorFlow,你需要知道TensorFlow如何:

- 将计算表示为图

- 在Sessions的上下文中运算图

- 将数据表示为张量(tensor)

- 使用Variable保存状态

- 使用feeds和fetches来在任意操作中获取和设置数据

概述

TensorFlow是一个你能够将计算表示为图的编程系统。在图中的节点称为ops(operations的缩写)。一个op使用零个或者多个张量(Tensors)。一个张量是一个具有类型的多维数组。例如,你能够将一个小批次的图像表示为4维浮点数数组,维度分别为[batch, height, width, channels]。

一个TensorFlow图是对于计算的描述。为了计算一些事物,一张图必须在一个会话(Sessions)中启动。一个会话将图中的操作放入到设备(Devices)中,例如CPU或者GPU,并且提供方法来运行它们。这些方法必须返回操作产生的张量,张量的形式为Python中的numpy ndarray对象和C以及C++中的tensorflow::Tensor实例。

计算图

TensorFlow程序通常被构造为构建一张图的构造阶段以及使用会话来运行图中操作的运行阶段。

例如,在构造阶段通常创建一张图来代表和训练一个神经网络。然后在运行阶段不断运行图中的一系列训练操作。

TensorFlow能够在C,C++,Python编程中被使用。使用Python库来构建图更加容易,因为其提供了许多在C和C++库中间没有的很有帮助的函数。

会话库对于这三种语言有着等效的功能。

构建图

为了构建图,从不需要任何输入的操作(源操作)开始,例如Constant,然后传递这些操作的输出到其它的操作来进行运算。

在Pyhton库中的操作构造函数返回代表构造后的操作的输出的对象。你可以传递这些对象给其它的操作构造函数来作为输入。

TensorFlow的Python库有一个默认的图,在图中可以使用ops的构造函数添加节点。默认的图对于很多应用都有效。查看Graph类的文档来了解如何显示管理多个图。

import tensorflow as tf

# Create a Constant op that produces a 1x2 matrix. The op is
# added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
matrix1 = tf.constant([[3., 3. ]])

# Create another Constant that produces a 2x1 matrix.
matrix2 = tf.constant([[ 2.], [2. ]])

# Create a Matmul op that takes ‘matrix1’ and ‘matrix2’ as inputs.
# The returned value, ‘product’, represents the result of the matrix multiplication.
product = tf.matmul(matrix1, matrix2)


默认的图现在有三个节点了,两个constant()操作和一个matmul操作。为了实际将矩阵相乘并得到乘法的结果,你必须在会话中启动图。

在会话中启动图

在创建图之后我们可以启动它。为了启动一张图,创建一个会话(Session)对象。如果没有指定参数,会话的构造函数启动默认的图。

查看会话类来获取完整地会话API

# Launch the default graph.
sess = tf.Session()

# To run the matmul op we call the session 'run()' method, passing 'product'
# which represents the output of the matmul op.  This indicates to the call
# that we want to get the output of the matmul op back.
#
# All inputs needed by the op are run automatically by the session.  They
# typically are run in parallel.
#
# The call 'run(product)' thus causes the execution of three ops in the
# graph: the two constants and matmul.
#
# The output of the op is returned in 'result' as a numpy `ndarray` object.
result = sess.run(product)
print(result)
# ==> [[ 12.]]

# Close the Session when we're done.
sess.close()


会话必须被关闭来释放资源。你也可以使用一个’with’代码块来输入一个会话,这样会话会在with代码块的最后部分自动释放

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


TensorFlow的实现能够将图的定义转换为在可用计算资源(例如CPU或者你的计算机上的一张GPU卡)中分布的可执行计算。通常你不用显式指定CPU或者GPU。TensorFlow会在你可能有的第一块GPU运行尽可能多的操作。

如果在你的机器上有超过一块可用的GPU,为了使用除了第一块之外的GPU,你必须显式将操作指定给它。使用with…Device语句来指定在这个操作上使用哪个CPU或者GPU。

with tf.Session() as sess:
with tf.device('/cpu:0'):
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])
product = tf.matmul(matrix1, matrix2)
result = sess.run(product)
print result


设备能够使用字符串来指定,现在支持的设备包括:

‘/cpu:0’:你机器上的CPU

‘/gpu:0’:你机器上的第一块GPU

‘/gpu:1’: 你机器上的第二块GPU,之后类似

查看使用GPUs获取更多的关于GPU和TensorFlow的信息。

在分布式会话中启动图

为了创建一个TensorFlow集群,在集群中的每个机器上启动一个TensorFlow服务器。如果你在客户端实例化一个会话,你传递给它一个集群中的机器的网络位置

with tf.Session('grpc://example.org:2222') as sess:
# Calls to sess.run(…) will be executed on the cluster


这个机器成为了会话的主服务器(master)。主服务器在集群中的机器(worker工作节点)上分布该图,就像在一台机器内在可用的计算资源上分布图一样。

你能够使用 ‘with tf.device():’语句来直接指定图中特定部分的工作节点。

with tf.device("/job:ps/task:0"):
weights = tf.Variable(...)
biases = tf.Variable(...)


查看分布式TensorFlow来获取更多有关分布式会话和集群的信息。

交互式使用

文档中的Python例子在一个会话(Session)中启动图,使用Session.run()方法来运行操作。

为了方便使用Python中例如IPython这样的交互式环境,可以使用InteractiveSession类,和Tensor.eval()以及Operation.run()方法。这样避免了不得不维持一个向量来处理会话。

# Enter an interactive TensorFlow Session.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# Initialize 'x' using the run() method of its initializer op.
x.initializer.run()

# Add an op to subtract 'a' from 'x'.  Run it and print the result
sub = tf.sub(x, a)
print(sub.eval())
# ==> [-2. -1.]

# Close the Session when we're done.
sess.close()


张量(Tensors)

TensorFlow程序使用一个张量数据结构来代表所有的数据 - 只有张量能在计算图的操作之间传递。你可以认为一个TensorFlow的张量为一个n维队列或者列表。一个张量有着静态类型,秩和形状。可以参见秩,形状和类型来更多了解TensorFlow如何处理这些概念的信息。

变量(Variables)

变量保存贯穿图的运行过程中的状态。如下的例子展示了如何将一个变量作为一个简单的计数器使用,查看变量来获取更多信息。

# Create a Variable, that will be initialized to the scalar value 0.
state = tf.Variable(0, name="counter")

# Create an Op to add one to `state`.

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# Variables must be initialized by running an `init` Op after having
# launched the graph.  We first have to add the `init` Op to the graph.
init_op = tf.initialize_all_variables()

# Launch the graph and run the ops.
with tf.Session() as sess:
# Run the 'init' op
sess.run(init_op)
# Print the initial value of 'state'
print(sess.run(state))
# Run the op that updates 'state' and print 'state'.
for _ in range(3):
sess.run(update)
print(sess.run(state))

# output:

# 0
# 1
# 2
# 3


在代码中的assign()操作像add()操作一样都是图中的一部分,所以直到run()运行了表达式之前,其并不做实际上执行赋值操作。

你通常将统计模型中的参数表示为一组向量。例如,你可以将一个神经网络的权重以张量的形式存储在变量中。在训练期间你可以通过反复运行训练图来更新此张量。

Fetches

为了获取操作的输出,调用Session对象中的run()来运行图,传递张量来检索输出的数据。在之前的例子中我们获取了单个节点state,但是你也可以获取多个张量。

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)

# output:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]


所有产生被请求的张量的值得操作都是一次性完成(不是每个请求的张量运行一次)。

Feeds

以上的例子通过存储在常量(Constants)和变量(Variables)将张量引入到运算图中。TensorFlow也提供了一个feed机制来讲张量直接插入到图中的任意操作中。

一个feed临时用一个张量的值替代了一个操作的输出。你可以应用feed操作做为run()调用的一个参数。feed仅仅被其传递给的run调用使用。最常见的使用方法包括制定特定的操作为’feed’操作,通过使用tf.placeholder()来创建它们。

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

# output:
# [array([ 14.], dtype=float32)]


如果你不应用一个feed给一个placeholder()操作,其将会产生一个错误。查看MNIST全连接feed教程(源代码)来获取一个大规模使用feed的例子。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TensorFlow 机器学习