Feed数据的形状与tensorflow中占位符的形状不匹配

时间:2018-06-05 05:57:30

标签: python tensorflow

当我使用tensorflow实现XOR时出错。该错误消息表明输入数据的形状与占位符的形状不匹配。代码如下:

#!/usr/bin/python
import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32,shape=[None,2])
data = np.random.rand(2,2)
print data.shape
print data
y = tf.add(x,x)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(y,{x:data})
print sess.run(y)

错误消息:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,2]

[[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,2], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

2 个答案:

答案 0 :(得分:2)

存在语法错误。正确的代码应该是:

x = tf.placeholder(dtype=tf.float32,shape=[None,2])
data = np.random.rand(2,2)
print data.shape
print data
y = tf.add(x,x)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
y_result = sess.run(y,{x:data})
print y_result 

答案 1 :(得分:1)

这很简单。您只需提供feed_dict即可在最终的x来电中填充sess.run。发生此错误是因为图表必须一直执行tf.Tensor提供给sess.run()的所有内容。由于y取决于xx是占位符,因此您必须为feed_dict电话提供sess.run()

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=[None, 2])

data = np.random.rand(2, 2)

y = tf.add(x, x)

sess = tf.Session()

sess.run(tf.global_variables_initializer())

# Note that I'm saving the output of the sess.run call.
y_out = sess.run(y, feed_dict={x: data})

# Here's your bug. You haven't provided a feed_dict in the line below.
# print(sess.run(y))
print("y_out")
print(y_out)