tensorflow 入门之三 - 常量、变量和占位符

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() 的时候, 才是真正的运行数据.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值