我用tensorflow编写了以下快速程序来打印斐波那契数。初始fib编号被初始化为占位符x1
和x2
。然而,当我试图输入session.run
中占位符的值时,会导致错误:
InvalidArgumentError: You must feed a value for placeholder tensor 'x2' with dtype int64 and shape [1]
你能帮我理解并解决我的代码问题吗?
import tensorflow as tf
session = tf.InteractiveSession()
import numpy as np
ones = tf.ones((1,))
n = 10
x1 = tf.placeholder(tf.int64, [1], name='x1')
x2 = tf.placeholder(tf.int64, [1], name='x2')
temp = tf.Variable(ones, name='temp')
tf.initialize_all_variables().run()
fib_nums = [x1, x2]
for i in range(100):
temp = x1 + x2
x1 = x2
x2 = temp
fib_nums.append(temp)
series = tf.stack(fib_nums)
print(np.ones(1).astype(np.int64))
session.run(series, feed_dict={x1:np.ones(1).astype(np.int64), x2:np.ones(1).astype(np.int64)})
print(series.eval())
这里有几个错误。首先,由于您重用Python名称x1
和x2
,因此当您在feed_dict
中给定它们时,它们不再引用占位符,而是引用循环的最后结果。因此,您应该更改代码,使您在feed_dict
中给出的键真正成为占位符。其次,首先用feed_dict
调用session.run
,这是正确的,但随后调用series.eval()
,这与前一行基本相同,只是在这种情况下没有提供feed_dict
,所以它不起作用。您实际上不需要调用series.eval()
,只需获取session.run
返回的值即可。你的固定程序可能看起来像这样:
import tensorflow as tf
session = tf.InteractiveSession()
import numpy as np
ones = tf.ones((1,))
n = 10
# Reserve these Python names for the placeholders
x1_ph = tf.placeholder(tf.int64, [1], name='x1')
x2_ph = tf.placeholder(tf.int64, [1], name='x2')
temp = tf.Variable(ones, name='temp')
tf.initialize_all_variables().run()
# Use placeholders as initial values in the iterations
x1, x2 = x1_ph, x2_ph
fib_nums = [x1, x2]
for i in range(100):
temp = x1 + x2
x1 = x2
x2 = temp
fib_nums.append(temp)
series = tf.stack(fib_nums)
print(np.ones(1).astype(np.int64))
# You can just give lists as inputs and TensorFlow will convert their type
series_val = sess.run(series, feed_dict={x1_ph: [1], x2_ph: [1]})
print(series_val)
输出:
[1]
[[ 1]
[ 1]
[ 2]
[ 3]
[ 5]
[ 8]
[ 13]
[ 21]
[ 34]
[ 55]
[ 89]
[ 144]
[ 233]
[ 377]
[ 610]
[ 987]
[ 1597]
[ 2584]
...
我认为另一个变体是使用tf.identity.
y = tf.identity(x1)
y1 = tf.identity(x2)
fib_nums = [y, y1]
for i in range(100):
temp = y + y1
y = y1
y1 = temp
fib_nums.append(temp)
这个占位符修改问题也在这里讨论
这是获得该系列的又一种方式。
def cond(i, x_next, x_prev):
return x_next <= 100
def body( i, x_next, x_prev ):
nextinseries = x_next + x_prev
next = tf.Print(x_next, [x_next], message="Next is : ")
prev = tf.Print(x_prev, [x_prev], message="Previous is : ")
with tf.control_dependencies([nextinseries]):
prev = tf.identity( next )
return [i + 1, nextinseries , prev ]
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(tf.while_loop(cond, body, [1, 1, 1]))
只需将tf.placeholder
更改为张量,它就可以使用
x1 = tf.ones(dtype=tf.int64, shape=1, name='x1')
x2 = tf.ones(dtype=tf.int64, shape=1, name='x2')