What's the difference between tf.placeholder and tf.Variable

https://stackoverflow.com/questions/36693740/whats-the-difference-between-tf-placeholder-and-tf-variable

down vote
The difference is that with tf.Variable you have to provide an initial value when you declare it. With tf.placeholder you don’t have to provide an initial value and you can specify it at run time with the feed_dict argument inside Session.run

placeholder 用来表示输入和输出数据,不需要有初始值

for step in xrange(FLAGS.max_steps):
    feed_dict = {
       images_placeholder: images_feed,
       labels_placeholder: labels_feed,
     }
    _, loss_value = sess.run([train_op, loss], feed_dict=feed_dict)

Variable 在Seesion训练时候会改变,而且需要有初始值

`tf.placeholder` 是在早期 TensorFlow 版本中使用的占位符操作符,它在图执行前预留空间,以便在运行时传入数据。而从 TF 2.0 开始,`tf.placeholder` 被官方建议弃用,转而使用 `tf.Variable` 来创建常量变量,特别是当你需要在程序执行期间动态赋值的数据。 如果你想用 `tf.Variable` 替代 `tf.placeholder`,你需要做以下几点: 1. **创建常量变量**:使用 `tf.Variable(initial_value=None, trainable=True, name=None)` 函数创建一个变量,`initial_value` 设置初始值,`trainable` 表示是否参与训练,`name` 是变量名称。 ```python variable = tf.Variable(tf.zeros([batch_size, input_shape])) ``` 2. **初始化变量**:在每次会话开始之前,你需要通过 `.assign` 或 `.initializer` 初始化变量,如果是模型的权重,则通常会在构建 `tf.keras.Model` 的时候一起完成自动初始化。 ```python sess.run(variable.initializer) ``` 3. **传入数据**:如果需要动态输入数据,可以直接赋值给变量,而不是像 placeholder 那样留空。 ```python # 在某个时刻赋予数据 variable.assign(new_data) ``` 4. **注意区分训练模式和评估模式**:对于需要在整个计算图中保持不变的参数,可以设置其`trainable=False`。 总之,`tf.Variable` 更加通用,不仅可以用作占位符,还可以存储模型参数等。但在处理需要延迟赋值的情况时,可以选择 `tf.Variable` 的 `assign` 功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值