Prediction from model saved with `tf.estimator.Estimator` in Tensorflow

本小妞迷上赌 提交于 2019-12-02 22:26:43

As for the TypeError, I solve it in this way.

First, name the placeholder:

feature_spec = {"input_image": tf.placeholder(dtype=tf.float32, shape=[None, 784], name='input_image')}

Then you can use it like this:

feed_dict={"input_image:0": input_data}

Hope it can help someone.


EDIT

In this question, afterestimator.export_savedmodel(...) you can do prediction like this:

with tf.Session(graph=tf.Graph()) as sess:
    meta_graph_def = tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_path)
    signature = meta_graph_def.signature_def
    x_tensor_name = signature['classes'].inputs['input_image'].name
    y_tensor_name = signature['classes'].outputs['labels'].name
    x = sess.graph.get_tensor_by_name(x_tensor_name)
    y = sess.graph.get_tensor_by_name(y_tensor_name)
    predictions = sess.run(y, {x: mnist.test.images[:5]})

The name of your input Tensor probably is input_image:0.

You can list the signature of your saved model by calling:

print(estimator.signature_def[tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY])

That should list the expected input/output Tensors.

I predict successfully by using tensorflow.contrib.predictor:

from tensorflow.contrib import predictor

predict_fn = predictor.from_saved_model(
    export_dir='model/1535012949',  # your model path
    signature_def_key='predict', 
)

predictions = predict_fn({'examples': examples})  # FYI, rename to `input_image`

But I want to predict by session and tensors also, so that I can use the traning model with other languages. Expect some perfect answer!

I am working with tf.contrib.learn.Estimator. As I see, the syntax and method signatures are almost the same so I believe the differences are related to the several Tensorflow versions. So you can create Estimator as usual with something like

estimator = learn.Estimator(
         model_fn=your_model,
         model_dir="tmp",
         config=tf.contrib.learn.RunConfig(
             save_checkpoints_steps=10,
             save_summary_steps=10,
             save_checkpoints_secs=None
         )
     )

Then you do the train asestimator.fit(input_fn=input_function, steps=100)

And then you can do the prediction calling

estimator .predict(prediction)

Mote, there is a trick, related with the Tensorflow's known issue. Calling predict does not properly initialize the Estimator, so you need to call

estimator.evaluate(x=prediction, y=label_array, steps=1)

before calling predict.

Hope, this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!