我已经在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())
答案 0 :(得分:2)
这里有两个错误。首先,由于您正在重用Python名称x1
和x2
,因此当您在feed_dict
中使用它们时,它们不再引用占位符,而是引用循环的最后结果。因此,您应该更改代码,以便在feed_dict
中输入的键确实是占位符。其次,您先使用正确的session.run
调用feed_dict
,然后再调用series.eval()
,它与上一行基本相同,只是您没有提供{{ 1}},因此无法正常工作。您实际上并不需要调用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)
我认为使用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)
此占位符修改问题也在here中进行了讨论
这是获得系列的另一种方法。
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]))
答案 2 :(得分:0)
只需将tf.placeholder
更改为张量即可使用
x1 = tf.ones(dtype=tf.int64, shape=1, name='x1')
x2 = tf.ones(dtype=tf.int64, shape=1, name='x2')