0

I'm training a model using TensorFlow and Keras. I would like to save the model and then load it. but I'm getting some errors.

I compile the model this way:

from tensorflow.keras.models import Model
import tensorflow as tf

model.compile(loss='categorical_crossentropy',
              optimizer=adam,
              metrics=['accuracy', top3, top5])

and after training I'm loading the model this way:

model.save('model')

So I get a folder "model" containing:

---model 
     ---assets
     ---variables
     ---keras_metadata.pb
     ---saved_model.pb

Finally, I try to load the model using:

import tensorflow as tf

new_model = tf.keras.models.load_model('model')
new_model.summary()

But I'm getting this error:

ValueError: Unable to restore custom object of type _tf_keras_metric 
currently. Please make sure that the layer implements `get_config`and 
`from_config` when saving. In addition, please use the `custom_objects` 
arg when calling `load_model()`.
3
  • Try to save like this: model.save('model.h5') Commented Jun 9, 2021 at 21:19
  • I tried that too. I got: OSError: Unable to open file (bad object header version number) when doing: new_model = tf.keras.models.load_model('model.h5') Commented Jun 9, 2021 at 21:24
  • I think this error is due to your custom metrics. Commented Jun 9, 2021 at 21:39

1 Answer 1

1

When your model utilizes custom objects, such as your custom metrics, you have to specify them with the custom_objects argument of load_model:

new_model = tf.keras.models.load_model('model', custom_objects={'top3': top3, 'top5': top5})

Note that the definitions of your custom metrics must be available in the same module/environment you are loading the model.

Sign up to request clarification or add additional context in comments.

1 Comment

@Laura did the answer resolve your problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.