python - 如何正确设置tensorflow中占位符的值?

标签 python python-3.x tensorflow

我在 tensorflow 中编写了以下快速程序来打印斐波那契数。初始 fib 数字初始化为占位符 x1x2 但是,当我尝试在 session.run 中提供占位符的值时,会导致错误:

InvalidArgumentError:您必须使用 dtype int64 和形状 [1] 为占位符张量“x2”提供值

您能帮助我理解并解决我的代码中的问题吗?

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 名称 x1x2,因此当您在 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]
...

关于python - 如何正确设置tensorflow中占位符的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53079511/

相关文章:

python - 如何在 Keras 中使用 Hausdorff 度量?

python - 无法过滤 Gmail API 推送通知

python - 每个服务器前缀

python - 从 tf.tensor 的一个操作中提取多列

python - Doctests 在 C 扩展和 Python3 上因 UnicodeDecodeError 而失败

python - 如何在 Bokeh 图的轴刻度中获得一个空格作为千​​位分隔符

amazon-web-services - 适用于tensorflow和pymysql的Sagemaker内核

python - 有没有办法可以用 python 将屏幕截图的输出保存在列表中

python - 使用python的子进程通过curl下载文件

python - 为什么我不能从下一个日期期间减去一个日期期间并转换为整数?