【问题标题】:Exporting and loading tf.contrib.estimator in Tensorflow 1.3 for prediction in python without using Tensorflow Serving在 Tensorflow 1.3 中导出和加载 tf.contrib.estimator 以在 python 中进行预测而不使用 Tensorflow Serving
【发布时间】:2017-10-13 00:08:17
【问题描述】:

我正在使用具有宽和深特征列的 tf.contrib.learn.DNNLinearCombinedRegressor。我使用 input_fn 将数据发送到此回归器进行训练。我既有真实特征又有分类特征,因此我的深层特征列由具有嵌入的稀疏列和实值列组成。而我的线性列是实值列。训练后,我可以使用 estimator.predict_scores() 方法天真地访问训练好的模型进行预测。但是,据我了解,这会从检查点文件重新创建张量流图,这对于我的预期应用程序来说很慢。然后我尝试使用 estimator.export_savedmodel() 来查看是否可以在我的应用程序中进行实际预测之前保存和加载图表。但我被它困住了。我面临以下问题:

  1. 为了导出,我做了以下操作:

    feature_spec = tf.feature_column.make_parse_example_spec(deep_feature_cols)
    
    export_input_fn = tf.contrib.learn.utils.build_parsing_serving_input_fn(feature_spec) 
    
    servable_model_path = regressor.export_savedmodel(export_dir_base = servable_model_dir, serving_input_fn = export_input_fn, as_text= True)
    

(请注意,由于 VarLen 功能列 - 嵌入列,原始和默认解析函数对我不起作用)。由于我仅使用我的深层列构建 feature_spec,我不明白保存的模型如何知道我用于线性列的内容。我不知道如何组合这两种类型的列来保存/导出。

  1. 虽然我能够成功导出经过训练的回归模型,但我不知道如何将其用于预测。我已经看过使用 Tensorflow Serving 执行此操作的教程,例如 this。但是,我只想在 python 中加载和使用一些简单的东西。我正在开发 Windows 中的交互式 GUI 应用程序,因此不想使用 bazel 为 Tensorflow Serving 构建保存的模型。我从post 尝试了以下操作,但它不适用于我的 input_fn

    from tensorflow.contrib import predictor
    predict_fn = predictor.from_saved_model(servable_model_path)
    predictions = predict_fn(get_input_fn(X, y, LABEL, num_epochs=1, shuffle=False))
    

其中 get_input_fn 是我的自定义 input_fn。当我运行此代码时,我收到以下错误:

AttributeError      Traceback (most recent call last)
<ipython-input-15-128f4d1ba155> in <module>()
----> 1 predictions = predict_fn(get_input_fn(X, y, LABEL, num_epochs=1, 
shuffle=False))

~\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-
packages\tensorflow\contrib\predictor\predictor.py in __call__(self, input_dict)
 63     """
 64     # TODO(jamieas): make validation optional?
---> 65     input_keys = set(input_dict.keys())
 66     expected_keys = set(self.feed_tensors.keys())
 67     unexpected_keys = input_keys - expected_keys

AttributeError: 'function' object has no attribute 'keys'

感谢任何输入。我在 Windows 10 上,在 Anaconda 虚拟环境中使用 Tensorflow 1.3 和 Python 3.5。

【问题讨论】:

  • 我遇到了同样的错误 - 你有进步吗?任何指针将不胜感激。

标签: python tensorflow


【解决方案1】:

再探查一下,predict_fn 需要一个字典,其键设置为与模型期望的特征变量完全相同的名称。在我的 CNN 模型中,输入是“输入”,如下所示:

def _cnn_model_fn(features, labels, mode):
  # Input Layer
  print("features shape", features['inputs'])

这是我在 predict_fn 中传递的内容,其中 myimage 是一个扁平的 np.array。

predictions = predict_fn({"inputs": [myimage]})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2017-07-16
    • 2020-01-07
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多