如何使用占位符分配tf.Variables?

3

目前,我有以下代码:

x = tf.placeholder(tf.int32, name = "x")
y = tf.Variable(0, name="y")
y = 2*x**2 + 5
for i in range(1,10):
    print("Value of y for x = ",i, " is: ",sess.run(y, feed_dict={x:i}))

然而,当我想在tensorboard上显示它时,它变得很混乱。 理想情况下,我想做y=tf.Variable(2*x**2 +5),但是tensorflow会抛出一个错误告诉我x未初始化。 或者,我不应该使用tf.Variable,使用其他东西是否更好?

2个回答

2
我认为你误解了tf.Variable的含义。引用Tensorflow文档的说法:

tf.Variable代表一个张量,其值可以通过运行操作来更改。与tf.Tensor对象不同,tf.Variable存在于单个session.run调用的上下文之外。

因此,在神经网络中,变量将是偏差和权重。在训练网络时,这些将会变化。在Tensorflow中,如果要使用变量,需要初始化它们(使用常量或随机值)。这就是你的错误所在:你将y定义为tf.Variable,因此需要初始化。
但是,你的y是确定性的,它不是tf.Variable。你可以删除定义y的那一行,它将正常工作:
import tensorflow as tf

x = tf.placeholder(tf.int32, name = "x")
y = 2*x**2 + 5

with tf.Session() as sess:
    for i in range(1,10):
        print("Value of y for x = ",i, " is: ",sess.run(y, feed_dict={x:i}))

最初的回答是:“它返回:”。
Value of y for x =  1  is:  7
Value of y for x =  2  is:  13
Value of y for x =  3  is:  23
Value of y for x =  4  is:  37
Value of y for x =  5  is:  55
Value of y for x =  6  is:  77
Value of y for x =  7  is:  103
Value of y for x =  8  is:  133
Value of y for x =  9  is:  167

2
如果你真的想要使用 tf.Variable 来实现这个,有两种方法。你可以将期望的表达式作为变量的初始化值。然后,在你初始化变量时,你会在 feed_dict 中传递 x 值。
import tensorflow as tf

# Placeholder shape must be specified or use validate_shape=False in tf.Variable
x = tf.placeholder(tf.int32, (), name="x")
# Initialization value for variable is desired expression
y = tf.Variable(2 * x ** 2 + 5, name="y")
with tf.Session() as sess:
    for i in range(1,10):
        # Initialize variable on each iteration
        sess.run(y.initializer, feed_dict={x: i})
        # Show value
        print("Value of y for x =", i , "is:", sess.run(y))

或者,您可以使用tf.assign操作来执行相同的操作。在这种情况下,在运行赋值时传递x值。
import tensorflow as tf

# Here placeholder shape is not stricly required as tf.Variable already gives the shape
x = tf.placeholder(tf.int32, name="x")
# Specify some initialization value for variable
y = tf.Variable(0, name="y")
# Assign expression value to variable
y_assigned = tf.assign(y, 2 * x** 2 + 5)
# Initialization can be skipped in this case since we always assign new value
with tf.Graph().as_default(), tf.Session() as sess:
    for i in range(1,10):
        # Assign vale to variable in each iteration (and get value after assignment)
        print("Value of y for x =", i , "is:", sess.run(y_assigned, feed_dict={x: i}))

然而,正如Nakor所指出的那样,如果y只是根据x的任何值计算出的结果,那么您可能不需要一个变量。变量的目的是保存在将来调用“run”时将维护的值。因此,只有当您想要根据x设置y的某个值,然后即使x更改(甚至如果x未提供),也要保持相同的值时,才需要它。

我明白了。所以问题在于在给x赋值之前尝试运行初始化程序。这真的很有帮助。非常感谢! - gust

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接