gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:05:13 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com