save and load model in tensorflow 2.0

Viewed 694

I saved a model from premade estimator in tensorflow 2.x with this code

import os
serving_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
tf.feature_column.make_parse_example_spec(my_feature_columns))
estimator_base_path = os.path.join( 'from_estimator')
estimator_path = classifier.export_saved_model(estimator_base_path, serving_input_fn)

this code create a folder which contains a .pb file i need to reuse this model in the future, i try to load woth this function

saved_model_obj = tf.compat.v2.saved_model.load(export_dir="/model_dir/")

but when i try to make a prediction on using the loaded model it raises this error

predictions = saved_model_obj.predict(
input_fn=lambda: input_fn(predict_x))


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-a9902ff8210c> in <module>
----> 1 predictions = saved_model_obj.predict(
      2     input_fn=lambda: input_fn(predict_x))

AttributeError: 'AutoTrackable' object has no attribute 'predict'

how can i load a .pb file and make prediction, like if i've never saved and loaded it?

1 Answers

When I save models for later use I usually do this:

Assuming that your model is model:

model.save('my_model.h5') 

This will save the modoel in a hdf5 format.

Then when I have to use it to predict again I can just:

new_model = tf.keras.models.load_model('my_model.h5')

and than you can new_model.predict()

Related