gpt4 book ai didi

python - Tensorflow - 重用模型 InvalidArgumentError

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

我在使用导出的 tensorflow 模型时遇到问题。它不允许我评估我提供的数据集。但是,如果我在与训练相同的 session 中运行评估,那么如果我必须重新训练我的模型只是为了使用另一个数据集进行测试,则不会出现任何问题,这会违背保存模型的目的。生成模型的python文件如下:

x = tf.placeholder(tf.float32, shape=[None, 1024], name = "x")
y_ = tf.placeholder(tf.float32, shape=[None, 10], name = "y_")

#===Model===

#Train
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name= "accuracy")
#Create Saver
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())

for i in range(40000):
batch = shvn_data.nextbatch(100)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %f"%(i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

#Save
saver.save(sess,'svhn_model1')

我保存了输入变量 x 和 y_,通过函数“accuracy”输入,以便我可以运行 precision.eval() 来获得预测的准确性。我以 100 张图像为一组评估数据集,然后对最终预测进行求和。在另一个 session 中评估模型的 python 文件如下:

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config = config)

shvn_data = DataLoader()
saver = tf.train.import_meta_graph('svhn_model1.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))
#sess.run(tf.global_variables_initializer())

#Variables to use with model
graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
y_ = graph.get_tensor_by_name("y_:0")
accuracy = graph.get_tensor_by_name("accuracy:0")
keep_prob = tf.placeholder(tf.float32)


img_whole = np.reshape(shvn_data.test_images,(-1,1024))
batch_whole = np.asarray(shvn_data.test_label.eval(), dtype = np.float32)

total_accuracy = 0
test_count = shvn_data.TEST_COUNT
batch_size = 100
steps = int(math.ceil(test_count/float(batch_size)))

for j in range(steps):
start = j*batch_size
if (j+1)*batch_size > shvn_data.TEST_COUNT:
end = test_count
else:
end = (j+1)*batch_size

img_batch = img_whole[start:end]
label_batch = batch_whole[start:end]
batch_accuracy = accuracy.eval(session = sess, feed_dict={ x: img_batch, y_: label_batch, keep_prob: 1.0}) #ISSUE LIES HERE

print("Test batch %d:%d accuracy %g"%(start,end,batch_accuracy))
total_accuracy += batch_accuracy

print ("Total Accuracy: %f" %(total_accuracy/steps))

错误如下。

  File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1052, in _do_call
raise type(e)(node_def, op, message)

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

Caused by op u'Placeholder', defined at:
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/spyder/utils/ipython/start_kernel.py", line 227, in <module>
main()
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/spyder/utils/ipython/start_kernel.py", line 223, in main
kernel.start()
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 474, in start
ioloop.IOLoop.instance().start()
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tornado/ioloop.py", line 887, in start
handler_func(fd_obj, events)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 276, in dispatcher
return self.dispatch_shell(stream, msg)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
handler(stream, idents, msg)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 390, in execute_request
user_expressions, allow_stdin)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/ipykernel/zmqshell.py", line 501, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2827, in run_ast_nodes
if self.run_code(code, result):
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-33e4fce19d34>", line 1, in <module>
runfile('/home/lwenyao/Desktop/Python/Import_Model.py', wdir='/home/lwenyao/Desktop/Python')
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/home/lwenyao/Desktop/Python/Import_Model.py", line 63, in <module>
saver = tf.train.import_meta_graph('svhn_model1.meta')
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1595, in import_meta_graph
**kwargs)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/meta_graph.py", line 499, in import_scoped_meta_graph
producer_op_list=producer_op_list)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 308, in import_graph_def
op_def=op_def)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/lwenyao/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
self._traceback = _extract_stack()

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

如前所述,如果我在训练模型时在同一 session 中运行评估,则不会出现任何问题。我所做的唯一更改是每次使用导入模型调用 .eval() 时添加参数 session = sess 。抱歉,帖子很长!

最佳答案

好吧,看来错误是由于尝试创建和使用另一个 keep_prob 引起的。导入模型后测试脚本中的变量。 IE。我创建了keep_prob = tf.placeholder(tf.float32,)在训练文件中。然而,accuracy.eval()在测试文件中试图寻找 keep_prob特别是从模型来看。我创建了另一个keep_prob = tf.placeholder(tf.float32,)在测试文件中,以为会是一样的,但事实并非如此。

我通过添加标签修改了训练文件中的代码: keep_prob = tf.placeholder(tf.float32, name="keep_prob")

在我的测试文件中,调用模型的变量:

#Variables to use with model
graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
y_ = graph.get_tensor_by_name("y_:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")#Changed this
accuracy = graph.get_tensor_by_name("accuracy:0")

现在一切正常了。我的代码是从tensorflow的Deep MNIST for Experts修改而来的。

关于python - Tensorflow - 重用模型 InvalidArgumentError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44274618/

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