Tensorflow – 重用模型的InvalidArgumentError

我在使用导出的Tensorflow模型时遇到了问题。它不允许我评估我提供的数据集。如果我在训练的同一个会话中运行评估,则没有问题,但是,如果每次测试新数据集时都需要重新训练模型,这就失去了保存模型的意义。我生成模型的Python文件如下:

x = tf.placeholder(tf.float32, shape=[None, 1024], name = "x")
y_ = tf.placeholder(tf.float32, shape=[None, 10], name = "y_")
#===模型===#
#训练
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")
#创建保存器
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("步骤 %d, 训练准确率 %f"%(i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
#保存
saver.save(sess,'svhn_model1')

我保存了输入变量x和y_,以便通过函数’accuracy’输入,以便我可以运行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())
#使用模型的变量
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}) #问题在这里
    print("测试批次 %d:%d 准确率 %g"%(start,end,batch_accuracy))
    total_accuracy += batch_accuracy
print ("总准确率: %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")

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

#使用模型的变量
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")
#更改了这个
accuracy = graph.get_tensor_by_name("accuracy:0")

现在它工作得很好。我的代码是从Tensorflow的Deep MNIST for Experts修改而来的。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注