dice系数作为损失函数的网络模型如何加载(ValueError: Unknown loss function:dice_coef_loss)

使用深度学习做医学图像分割时,经常会用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})

重点看上面代码的最后一行,通过字典指定我们自定义的函数(或许是一个指标,或许是一个损失函数)就可以解决上面的问题。

  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值