tensorflow - 如何更有效地在 Tensorflow 中运行图表?
问题描述
如何在不重新启动操作的情况下更有效地运行已保存的 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
解决方案
每次运行预测时,您都在导入图表和会话。
将图形和会话保存在内存中(保持它们可用,在对象或全局变量中)。运行一个新的预测你应该只需要执行sess.run
line.
您目前一次运行 1 个预测。如果同时运行一堆请求(基本上是批处理预测),模型内部的矩阵乘法会更有效地执行。这并不总是可行的,但只要您可以在内存中执行,它确实可以提供良好的性能。
您从检查点导入模型。这可能包括有利于训练的操作放置,但可能不适合预测。使用 saved_model 导出功能,它会清除它,允许客户选择最佳位置。这应该允许您正确使用 GPU。作为副作用,它将为您存储输入和输出张量的名称,这样您就不需要对它们进行硬编码。
最后,确保您拥有正确版本的 tensorflow。基本的没有 GPU 支持,甚至没有 AVX2 支持(现代 CPU 上的特殊指令)。根据模型和工作量,它们可能会产生或大或小的影响。
推荐阅读
- git - 为什么在推送到我的 github 存储库时出现此错误
- bash - 如何使用 bash 命令输出不带冒号的日期
- c++ - 显示 N 个素数
- angular - 即使表单未经过验证,Angular 7 在组件加载时设置反应表单的值也会启用保存按钮
- wcf - 在浏览器中运行 WCF 服务主机
- python - Numpy / Chebyshev 模块:获取价值
- swift - 如何在 Swift 中将字典转换为自定义类型?
- python - Pandas:从 groupby 创建一个数据框,并在不同的列上应用 sum 和 mean
- java - Null varargs 导致警告:“为 varargs 参数创建未经检查的泛型数组”
- embedded - Yocto:使用其他配方的静态库,