tensorflow 入门之三 - 常量、变量和占位符
TensorFlow 提供了一个库来定义和执行各种数学运算. 这些数学运算建立在"张量"上.
张量: 理解为矩阵/数组吧
张量类型:
- 常量: 通编程语言中的常量,训练数据就是常量
- 变量: 可变的量. 保存训练参数.
- 占位符: 用于将值输入 TensorFlow 图中。用于和 feed_dict 配合输入数据. 在会话中运行计算图时,可以为占位符赋值。这样在构建一个计算图时不需要真正地输入数据
import tensorflow as tf
tf.__version__
'1.14.0'
常量
tf.constant(1),tf.constant([1,2]),tf.constant([[1,2],[2,3],[3,3]]),tf.constant([[[1,2]]])
(<tf.Tensor 'Const:0' shape=() dtype=int32>,
<tf.Tensor 'Const_1:0' shape=(2,) dtype=int32>,
<tf.Tensor 'Const_2:0' shape=(3, 2) dtype=int32>,
<tf.Tensor 'Const_3:0' shape=(1, 1, 2) dtype=int32>)
# 生成 0 张量
tf.zeros(1,tf.int32),tf.zeros([1,],tf.int32),tf.zeros([1,2],tf.int32),tf.zeros([1,2,3],tf.int32)
(<tf.Tensor 'zeros:0' shape=(1,) dtype=int32>,
<tf.Tensor 'zeros_1:0' shape=(1,) dtype=int32>,
<tf.Tensor 'zeros_2:0' shape=(1, 2) dtype=int32>,
<tf.Tensor 'zeros_3:0' shape=(1, 2, 3) dtype=int32>)
# 序列
tf.linspace(1.0,10.0,10)
<tf.Tensor 'LinSpace:0' shape=(10,) dtype=float32>
# 范围
tf.range(1.0,10.0,1.0)
<tf.Tensor 'range:0' shape=(9,) dtype=float32>
变量
range=tf.range(1.0,10.0,1.0)
range
<tf.Tensor 'range_1:0' shape=(9,) dtype=float32>
v_a=tf.Variable(range)
v_b=tf.Variable(range)
v_a,v_b
(<tf.Variable 'Variable:0' shape=(9,) dtype=float32_ref>,
<tf.Variable 'Variable_1:0' shape=(9,) dtype=float32_ref>)
tf.Variable: 类型
Variable:0 : 类型+序号
shape=(9,): 维度
dtype=float32_ref: 类型
tf.global_variables_initializer()
<tf.Operation 'init' type=NoOp>
占位符
用于将数据提供给计算图
tf.placeholder(dtype,shape=None,name=None)
x=tf.placeholder("float")
y=2*x
data=tf.range(1,100,3)
x,y,data
(<tf.Tensor 'Placeholder:0' shape=<unknown> dtype=float32>,
<tf.Tensor 'mul:0' shape=<unknown> dtype=float32>,
<tf.Tensor 'range_2:0' shape=(33,) dtype=int32>)
with tf.Session() as se:
x_data=se.run(data)
x_data
array([ 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49,
52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97])
with tf.Session() as se:
y_pre=se.run(y,feed_dict={x:x_data})
y_pre
array([ 2., 8., 14., 20., 26., 32., 38., 44., 50., 56., 62.,
68., 74., 80., 86., 92., 98., 104., 110., 116., 122., 128.,
134., 140., 146., 152., 158., 164., 170., 176., 182., 188., 194.],
dtype=float32)
总结
无论是常量,还是变量, 在定义的时候其实都是 “不运行” 的,它们只是一个占位符.
何时真正运行数据: 调用 tf.Session().run() 的时候, 才是真正的运行数据.