Tensorflow入门 -- 191204

Definition

  • 使用图 (graph) 来表示计算任务.
  • 在被称之为 会话 (Session) 的上下文 (context) 中执行图.
  • 使用 tensor 表示数据.
  • 通过 变量 (Variable) 维护状态.
  • 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.

Summarize

  • Graph:图中的节点为op(operation),一个op获得0+个tensor,执行计算,产生0+个tensor。
  • 图须在会话Session中启动。会话将op发布到设备上,同时提供执行op的方法,即程序。方法执行后,返回产生的tensor。
  • Python 语言中, 返回的 tensor 是 numpy ndarray 对象; 在 C 和 C++ 语言中, 返回的 tensor 是 tensorflow::Tensor 实例.

Graph Construction

1. source op

源 op 不需要任何输入, 例如常量 (Constant). 源 op 的输出被传递给其它 op 做运算.
Python 库中, op 构造器的返回值代表被构造出的 op 的输出, 这些返回值可以传递给其它 op 构造器作为输入.

# -*- coding: utf-8 -*-
"""
Created on Mon Dec  9 19:01:17 2019

@author: HTING
"""

import tensorflow as tf
matrix1 = tf.constant([4.,4.])
matrix2 = tf.constant([[2.],[3.]])
product = tf.matmul(matrix1,matrix2)

2. 在一个会话中启动图

(1)tf.Session()

启动图的第一步是创建一个 Session 对象, 如果无任何创建参数, 会话构造器将启动默认图.

# 启动默认图
sess = tf.Session()

result = sess.run(product)
print result
# --> [[16.],24.]])

# 关闭会话
sess.close()

若报错:
AttributeError: module 'tensorflow' has no attribute 'Session'
则表示tensorflow版本为2.0.0,须在代码区加入tf.compat.v1.disable_eager_execution()
参考网址:https://www.tensorflow.org/guide/migrate

tensorflow2.0.0

import tensorflow as tf

# tensorflow2.0.0 必备良药
tensorflow.compat.v1.disable_eager_execution()

matrix1 = tf.constant([4.,4.])
matrix2 = tf.constant([[2.],[3.]])
product = tf.matmul(matrix1,matrix2)

# 启动默认图
# tensorflow2.0.0: tensorflow.compat.v1.Session()
sess = tf.compat.v1.Session()

result = sess.run(product)
print result
# --> [[16.],24.]])

# 关闭会话
sess.close()

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

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

在实现上,TensorFlow将Graph定义转换为分布式执行的操作,以充分利用可用的计算资源.TensorFlow会自动检测设备进行计算.

如果机器上CPU或GPU过多,则多余的设备默认不参与计算.为了充分利用计算资源,须将op明确指派给它们执行

with···Device语句用来指派特定的设备执行操作

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

Interactive use(交互式使用)

为了便于使用IPython等交互环境,可以使用InteractiveSessionSession , 使用Tensor.eval() && Operation.run()Session.run() .这样可以避免使用一个变量来维持会话.

# 进入一个交互式TensorFlow会话
import tensorflow as tf
sess = tf.compat.v1.InteractiveSession()

x = tf.Variable([4.,4.])
y = tf.constant([2.,3.])

# 使用初始化器Initializer op 的run()方法初始化 ‘x'
x.initializer.run()

# 增加一个减法 sub op, 从'x' 减去’y'.	运行减法 op, 输出结果
sub = tf.sub(x,y)
print sub.eval()
# ==> [2.,1.]

tensor

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

Variable

state = tf.Variable(0, name = "counter")

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

代码中 assign() 操作是图所描绘的表达式的一部分, 正如 add() 操作一样. 所以在调用 run() 执行表达式之前, 它并不会真正执行赋值操作.

通常会将一个统计模型中的参数表示为一组变量. 例如, 你可以将一个神经网络的权重作为某个变量存储在一个 tensor 中. 在训练过程中, 通过重复运行训练图, 更新这个 tensor.

Fetch

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():
  result = sess.run([mul, intermed])
  print result

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

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

如果没有正确提供 feed, placeholder() 操作将会产生错误.

–部分引用于http://www.tensorfly.cn/tfdoc/get_started/basic_usage.html

发布了26 篇原创文章 · 获赞 3 · 访问量 1395

猜你喜欢

转载自blog.csdn.net/qq_42937176/article/details/103392979