keras-team / keras

Deep Learning for humans
http://keras.io/
Apache License 2.0
61.27k stars 19.38k forks source link

Unable to load finetuned keras model. #19808

Open ragesh2000 opened 1 month ago

ragesh2000 commented 1 month ago

I have a keras model fine tuned from resnet101 (.h5). But iit is unable to load using latest keras libraries. The following is my code

from keras_retinanet import models
model = models.load_model('finetuned_model.h5')

The model was trained on older version of keras. I think that why iam getting the following error TypeError: Error when deserializing class 'BatchNormalization' using config={'dtype': 'float32', 'center': True, 'freeze': True, 'gamma_regularizer': None, 'beta_constraint': None, 'beta_regularizer': None, 'gamma_initializer': {'config': {}, 'class_name': 'Ones'}, 'name': 'bn_conv1', 'momentum': 0.99, 'trainable': False, 'moving_variance_initializer': {'config': {}, 'class_name': 'Ones'}, 'moving_mean_initializer': {'config': {}, 'class_name': 'Zeros'}, 'scale': True, 'epsilon': 1e-05, 'beta_initializer': {'config': {}, 'class_name': 'Zeros'}, 'gamma_constraint': None}. Is there any method that i can change the model configurations so that iam able to load it using latest keras libraries.

fchollet commented 1 month ago

It looks like a config deserialization issue. If you have the model's code, you can:

  1. Load the old model with the old Keras version
  2. Save its weights via save_weights() to h5 format
  3. Update to the latest Keras version
  4. Use the code to create an instance of the model
  5. Load the weights file
ragesh2000 commented 1 month ago

But the problem is I am not able to load the model in any version. It was used keras-resnet==0.1.0 at the time of training and saving the model. But this version is not even available now. The oldest version currently available is keras-resnet==0.3.1. I am getting the same error in this version also. @fchollet

fchollet commented 1 month ago

Looking at the config in the error message, I have a vague idea what might be going on. This is not the config of a Keras BatchNormalization layer. For instance, the freeze argument is not a Keras argument.

So I think the model was built using custom layer from some package. But the name of these layers collides with built-in Keras layers. Hence the error.

You need to provide custom_objects=... when loading the model. Specify the custom classes by hand.