使用深度学习做医学图像分割时,经常会用dice系数作为损失函数。定义的方式网上有很多就不讲了,但在加载时经常遇到麻烦。
使用keras时,一般用load_model()函数加载模型,但无法直接加载dice系数作为损失函数的模型,如果强行加载会报以下的错误:
ValueError: Unknown loss function:dice_coef_loss
怎么解决这个问题呢,其实很简单。
首先可以看一下函数 load_model
的源码,在这里只给出说明部分如下
def load_model(filepath, custom_objects=None, compile=True):
"""Loads a model saved via `save_model`.
# Arguments
filepath: String, path to the saved model.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.
compile: Boolean, whether to compile the model
after loading.
# Returns
A Keras model instance. If an optimizer was found
as part of the saved model, the model is already
compiled. Otherwise, the model is uncompiled and
a warning will be displayed. When `compile` is set
to False, the compilation is omitted without any
warning.
# Raises
ImportError: if h5py is not available.
ValueError: In case of an invalid savefile.
"""
其中的 custom_objects
是可选的字典,在反序列化过程中映射名称(字符串)到要考虑的自定义类或函数,所以可以直接通过字典来制定缺失的指标或者损失函数,如下
# parameter for loss function
smooth = 1.
# metric function and loss function
def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_loss(y_true, y_pred):
return -dice_coef(y_true, y_pred)
# load model
weight_path = './weights.h5'
model = load_model(weight_path,custom_objects={'dice_coef_loss': dice_coef_loss,'dice_coef':dice_coef})
重点看上面代码的最后一行,通过字典指定我们自定义的函数(或许是一个指标,或许是一个损失函数)就可以解决上面的问题。