首页 > 解决方案 > tensorflow自定义估计器的predictions和export_outputs有什么区别,如何使用?

问题描述

我想保存我的张量流模型并在以后恢复它以进行预测,并且我使用估计器export_savedmodel来保存模型。

至于文档,我serving_input_receiver_fn用来指定输入。我也想用来export_outputs指定输出,但是我不明白predictions和export_outputs的区别?

if mode == tf.estimator.ModeKeys.PREDICT:
    export_outputs = {
        'predict_output': tf.estimator.export.PredictOutput({
            'class_ids': predicted_classes[:, tf.newaxis],
            'probabilities': tf.nn.softmax(logits),
            'logits': logits
        })
    }
    predictions = {
        'class': predicted_classes[:, tf.newaxis],
        'prob': tf.nn.softmax(logits),
        'logits': logits,
    }
    return tf.estimator.EstimatorSpec(mode, predictions=predictions, export_outputs=export_outputs)

另一个问题是如何在会话中使用保存的 pb 模型进行预测?

with tf.Session(graph=tf.Graph()) as sess:
    model_path = 'model/1535016490'
    tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_path)
    inputs = sess.graph.get_tensor_by_name('input_example:0')
    # how to get the output tensor?
    # outputs = sess.graph.get_tensor_by_name()
    res = sess.run([outputs], feed_dict={inputs: examples})

我可以使用tensorflow.contrib.predictor来获得一些结果,但我想要一种通用方法,我们的团队将使用 C++ 恢复模型。所以我认为获取张量并在会话中运行它们也许是我想要的方法?

from tensorflow.contrib import predictor

predict_fn = predictor.from_saved_model(
    export_dir='model/1535012949',
    signature_def_key='predict_output',
    tags=tf.saved_model.tag_constants.SERVING
)

predictions = predict_fn({'examples': examples})

非常感谢您的帮助!

标签: tensorflowtensorflow-serving

解决方案


对于第一个问题,我不是 100% 确定,但我相信在 tf.session() 中调用 estimator.predict(...) 时会使用预测,而在服务期间使用 export_outputs。我的意思是,如果你有一个 docker tensorflow/serving 或其他一些服务器正在运行并加载了一个保存的模型,并且你使用输入查询它,那么响应将基于你的 export_outputs 定义。

对不起,我不知道你的第二个问题的好答案。在这一点上,有很多不同的方法可以保存 tensorflow 模型,以至于很难说清楚。我会说查看保存和恢复的官方文档,并根据您保存模型的方式以及是否使用估算器找到建议的恢复方法。

此外,#tensorflow 头版上的这个问题可能很有用。

祝你好运~~


推荐阅读