Issue
I am new to python, and I was trying to run this code on loading the model for building extraction. But it throws the error that the name ‘model’ is not found. I am unable to resolve it. Can anyone please help.
This is the code:
from tensorflow.keras.models import load_model
from loss import bce_dice_loss, dice_coef
model = load_model('D:\RESEARCH\IITR\BUILDING_EXTRACTION_PhD_Final_WORK\DATASET\ISPRS_DATASET\Toronto\Toronto\ImagesDolon\output\weights\my_model.h5',custom_objects={ 'bce_dice_loss': bce_dice_loss}) # Load BCE Dice Loss from loss.py into model
The error:
`ValueError` `Traceback (most recent call last)`
`Input In [18], in <cell line: 4>()`
`1 from tensorflow.keras.models import load_model`
`2 from loss import bce_dice_loss, dice_coef`
`----> 4 model = load_model('D:\RESEARCH\IITR\BUILDING_EXTRACTION_PhD_Final_WORK\DATASET\ISPRS_DATASET\Toronto\Toronto\ImagesDolon\output\weights\my_model.h5',`
`5 custom_objects={ 'bce_dice_loss': bce_dice_loss} # Load BCE Dice Loss from loss.py into model`
`6 )
`
`File ~\anaconda3\envs\tensorflow\lib\site-packages\keras\utils\traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)`
`65 except Exception as e: # pylint: disable=broad-except`
`66 filtered_tb = _process_traceback_frames(e.__traceback__)`
`---> 67 raise e.with_traceback(filtered_tb) from None`
`68 finally:`
`69 del filtered_tb`
`File ~\anaconda3\envs\tensorflow\lib\site-packages\keras\utils\generic_utils.py:709, in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)`
`707 obj = module_objects.get(object_name)`
`708 if obj is None:`
`--> 709 raise ValueError(`
`710 f'Unknown {printable_module_name}: {object_name}. Please ensure '`
`711 'this object is passed to the `custom_objects` argument. See '`
`712 'https://www.tensorflow.org/guide/keras/save_and_serialize'`
`713 '#registering_the_custom_object for details.')`
`715 # Classes passed by name are instantiated with no args, functions are`
`716 # returned as-is.`
`717 if tf_inspect.isclass(obj):`
`ValueError: Unknown metric function: dice_coef. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.`
Solution
The error is saying that model has been created using a custom metric, called dice_coef
. When re-loading the model, you should add that metric too to your model creation, just as you have done for the custom loss:
from tensorflow.keras.models import load_model
from loss import bce_dice_loss, dice_coef
model = load_model(
'D:\RESEARCH\IITR\BUILDING_EXTRACTION_PhD_Final_WORK\DATASET\ISPRS_DATASET\Toronto\Toronto\ImagesDolon\output\weights\my_model.h5',
custom_objects={'bce_dice_loss': bce_dice_loss, 'dice_coef': dice_coef}
)
Answered By – ClaudiaR
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0