tf.Variable tf.placeholder tf.constant 区别
import tensorflow as tf
# 构建计算图节点(声明节点)
a = tf.Variable(1) # 此阶段必须指定初值
b = tf.constant(1)
c = tf.placeholder(dtype=tf.int32, shape=(1,)) # 此阶段无需指定初值
update = tf.assign(a, tf.add(a, b))
# 运行计算图前准备
init = tf.global_variables_initializer() # init等价于初始化所有变量
feed_dict = {c:[10]} # feed_dict等价于为placeholder喂入数据,准备运行计算图
#注意一定加中括号,因为place_holder中一定是张量,张量最少有一组中括号
# 运行计算图
with tf.Session() as sess:
sess.run(init) # 初始化所有变量
print("c:{}".format(sess.run(c, feed_dict = feed_dict))) # 为placeholder喂入数据
for i in range(2):
print("update a:{}".format(sess.run(update))) # 输出在屏幕的是a的值
print("a:{}".format(sess.run(a)) )
运行结果:
c:[10]
update a:2
a:2
update a:3
a:3
总结:
-
tf.Variable:表示变量,运行时可以改变。主要用于一些可训练变量(trainable variables),比如模型的权重(weights,W)或者偏置值(bias);
声明时,必须提供初始值。
运行时,必须初始化。 用sess.run(tf.global_variables_initializer())初始化所有变量 -
tf.placeholder:表示张量(最少有一维,即最少含有一组中括号),运行时不可改变。用于得到传递进来的真实的训练样本:
声明时,不指定初始值
运行时,需要赋值。 通过 Session.run 的函数的 feed_dict 参数指定 -
tf.constan:表示常量,运行时不可改变