TensorFlow v2:替换 tf.contrib.predictor.from_saved_model

2024-01-12

到目前为止,我正在使用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)

Using 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 的背景下):

  1. 我该如何更换_feed_tensors.keys()?
  2. 如何使用简单的方式进行推理tf.estimator模型加载了tf.saved_model.load

非常感谢,非常感谢任何帮助。

注意:此问题与发布的问题不重复here http://This%20question%20is%20not%20a%20duplicate%20of%20the%20question%20posted因为那里提供的答案全部依赖于 TensorFlow v1 的功能,而这些功能已在 TensorFlow v2 中删除。

EDIT:问题海报here https://stackoverflow.com/questions/58308258/run-prediction-from-saved-model-in-tensorflow-2-0似乎问了基本相同的事情,但直到现在(2020-01-22)也没有得到答复。


希望您已使用类似于下面提到的代码保存了估计器模型:

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)

To 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))

欲了解更多详情,请参阅这个链接 https://www.tensorflow.org/guide/saved_model#savedmodels_from_estimators其中解释了使用 TF Estimator 保存的模型。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TensorFlow v2:替换 tf.contrib.predictor.from_saved_model 的相关文章

随机推荐