如何解决Keras 语义分割的自定义骰子损失
我有以下自定义骰子损失代码,用于 keras tensorflow 中的语义分割。该函数应该能够预测多个类别,但对于这种情况,我将 num_classes
设置为 2,因为我只需要背景和蒙版。
def dice(y_true,y_pred,num_classes=2,smooth=1e-7,ignore_background=False):
y_true = K.one_hot(K.cast(y_true,'int32'),num_classes=num_classes)[...,1:] if ignore_background else K.one_hot(
K.cast(y_true,num_classes=num_classes)
y_true_f = K.flatten(y_true)
y_pred = y_pred[...,1:] if ignore_background else y_pred
y_pred_f = K.flatten(y_pred)
intersect = reduce_sum(y_true_f,axis=-1) * reduce_sum(y_pred_f,axis=-1)
denom = reduce_sum(y_true_f,axis=-1) + reduce_sum(y_pred_f,axis=-1)
dice = K.mean((2. * intersect / (denom + smooth)))
return dice
def dice_loss(y_true,y_pred):
print('y_true.shape: ',y_true.shape,'y_pred.shape: ',y_pred.shape)
return 1 - dice(y_true,y_pred)
我正在训练的模型预测两个掩码和两个背景连接在两个数组中,因此输出的形状为 (256,256,2),(256,2)。
该模型没有训练,损失曲线很快就达到了 E-6,此后不再改变。我不知道我在这里做错了什么。我打印了 y_true 和 y_pred 的形状,结果如下:y_true.shape: (None,None,None) y_pred.shape: (None,2)
.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。