Tensorflow 错误:InvalidArgumentError:您必须使用 dtype float 和 shape[?:784]] 为占位符张量“Placeholder”提供一个值

Posted

技术标签:

【中文标题】Tensorflow 错误:InvalidArgumentError:您必须使用 dtype float 和 shape[?:784]] 为占位符张量“Placeholder”提供一个值【英文标题】:Tensorflow error: InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape[?:784]] 【发布时间】:2018-02-26 16:57:36 【问题描述】:

我在 ubuntu 16.04 上运行 tensorflow 版本 1.3.0。我正在玩一个代码,我的主要目的是在 tensorboard 上可视化图表。在运行代码时,当第一次运行代码时,一切似乎都很好。但是在那之后,当我第二次运行代码时,我得到了这个错误:

InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784]
 [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

这是回溯:

InvalidArgumentError Traceback (most recent call last)
<ipython-input-26-149c9b9d8878> in <module>()
 11             sess.run(optimizer, feed_dict=x: batch_xs, y: 
 batch_ys)
 12             avg_cost += sess.run(cost_function, feed_dict=x: 
 batch_xs, y: batch_ys)/total_batch
 ---> 13             summary_str = sess.run(merged_summary_op, 
feed_dict=x: batch_xs, y: batch_ys)
 14             summary_writer.add_summary(summary_str, 
 iteration*total_batch + i)
 15         if iteration % display_step == 0:

/home/niraj/anaconda2/lib/python2.7/site-
packages/tensorflow/python/client/session.pyc in run(self, fetches, 
feed_dict, options, run_metadata)
893     try:
894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
896       if run_metadata:
897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

InvalidArgumentError                      Traceback (most recent call 
last)
<ipython-input-26-149c9b9d8878> in <module>()
11             sess.run(optimizer, feed_dict=x: batch_xs, y: 
batch_ys)
12             avg_cost += sess.run(cost_function, feed_dict=x: 
batch_xs, y: batch_ys)/total_batch
---> 13             summary_str = sess.run(merged_summary_op, 
feed_dict=x: batch_xs, y: batch_ys)
14             summary_writer.add_summary(summary_str, 
iteration*total_batch + i)
15         if iteration % display_step == 0:

/home/niraj/anaconda2/lib/python2.7/site-
packages/tensorflow/python/client/session.pyc in run(self, fetches, 
feed_dict, options, run_metadata)
893     try:
894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
896       if run_metadata:
897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/niraj/anaconda2/lib/python2.7/site-
packages/tensorflow/python/client/session.pyc in _run(self, handle, 
fetches, feed_dict, options, run_metadata)
1122     if final_fetches or final_targets or (handle and 
feed_dict_tensor):
1123       results = self._do_run(handle, final_targets, 
final_fetches,
-> 1124                              feed_dict_tensor, options, 
run_metadata)
1125     else:
1126       results = []

/home/niraj/anaconda2/lib/python2.7/site-
packages/tensorflow/python/client/session.pyc in _do_run(self, handle,
target_list, fetch_list, feed_dict, options, run_metadata)
1319     if handle is None:
1320       return self._do_call(_run_fn, self._session, feeds, 
fetches, targets,
-> 1321                            options, run_metadata)
1322     else:
1323       return self._do_call(_prun_fn, self._session, handle, 
feeds, fetches)

/home/niraj/anaconda2/lib/python2.7/site-
packages/tensorflow/python/client/session.pyc in _do_call(self, fn, 
*args)
1338         except KeyError:
1339           pass
-> 1340       raise type(e)(node_def, op, message)
1341 
1342   def _extend_graph(self):

代码如下:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/home/niraj/Documents/artificial 
intelligence/projects/tensorboard", one_hot=True)

learning_rate = 0.01
training_iteration = 200
batch_size = 100
display_step = 2

# TF graph input
x = tf.placeholder('float32', [None, 784]) # mnist data image of shape 
28*28=784
y = tf.placeholder('float32',[None, 10]) # 0-9 digits recognition => 
10 classes

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

with tf.name_scope("Wx_b") as scope:
    model = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax

w_h = tf.summary.histogram("weights", W)
b_h = tf.summary.histogram("biases", b)

with tf.name_scope("cost_function") as scope:
    cost_function = -tf.reduce_sum(y*tf.log(model))
tf.summary.scalar("cost_function", cost_function)

with tf.name_scope("train") as scope:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function)

init = tf.global_variables_initializer()
merged_summary_op = tf.summary.merge_all()
with tf.Session() as sess:
    sess.run(init)
summary_writer = tf.summary.FileWriter('/home/niraj/Documents/artificial intelligence/projects/tensorboard', graph=sess.graph)
for iteration in range(training_iteration):
    avg_cost = 0
    total_batch = int(mnist.train.num_examples/batch_size)
    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        sess.run(optimizer, feed_dict=x: batch_xs, y: batch_ys)
        avg_cost += sess.run(cost_function, feed_dict=x: batch_xs, y: batch_ys)/total_batch
        summary_str = sess.run(merged_summary_op, feed_dict=x: batch_xs, y: batch_ys)    
        summary_writer.add_summary(summary_str, iteration*total_batch + i)
    if iteration % display_step == 0:
        print "Iteration:", '%04d' % (iteration + 1), "cost=", ":.9f".format(avg_cost)


print "Tuning completed!"
predictions = tf.equal(tf.argmax(model, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(predictions, "float"))
print "Accuracy:", accuracy.eval(x: mnist.test.images, y: mnist.test.labels)

提醒您此代码在我第一次运行时运行良好。在第二次运行时出现错误。但是当我关闭笔记本和 jupyter 终端然后重新打开它并再次运行时,它将再次运行而没有任何错误,并且在第二次运行时出现上述错误。

【问题讨论】:

【参考方案1】:

我遇到了同样的问题,到目前为止发现当我删除摘要操作时不会发生错误。如果我找到一种方法让它与摘要一起使用,我会更新它......

更新:

我按照这里的建议解决了这个问题:Error with feed values for placeholders when running the merged summary op

我用tf.summary.merge([summary_var1, summary_var2])替换了tf.summary.merge_all

解决此问题的更简单方法是在循环结束时调用 tf.reset_default_graph(),然后再开始训练。

【讨论】:

是的。 tf.reset_default_graph() 正在工作。实际上,前几天我正在阅读这本书“使用 scikit-learn 和 tensorflow 动手”,我偶然发现了一个提示,其中明确提到了“在 Jupyter(或 Python shell)中,运行相同的命令是很常见的尝试时不止一次。因此,您最终可能会得到一个包含许多重复节点的默认图。一种解决方案是重新启动 Jupyter 内核(或 Python shell),但更方便的解决方案是重置默认值通过运行 tf.reset_default_graph() 绘制图形。"

以上是关于Tensorflow 错误:InvalidArgumentError:您必须使用 dtype float 和 shape[?:784]] 为占位符张量“Placeholder”提供一个值的主要内容,如果未能解决你的问题,请参考以下文章

Tensorflow 导入错误:没有名为“tensorflow”的模块

tensorflow 有错误

在pycharm中安装tensorflow引起的错误

显式 tensorflow 会话在 Tensorflow/nmt 中给出获取错误

在aarch64上安装Tensorflow:错误:找不到满足tensorflow要求的版本

使用 TensorFlow 训练图像时使用 GPU 错误