pythonkerasgoogle-colaboratorymetricscustom-object

Unable to load model with custom_object (in a different file) in Google Colab


I trained a CNN and saved it in my Google Drive, now I am trying to load it and test it with a different dataset, however I'm having problems to load it using custom_objects.

My code:

from google.colab import drive
drive.mount('/content/drive')

import tensorflow as tf
import keras
newmodel =  tf.keras.models.load_model('/content/drive/My Drive/Programa2/New_UNet.h5', custom_objects={'Metrics.dice_coef':Metrics.dice_coef,'Metrics.precision':Metrics.precision, 'Metrics.sensitivity':Metrics.sensitivity,'Metrics.specificity':Metrics.specificity})


# compile the model
newmodel.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy',Metrics.dice_coef,Metrics.precision,Metrics.sensitivity,Metrics.specificity])

newmodel.summary()

Error message:

NameError                                 Traceback (most recent call last)
<ipython-input-13-d14ae084fec6> in <module>()
      4 import tensorflow as tf
      5 import keras
----> 6 newmodel =  tf.keras.models.load_model('/content/drive/My Drive/Programa2/New_UNet.h5', custom_objects={'Metrics.dice_coef':Metrics.dice_coef,'Metrics.precision':Metrics.precision, 'Metrics.sensitivity':Metrics.sensitivity,'Metrics.specificity':Metrics.specificity})
      7 
      8 

NameError: name 'Metrics' is not defined

Metrics is another code file with the metrics functions created to evaluate the segmentation, it is in the same drive folder as the others files I'm using.

Thanks in advance!


Solution

  • It's solved, since the metrics aren't needed for prediction, it was possible to be loaded using:

    newmodel =  tf.keras.models.load_model('/content/drive/My Drive/Programa2/newmodel.h5',compile=False)