【问题标题】:Saving, loading, and predicting from a TensorFlow Estimator model (2.0)从 TensorFlow Estimator 模型 (2.0) 保存、加载和预测
【发布时间】:2020-03-16 11:31:16
【问题描述】:

TF2 中是否有序列化和恢复Estimator 模型的指南?文档参差不齐,其中大部分没有更新到 TF2。我还没有在任何地方看到一个清晰且完整的示例,说明 Estimator 被保存、从磁盘加载并用于根据新输入进行预测。

TBH,我对这看起来有多复杂感到有些困惑。估计器被称为拟合标准模型的简单、相对高级的方法,但在生产中使用它们的过程似乎非常神秘。例如,当我通过tf.saved_model.load(export_path) 从磁盘加载模型时,我得到一个AutoTrackable 对象:

<tensorflow.python.training.tracking.tracking.AutoTrackable at 0x7fc42e779f60>

不清楚为什么我没有找回我的Estimator。看起来曾经有一个听起来很有用的函数 tf.contrib.predictor.from_saved_model,但由于 contrib 已经消失,它似乎不再起作用(除了它出现在 TFLite 中)。

任何指针都会非常有帮助。如你所见,我有点失落。

【问题讨论】:

  • 您检查过 2.0 中tf.saved_model.load 的文档吗?它与the 1.x version 不同。 “从 TensorFlow 1.x 导入 SavedModels”部分适用于估算器,并解释了如何获取一个可调用的函数以使用 prune 评估模型。
  • 好的,这可能是混淆的一部分,因为我没有使用 TensorFlow 1.x。在这些文档中,没有明确说明如何让我的Estimator(在我的情况下是DNNRegression)回来。
  • 这可能是我在尝试使用Estimators 时犯了一个错误。也许我应该专门使用 Keras 界面。我只是想生成几个模型,将它们序列化,然后根据需要加载它们以进行预测。
  • 啊,所以您想检索实际的估算器对象,而不仅仅是能够加载模型并运行它,对吗?是的,似乎没有一个 API,仅适用于一般的 running modelsKeras models... 使用 Keras 通常更容易,如果您需要估算器接口,您可以 make an estimator from a Keras model。跨度>
  • 如果您只是重新创建相同的 Estimator(相同的 model_fn,或具有相同参数的相同罐装 Estimator),并重用相同的输出目录,它将重新加载并准备好使用 .predict。如果您不想或没有源代码来重新创建相同的 Estimator,saved_model.load 将为您提供一个可以查询(用于预测)的对象,但该对象将没有 Estimator API。

标签: tensorflow


【解决方案1】:

也许作者不再需要答案,但我能够使用 TensorFlow 2.1 保存和加载 DNNClassifier

# training.py
from pathlib import Path
import tensorflow as tf

....
# Creating the estimator
estimator = tf.estimator.DNNClassifier(
    model_dir = <model_dir>,
    hidden_units = [1000, 500],
    feature_columns = feature_columns, # this is a list defined earlier
    n_classes = 2,
    optimizer = 'adam')

feature_spec = tf.feature_column.make_parse_example_spec(feature_columns)
export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)
servable_model_path = Path(estimator.export_saved_model(<model_dir>, export_input_fn).decode('utf8'))
print(f'Model saved at {servable_model_path}')

对于加载,你找到了正确的方法,你只需要检索 predict_fn

# testing.py
import tensorflow as tf
import pandas as pd

def predict_input_fn(test_df):
    '''Convert your dataframe using tf.train.Example() and tf.train.Features()'''
    examples = []
    ....
    return tf.constant(examples)

test_df = pd.read_csv('test.csv', ...)

# Loading the estimator
predict_fn = tf.saved_model.load(<model_dir>).signatures['predict']
# Predict
predictions = predict_fn(examples=predict_input_fn(test_df))

希望这也可以帮助其他人(:

【讨论】:

  • 我确实完全放弃了使用 Estimators,但这对其他人来说是一个有用的参考。我会接受答案。
  • 我无法相信用当前的 Estimator API 来做一些简单的事情是多么的麻烦,比如保存和加载模型。相比之下,Pytorch 非常简单直观。
  • 嘿@Omar Contugno,你能详细说明如何Convert your dataframe using tf.train.Example() and tf.train.Features()吗?我在您回答的这一步遇到问题。
  • 我使用这里提供的代码:shzhangji.com/blog/2018/05/14/…df--&gt;tf.constant(examples) 转换
猜你喜欢
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 2020-05-20
  • 2020-05-21
相关资源
最近更新 更多