tensorflow的基本用法

xiaoxiao2021-02-27  280

tensorflow的基本用法

主要数据类型

类型描述作用Session会话用于执行graphgraph计算任务必须在Session中启动tensor数据一个类型化的多维数组op操作graph中的节点,输入tensor,经op后输出也为tensorVariable变量用于状态的维护feed赋值为op的tensor赋值fetch取值从op的tensor取值

过程原理

一个 TensorFlow 即为一个张图的计算过程. 必须在 Session 中启动 graph 。并将graph 的 op 分发到 CPU 或 GPU 上, 同时提供执行 op 的方法. 这些方法执行后, 将产生的 tensor 返回. 在 Python 语言中, 返回的 tensor 是 numpy ndarray 对象; 在 C 和 C++ 语言中, 返回的 tensor 是 tensorflow::Tensor 实例.

构建图

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

下面这个例子,构建了一个包含三个op的图,两个constant() op 以及一个matmul() op

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)

到目前为止,我们仅仅构建了一张图,但是并没有真正的进行运算,因此下面,需要通过Session启动graph.

在Session中启动graph

启动图的第一步是创建一个 Session 对象, 如果无任何创建参数, 会话构造器将启动默认图.Session的更多用法参阅http://wiki.jikexueyuan.com/project/tensorflow-zh/api_docs/python/client.html 创建Session完毕后,需要使用sess.run(op)方法来执行你想要的操作

# 启动默认图. 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对象在使用完毕后,必须要关闭才能释放资源,有两种关闭方式。

通过 sess.close()直接关闭通过with代码块关闭 with tf.Session() as sess: result = sess.run([product]) print result

指定CPU或GPU运行

前面有说到,Session会把op分发到CPU或GPU(统称为device)上运行,当这些device的数量有多个时,默认总是启动第一个参与计算,如果需要提高效率,可以通过以下代码段指派device:

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

device的指定规则为: - “/cpu:0”: 机器的 CPU. - “/gpu:0”: 机器的第一个 GPU, 如果有的话. - “/gpu:1”: 机器的第二个 GPU, 以此类推.

交互

通常,会使用session.run()方法来执行某些操作,但是为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用 InteractiveSession 代替 Session 类, 使用 Tensor.eval() 和 Operation.run() 方法代替 Session.run(). 这样可以避免使用一个变量来持有会话.

# 进入一个交互式 TensorFlow 会话. import tensorflow as tf sess = tf.InteractiveSession() 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. 想了解 TensorFlow 是如何处理这些概念的, 参见 Rank, Shape, 和 Type(http://wiki.jikexueyuan.com/project/tensorflow-zh/resources/dims_types.html).

Veriables

Veriables维护图执行过程中的状态信息. 下面的例子演示了如何使用变量实现一个简单的计数器. 更多细节访问http://wiki.jikexueyuan.com/project/tensorflow-zh/how_tos/variables/index.html

# 创建一个变量, 初始化为标量 0. state = tf.Variable(0, name="counter") # 创建一个 op, 其作用是使 state 增加 1 one = tf.constant(1) new_value = tf.add(state, one) update = tf.assign(state, new_value) # 启动图后, 变量必须先经过`初始化` (init) op 初始化, # 首先必须增加一个`初始化` op 到图中. init_op = tf.initialize_all_variables() # 启动图, 运行 op with tf.Session() as sess: # 运行 'init' op sess.run(init_op) # 打印 'state' 的初始值 print sess.run(state) # 运行 op, 更新 'state', 并打印 'state' for _ in range(3): sess.run(update) print sess.run(state) # 输出: # 0 # 1 # 2 # 3

Fetch

为了获取操作的输出内容, 可以在使用 Session 对象的 run() 调用 执行图时, 传入一些 tensor, 这些 tensor 会帮助你取回结果. 在之前的例子里, 我们只取回了单个节点 state, 但是你也可以取回多个 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 # 输出: # [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]

需要获取的多个 tensor 值,在 op 的一次运行中一起获得(而不是逐个去获取 tensor)。

Feed

通过 tf.placeholder() 为变量创建指定数据类型占位符,在run的时候,通过feed_dict来为变量赋值。

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.]}) # 输出: # [array([ 14.], dtype=float32)]
转载请注明原文地址: https://www.6miu.com/read-4517.html

最新回复(0)