Loading custom model after saving

I have learned to train using custom layers and custom loss. But after saving the model to .keras format I am getting errors in loading the saved model. If there is some other way to load the custom model then please suggest me.
Refer code: GitHub - bhavaysavaliya/Custom-Object-Detection-Model-In-Tensorflow: Work In Progress

2 Likes

Have you tried googling “saving and loading TF models”? The top hit is this tutorial on the TF website with the title “Save and Load Models”. :nerd_face:

1 Like

Be also careful, the way you decide to save your model (see @paulinpaloalto link), since depending on the way you save it, you would also need to redo or refactor the class that you used to train the model in order to load the model successfully. Otherwise, it will be useless the loaded module to use model.fit() on new data.

1 Like

The reason for error in your notebook is that the custom layers aren’t registered with keras at load time. Here’s one way to specify custom objects for reconstruction.


# model.save('mine.keras')

import keras
from Object_Detection import YoloConvLayer, YoloSPPFLayer, YoloC2FLayer

model2 = keras.models.load_model('mine.keras',
                                 custom_objects={'YoloSPPFLayer': YoloSPPFLayer,
                                                 'YoloConvLayer': YoloConvLayer,
                                                 'YoloC2FLayer': YoloC2FLayer
                                                 })

You can read about it here

Thank you all for your help. Sorry for the late response due to some personal issues. I tried saving weights and then loading weights. It worked. But when I tried saving the model it threw some errors.


I got this error related to some parameter named ‘reduction’. I have not used this parameter anywhere.

1 Like

Also when I loaded saved_weights and then trained again, the validation loss showed infinite at every epochs.

1 Like

Based on this line of code, YoloLoss accepts only anchors as constructor argument.

Yes, @balaji.ambresh YoloLoss accepts only anchors as constructors but I don’t understand why it is throwing an error that the unexpected argument ‘reduction’ passed.
@paulinpaloalto @Nydia please look into this matter.

1 Like

Did you load the model to continue the training or just to re-use it?

I just loaded the model again to check whether the model is generating predictions or not. But the model wasn’t able to load.

I was trying to save the model and later use that model to integrate with flask or other technologies.

@Nydia Please consider this link to view YoloLoss class.
Link: Custom-Object-Detection-Model-In-Tensorflow/Object_Detection/loss.py at main · bhavaysavaliya/Custom-Object-Detection-Model-In-Tensorflow (github.com)

Hi @Bhavay_Savaliya I was on holidays, I am sorry for the late answer, can you please also tell me where is the file where you are loading the model?