tf.placeholder 与 tf.Variable区别

二者的主要区别在于:

tf.Variable:主要在于一些可训练变量(trainable variables),比如模型的权重(weights,W)或者偏置值(bias);

声明时,必须提供初始值;**

名称的真实含义,在于变量,也即在真实训练时,其值是会改变的,自然事先需要指定初始值;

1
2
weights = tf.Variable( tf.truncated_normal([IMAGE_PIXELS, 		                               hidden1_units],stddev=1./math.sqrt(float(IMAGE_PIXELS)), name='weights'))
biases = tf.Variable(tf.zeros([hidden1_units]), name='biases')

tf.placeholder:用于得到传递进来的真实的训练样本:

不必指定初始值,可在运行时,通过 Session.run 的函数的 feed_dict 参数指定;这也是其命名的原因所在,仅仅作为一种占位符;

1
2
images_placeholder = tf.placeholder(tf.float32, shape=[batch_size, IMAGE_PIXELS])
labels_placeholder = tf.placeholder(tf.int32, shape=[batch_size])

如下则是二者真实的使用场景:

1
2
3
4
5
6
for step in range(FLAGS.max_steps):
feed_dict = {
images_placeholder = images_feed,
labels_placeholder = labels_feed
}
_, loss_value = sess.run([train_op, loss], feed_dict=feed_dict)

当执行这些操作时,tf.Variable 的值将会改变,也即被修改,这也是其名称的来源(variable,变量)。

那么,什么时候该用tf.placeholder,什么时候该使用tf.Variable之类直接定义参数呢?

答案是,tf.Variable适合一些需要初始化或被训练而变化的权重或参数,而tf.placeholder适合通常不会改变的被训练的数据集。

小例子:

1
2
3
4
5
6
7
8
9
import tensorflow as tf

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)

output = tf.multiply(input1, input2)

with tf.Session() as sess:
print(sess.run(output, feed_dict={input1: 7., input2: 2.}))

输出:

1
14.0

本文标题:tf.placeholder 与 tf.Variable区别

文章作者:goingcoder

发布时间:2018年04月06日 - 18:04

最后更新:2018年04月06日 - 19:04

原始链接:https://goingcoder.github.io/2018/04/06/tf4/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------本文结束感谢您的阅读-------------