python - TensorFlow v2:替换 tf.contrib.predictor.from_saved_model
问题描述
到目前为止,我正在使用tf.contrib.predictor.from_saved_model
加载一个SavedModel
(tf.estimator
模型类)。但是,很遗憾,此功能已在 TensorFlow v2 中删除。到目前为止,在 TensorFlow v1 中,我的编码如下:
predict_fn = predictor.from_saved_model(model_dir + '/' + model, signature_def_key='predict')
prediction_feed_dict = dict()
for key in predict_fn._feed_tensors.keys():
#forec_data is a DataFrame holding the data to be fed in
for index in forec_data.index:
prediction_feed_dict[key] = [ [ forec_data.loc[index][key] ] ]
prediction_complete = predict_fn(prediction_feed_dict)
使用tf.saved_model.load
,我在 TensorFlow v2 中尝试以下操作失败:
model = tf.saved_model.load(model_dir + '/' + latest_model)
model_fn = model.signatures['predict']
prediction_feed_dict = dict()
for key in model_fn._feed_tensors.keys(): #<-- no replacement for _feed_tensors.keys() found
#forec_data is a DataFrame holding the data to be fed in
for index in forec_data.index:
prediction_feed_dict[key] = [ [ forec_data.loc[index][key] ] ]
prediction_complete = model_fn(prediction_feed_dict) #<-- no idea if this is anyhow close to correct
所以我的问题是(都在 TensorFlow v2 的背景下):
- 我该如何更换
_feed_tensors.keys()
? - 如何使用
tf.estimator
加载的模型以直接的方式进行推理tf.saved_model.load
非常感谢,任何帮助表示赞赏。
注意:此问题与此处发布的问题不重复,因为那里提供的答案都依赖于 TensorFlow v1 中已在 TensorFlow v2 中删除的功能。
编辑:这里的问题 postet似乎问的问题基本相同,但直到现在(2020-01-22)也没有答案。
解决方案
希望您已经使用类似于下面提到的代码保存了 Estimator 模型:
input_column = tf.feature_column.numeric_column("x")
estimator = tf.estimator.LinearClassifier(feature_columns=[input_column])
def input_fn():
return tf.data.Dataset.from_tensor_slices(
({"x": [1., 2., 3., 4.]}, [1, 1, 0, 0])).repeat(200).shuffle(64).batch(16)
estimator.train(input_fn)
serving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
tf.feature_column.make_parse_example_spec([input_column]))
export_path = estimator.export_saved_model(
"/tmp/from_estimator/", serving_input_fn)
您可以使用下面提到的代码加载模型:
imported = tf.saved_model.load(export_path)
要Predict
通过传递输入特征来使用您的模型,您可以使用以下代码:
def predict(x):
example = tf.train.Example()
example.features.feature["x"].float_list.value.extend([x])
return imported.signatures["predict"](examples=tf.constant([example.SerializeToString()]))
print(predict(1.5))
print(predict(3.5))
有关更多详细信息,请参阅此链接,其中解释了使用 TF Estimator 保存的模型。
推荐阅读
- c# - 根据列表中存在的键值过滤字典
- groovy - 如何通过 Groovy 将路由规则关联到 Nexus OSS 上的代理存储库?
- visual-studio - Visual Studio / msbuild CopyToOutputDirectory - 它是如何工作的?
- python - 未找到 SimpleHTTPServer python3
- audiocontext - 多个音频上下文,用例是什么?
- laravel - 在 herkou(混合内容)上部署我的 laravel 时遇到问题
- excel - 在 Excel 中分配具有下限和上限的数据
- orm - Doctrine ORM,多对多,延迟加载。检索实体并获取加入所有功能
- php - nginx 作为 PHP 服务入口点
- html - 我可以使用 CSS 为多级列表中的最后一级制作样式吗?