tf.Variable tf.placeholder tf.constant 区别

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

总结:

  1. tf.Variable:表示变量,运行时可以改变。主要用于一些可训练变量(trainable variables),比如模型的权重(weights,W)或者偏置值(bias);
    声明时,必须提供初始值
    运行时,必须初始化。 用sess.run(tf.global_variables_initializer())初始化所有变量

  2. tf.placeholder:表示张量(最少有一维,即最少含有一组中括号),运行时不可改变。用于得到传递进来的真实的训练样本:
    声明时,不指定初始值
    运行时,需要赋值。 通过 Session.run 的函数的 feed_dict 参数指定

  3. tf.constan:表示常量,运行时不可改变

参考链接:
TensorFlow 辨异 —— tf.placeholder 与 tf.Variable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值