Tensorflow - 重用模型InvalidArgumentError

问题描述:

我有使用导出的张量流模型的问题。它不允许我评估我提供的数据集。如果我在与培训相同的环节中运行评估,那么没有任何问题会影响保存模型的目的,如果我必须重新训练我的模型来测试其他数据集。用于生成模型的Python文件是这样:Tensorflow - 重用模型InvalidArgumentError

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.eval()获得的精度预测。我分批评估了100幅图像的数据集,然后总结了最终的预测结果。在另一个会话中评估模型的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"]()]] 

如前所述,如果我在训练模型时在同一个会话中运行它,评估没有问题。我做的唯一更改是每次在使用导入的模型时调用.eval()时,我添加了参数session = sess。对不起,很长的帖子!

好的,看起来这个错误是由于在导入模型之后尝试在测试脚本中创建并使用另一个keep_prob变量而引起的。即我在培训文件中创建了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的专家深层MNIST