如何创建以占位符作为初始值设定项的变量?下图分解为:
InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float
[[node Placeholder_1 (defined at <ipython-input-10-b8d54264dc85>:3) = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
我的代码:
tf.reset_default_graph()
a = tf.placeholder(dtype=tf.float32,shape=())
d = tf.placeholder(dtype=tf.float32,shape=())
b = tf.get_variable(name='b',initializer=d)
c=a+d
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(c, feed_dict={a:5.,d:10.}))
tensorflow 中关于初始化程序的文档说:
Initializer for the variable if one is created. Can either be an initializer object or a Tensor. If it's a Tensor, its shape must be known unless validate_shape is False.
但是,如果我注释掉创建 b 的行,代码似乎可以运行。我的提取甚至不依赖于 b。
我如何着手创建根据某些占位符初始化的变量?
请您参考如下方法:
我认为您的问题在 https://github.com/tensorflow/tensorflow/issues/4920 中有所描述
我的解决方法是使用 tf.assign ,它就像一个惰性初始化程序,形状将在 d 和 tf.zeros_like。为了了解它是如何工作的,我将 b 设为资源变量,以便它在 sess.run 调用之间保持状态。
tf.reset_default_graph()
a = tf.placeholder(dtype=tf.float32,shape=(), name='a')
d = tf.placeholder(dtype=tf.float32,shape=(), name='d')
b = tf.get_variable(name='b', initializer=tf.zeros_like(d), use_resource=True)
b_init = tf.assign(b, d)
c=a+d
add_one = tf.assign(b,tf.add(b,tf.ones_like(b)))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run([c, b_init], feed_dict={a:5.,d:10.}))
for i in range(10):
sess.run(add_one)
print(sess.run([c,b], feed_dict={a:5.,d:10.}))
输出
[15.0, 10.0]
[15.0, 11.0]
[15.0, 12.0]
[15.0, 13.0]
[15.0, 14.0]
[15.0, 15.0]
[15.0, 16.0]
[15.0, 17.0]
[15.0, 18.0]
[15.0, 19.0]
[15.0, 20.0]
