如何在不重新启动操作的情况下更有效地运行已保存的Tensorflow模型??每次调用predict方法时,都需要花费一些时间才能得到得分结果。
def predict(self, msg):
tensor = self._convector.sentence_to_id_vector(msg)
if tensor is 0:
return 0
else:
graph = tf.Graph()
with graph.as_default():
sess = tf.Session()
saver = tf.train.import_meta_graph("{}/model.ckpt.meta".format(self._model_dir))
saver.restore(sess, ("{}/model.ckpt".format(self._model_dir)))
input = graph.get_operation_by_name('input').outputs[0]
seq_len = graph.get_operation_by_name('lengths').outputs[0]
dropout_keep_prob = graph.get_operation_by_name('dropout_keep_prob').outputs[0]
prediction = graph.get_operation_by_name('final_layer/softmax/predictions').outputs[0]
model_seq_len = self._convector.sequence_len
sample_len = self._convector.sample_len
score = sess.run(prediction, feed_dict={input: tensor.reshape(1, model_seq_len),
seq_len: [sample_len], dropout_keep_prob: 1.0})
print('score result: [{0:.2f}, {1:.2f}]'.format(score[0, 0], score[0, 1]))
return score发布于 2018-05-17 21:16:35
每次运行预测时都会导入图形和会话。
将图形和会话保存在内存中(保持它们在对象或全局变量中可用)。运行一个新的预测,你应该只需要执行sess.run行。
您当前一次运行一个预测。如果你同时运行一堆请求(基本上是批处理预测),模型内部的矩阵乘法会更有效地执行。这并不总是可以做到的,但只要您能够将执行放入内存中,它就能提供良好的性能。
您可以从检查点导入模型。这可能包括对训练有益的操作位置,但对于预测可能不是理想的。使用saved_model导出功能,它将清除它,允许客户端选择最佳位置。这应该允许您正确使用GPU。作为一个副作用,它将为您存储输入和输出张量的名称,这样您就不需要对它们进行硬编码。
最后,确保您拥有正确版本的tensorflow。基本款没有图形处理器支持,甚至没有AVX2支持(现代GPU上的特殊说明)。根据模型和工作负载的不同,它们可能很小,也可能很大。
https://stackoverflow.com/questions/50392006
复制相似问题