tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'x_1' with dtype float and shape [?,227,227,3]

记一次超级蠢超级折磨我的bug。

报错内容:

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'x_1' with dtype float and shape [?,227,227,3]
[[Node: x_1 = Placeholder[dtype=DT_FLOAT, shape=[?,227,227,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: fc3/_33 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_110_fc3", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

错误理解起来很简单,没有给placeholder ‘x_1’赋值。

这是我的预测代码:

image = Image.open(imagefile)
image = image.resize([227, 227])
image_array = np.array(image)
image_array = image_array.astype(float)
image = np.reshape(image_array, [1, 227, 227, 3])
saver = tf.train.import_meta_graph("/home/ubuntu/demo/package/5.8_2000op_256batch/AlexNetModel.ckpt.meta")
graph = tf.get_default_graph()
prediction = graph.get_tensor_by_name("fc3:0")
x = graph.get_tensor_by_name("x:0")
with tf.Session() as sess:
  saver.restore(sess, "/home/ubuntu/demo/package/5.8_2000op_256batch/AlexNetModel.ckpt")
  Predict = sess.run(prediction, feed_dict={x: image})
  max_index = np.argmax(Predict)
  if max_index==0:
    return "cat"
  else:
    return "dog"

之前是觉得image格式有问题,不能作为输入给x。

因为最初始,源码是这样写的:

image = Image.open(imagefile)
image = image.resize([227, 227])
image_array = np.array(image)

image = tf.cast(image_array,tf.float32)
image = tf.image.per_image_standardization(image)
image = tf.reshape(image, [1, 227, 227, 3])

而使用tf的方法,返回值是一个tensor,而tensor是无法赋值给placeholder定义的数据类型。

  • sess.run()第一个参数是要fetch的变量,这个变量的类型只能是tensor或者string, 后面如果要加feed_dict = {}, 注意feed的数据类型可以是Python scalars, strings, lists, numpy ndarrays, or TensorHandles,不能是tensor.fecth得到的变量是<type 'numpy.ndarray'>。一句话就是,在运行图的时,tensor用sess.run()取出来,然后再feed进去。

所以就把image的形状变化,tf.reshape()改为了np.reshape(),但是还有问题,报错为上面的You must feed a value for placeholder tensor 'x_1' with dtype float and shape [?,227,227,3].......

完了彻底把我整懵逼了,不知道应该给x什么样的输入了,但是又好奇怪,placeholder tensor 'x_1'那里来的,没有定义过 'x_1'这种东西呀。贴一下训练代码,placeholder的申请。

x = tf.placeholder(tf.float32, [None, 227, 227, 3],name='x')
y = tf.placeholder(tf.float32, [None, n_classes])

感觉没问题啊,挺好的啊。如果代码真的是这样确实没啥问题挺好的,关键是自己脑残,x = tf.placeholder(tf.float32, [None, 227, 227, 3],name='x')申请了两遍

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'x_1' with dtype float and shape [?,227,227,3]

删掉一个。OK了。很烦,困扰了自己好几天

上一篇:iOS 用collectionview 做的无限图片滚动 广告banner适用


下一篇:【err】tensorflow.python.framework.errors_impl.OutOfRangeError: RandomShuffleQueue