TensorFLow的基本用法

作者: Shuailong | 来源:发表于2017-01-20 14:05 被阅读322次

为了使用TensorFlow你需要理解一下几个方面:TensorFlow是如何

  • 把运算表示为图
  • 在 Session 的语境下执行图
  • 把数据用多维向量表示
  • 用 Variable 维护状态
  • 使用feed和fetch把数据放进和取出任意的算子

概述

TensorFlow把运算表示为图。图的节点是ops(operations)。一个op可以对零个或者多个tensor进行运算,产生零个或多个tensor。在TensorFlow的语境下,tensor就是一个多维向量。
一个TensorFlow 图就是一个对运算的描述。运算开始之前你必须把图在一个Session中 启动。Session会把图放在Devices上面,比如CPU、GPU,然后提供方法来进行计算。在Python中这些方法会返回 numpy 的 ndarray,在C/C++中则会返回tensorflow:Tensor类型的实例。

计算流图

TensorFlow程序一般分为构建阶段和执行阶段。在构建阶段,你可以把图组合起来,比如神经网络图模型。在执行阶段则用Session在执行一系列的ops,比如训练神经网络的运算。
TensorFlow的图可以用Python、C或者C++来写,但是Python会简单一点,因为有许多辅助函数可以使用。

  • 构建图
    首先从不需要任何输入的算子开始,比如 Constant 。把输出结果传递给其他需要输入的算子。
    TF的Python提供了默认的图,可以在大多数场景下使用。

    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)
    
  • 在Session中启动图

     # 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 matmul 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 tf.Session() as sess:
        result = sess.run([product])
        print(result)
    

    通常呢你不需要告诉TF你需要哪个设备进行运算,但是如果你有多个GPU的话你就可以指定TF用哪个设备进行运算了。比如

    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。

 你也可以在分布式集群中运行TensorFlow:

with tf.Session("grpc://example.org:2222") as sess:

Calls to sess.run(...) will be executed on the cluster.

...

指定的机器将会成为你的master,并调动集群中的其他机器进行运算。
或者用```tf.device()```语句来指定worker。

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


### 交互使用

在iPython等交互式的Python环境中,你可以用```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()


### Tensor
TensorFlow程序使用Tensor来表示所有的数据。只有Tensor可以在Operation之间传递。你可以把Tensor看作是一个多维数组。Tensor有静态类型、秩以及形状。

### Variable
Variable 维护执行过程中图的状态。

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.global_variables_initializer()

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

通常你可以把一个统计模型中的参数表达为Variable。比如,把神经网络的权重表达为Variable中的tensor。训练过程中你通过不断地运行图来更新这个tensor。

### Fetches
你可以通过运行Session的```run()```方法来获取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)

output:

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

所有需要的op都会被运行一遍。

### Feeds
Feeds用tensor的值暂时取代了一个op的输出。你可以把feed的数据作为参数传进```run()```函数。feed数据仅会应用于当前的 ```run()```。你可以指定```tf.placeholder()```来创建要feed的op。

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)]







相关文章

网友评论

    本文标题:TensorFLow的基本用法

    本文链接:https://www.haomeiwen.com/subject/ekvwbttx.html