Tensorflow加载模型,在测试集上测试,运行到sess.run是报错,InvalidArgumentError: You must feed a value for placeholder tensor 'y_true' with dtype float and shape [?,50],但是我检查了类型和形状有一致,为什么feed时会出错。
def TestModel():
epochs=1
path="g:/pythonCode/入门篇TestDataset/"
filename, image = get_batch_data(path,epochs)
print("image:",image)
accuracy=0
i=0
accuracy_list=[]
loss_list=[]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
if os.path.exists("./tmp/model/checkpoint"):
saver=tf.train.import_meta_graph("./tmp/model/CNNmodel.ckpt.meta")
saver.restore(sess,tf.train.latest_checkpoint("./tmp/model/"))
else :
print("not finding CNNmodel")
try:
while not coord.should_stop():
i=i+1
filename_value, image_value = sess.run([filename, image])
print("image_value:",image_value.dtype,image_value.shape)
labels,labelsNum = filename2label(filename_value, 'G:/pythonCode/入门篇TestDataset/class.csv')
labels_one_hot = tf.one_hot(labels, depth=labelsNum)
print("labels_one_hot:",labels_one_hot)
labels_one_hot = tf.one_hot(labels, depth=labelsNum).eval()
graph=tf.get_default_graph()
x = graph.get_tensor_by_name('x_1:0')
print("x=",x)
y_true=graph.get_tensor_by_name('y_true_1:0')
print("y_true=",y_true)
#n=labels_one_hot.size()
#y_true.set_shape([959,50])
# y_predict=tf.get_collection('pred_network')[0]
# y_predict_value,y_true_value = sess.run([y_predict,y_true], feed_dict={x: image_value, y_true: labels_value})
# equal_list = tf.equal(np.argmax(y_true_value,axis=1), np.argmax(y_predict_value,axis=1))
# accuracy = accuracy +tf.reduce_mean(tf.cast(equal_list, tf.float32))
loss=tf.get_collection('pred_network')[1]
print("loss=",loss)
optimizer=tf.get_collection('pred_network')[2]
print("optimizer=",optimizer)
accuracy=tf.get_collection('pred_network')[3]
print("accuracy=",accuracy)
_, error, accuracy_value = sess.run([optimizer, loss, accuracy], feed_dict={x: image_value, y_true: labels_one_hot})
accuracy_list.append(accuracy_value)
loss_list.append(error)
except tf.errors.OutOfRangeError:
print('Done training')
finally:
# 回收线程
coord.request_stop()
coord.join(threads)
print("测试集上的损失为 %f,准确率为 %f" % (np.mean(loss_list),np.mean(accuracy_list)))
return
if __name__ == "__main__":
#TrainModel()
TestModel()
runfile('G:/pythonCode/2022-1-5.py', wdir='G:/pythonCode')
**image: Tensor("batch_23:1", shape=(?, 60, 60, 1), dtype=float32)
INFO:tensorflow:Restoring parameters from ./tmp/model/CNNmodel.ckpt
image_value: float32 (959, 60, 60, 1)
labels_one_hot: Tensor("one_hot_364:0", shape=(959, 50), dtype=float32)
x= Tensor("x_1:0", shape=(?, 60, 60, 1), dtype=float32)
y_true= Tensor("y_true_1:0", shape=(959, 50), dtype=float32)
loss= Tensor("Mean:0", shape=(), dtype=float32)
optimizer= name: "Adam"
op: "NoOp"
input: "^Adam/update_conv1/conv1_weights/ApplyAdam"
input: "^Adam/update_conv1/conv1_bias/ApplyAdam"
input: "^Adam/update_conv2/conv2_weights/ApplyAdam"
input: "^Adam/update_conv2/conv2_bias/ApplyAdam"
input: "^Adam/update_full_connection/weights_fc/ApplyAdam"
input: "^Adam/update_full_connection/bias_fc/ApplyAdam"
input: "^Adam/Assign"
input: "^Adam/Assign_1"
accuracy= Tensor("Mean_1:0", shape=(), dtype=float32)**
Traceback (most recent call last):
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\client\session.py", line 1334, in _do_call
return fn(*args)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\client\session.py", line 1319, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\client\session.py", line 1407, in _call_tf_sessionrun
run_metadata)
InvalidArgumentError: You must feed a value for placeholder tensor 'y_true' with dtype float and shape [?,50]
[[{{node y_true}} = Placeholder[dtype=DT_FLOAT, shape=[?,50], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "G:\pythonCode\2022-1-5.py", line 310, in <module>
TestModel()
File "G:\pythonCode\2022-1-5.py", line 293, in TestModel
_, error, accuracy_value = sess.run([optimizer, loss, accuracy], feed_dict={x: image_value, y_true: labels_one_hot})
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\client\session.py", line 929, in run
run_metadata_ptr)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\client\session.py", line 1152, in _run
feed_dict_tensor, options, run_metadata)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\client\session.py", line 1328, in _do_run
run_metadata)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\client\session.py", line 1348, in _do_call
raise type(e)(node_def, op, message)
InvalidArgumentError: You must feed a value for placeholder tensor 'y_true' with dtype float and shape [?,50]
[[node y_true (defined at G:\pythonCode\2022-1-4.py:167) = Placeholder[dtype=DT_FLOAT, shape=[?,50], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
Caused by op 'y_true', defined at:
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\spyder_kernels\console\__main__.py", line 23, in <module>
start.main()
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\spyder_kernels\console\start.py", line 300, in main
kernel.start()
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\ipykernel\kernelapp.py", line 612, in start
self.io_loop.start()
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\platform\asyncio.py", line 199, in start
self.asyncio_loop.run_forever()
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\asyncio\base_events.py", line 442, in run_forever
self._run_once()
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\asyncio\base_events.py", line 1462, in _run_once
handle._run()
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\asyncio\events.py", line 145, in _run
self._callback(*self._args)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\ioloop.py", line 688, in <lambda>
lambda f: self._run_callback(functools.partial(callback, future))
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\ioloop.py", line 741, in _run_callback
ret = callback()
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 814, in inner
self.ctx_run(self.run)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 162, in _fake_ctx_run
return f(*args, **kw)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 775, in run
yielded = self.gen.send(value)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\ipykernel\kernelbase.py", line 365, in process_one
yield gen.maybe_future(dispatch(*args))
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 234, in wrapper
yielded = ctx_run(next, result)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 162, in _fake_ctx_run
return f(*args, **kw)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\ipykernel\kernelbase.py", line 268, in dispatch_shell
yield gen.maybe_future(handler(stream, idents, msg))
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 234, in wrapper
yielded = ctx_run(next, result)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 162, in _fake_ctx_run
return f(*args, **kw)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\ipykernel\kernelbase.py", line 545, in execute_request
user_expressions, allow_stdin,
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 234, in wrapper
yielded = ctx_run(next, result)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tornado\gen.py", line 162, in _fake_ctx_run
return f(*args, **kw)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\ipykernel\ipkernel.py", line 306, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\ipykernel\zmqshell.py", line 536, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\IPython\core\interactiveshell.py", line 2867, in run_cell
raw_cell, store_history, silent, shell_futures)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\IPython\core\interactiveshell.py", line 2895, in _run_cell
return runner(coro)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\IPython\core\async_helpers.py", line 68, in _pseudo_sync_runner
coro.send(None)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\IPython\core\interactiveshell.py", line 3072, in run_cell_async
interactivity=interactivity, compiler=compiler, result=result)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\IPython\core\interactiveshell.py", line 3263, in run_ast_nodes
if (await self.run_code(code, result, async_=asy)):
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-34ac56b441df>", line 1, in <module>
runfile('G:/pythonCode/2022-1-4.py', wdir='G:/pythonCode')
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 566, in runfile
post_mortem=post_mortem)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 453, in exec_code
exec(compiled, ns_globals, ns_locals)
File "G:\pythonCode\2022-1-4.py", line 370, in <module>
File "G:\pythonCode\2022-1-4.py", line 167, in TrainModel
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\ops\array_ops.py", line 1747, in placeholder
return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 6251, in placeholder
"Placeholder", dtype=dtype, shape=shape, name=name)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\util\deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\framework\ops.py", line 3274, in create_op
op_def=op_def)
File "G:\PythonInstall\Anaconda\envs\TensorFlow\lib\site-packages\tensorflow\python\framework\ops.py", line 1770, in __init__
self._traceback = tf_stack.extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'y_true' with dtype float and shape [?,50]
[[node y_true (defined at G:\pythonCode\2022-1-4.py:167) = Placeholder[dtype=DT_FLOAT, shape=[?,50], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
输出类型和形状,发现都是一致的,想不明白是什么原因,请赐教