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

到目前为止,我正在使用tf.contrib.predictor.from_saved_model来加载Savedmodeltf.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中):

  1. 如何替换_feed_tensors.keys()
  2. 如何使用加载了tf.estimator的{​​{1}}模型以直接的方式进行推断

非常感谢,感谢您的帮助。

注意:该问题与先前发布的here并不相同,因为那里提供的答案都取决于TensorFlow v2中已删除的TensorFlow v1功能。

sx8382 回答:TensorFlow v2:替换tf.contrib.predictor.from_saved_model

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

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])).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))

有关更多详细信息,请参阅this link,其中解释了使用TF Estimator保存的模型。

本文链接:https://www.f2er.com/2959563.html

大家都在问