Skip to main content
 首页 » 编程设计

python之Keras:骰子系数损失函数为负且随epochs增加

2025年05月04日14sharpest

根据 Dice Co-eff 损失函数的这个 Keras 实现,损失是 dice 系数计算值的负值。损失应该随着时间的推移而减少,但通过这种实现,我自然会得到负损失,并且损失会随着时间的推移而减少,即从 0 向负无穷大方向移动,而不是接近 0。如果我使用(1- dice co-eff) 而不是 (-dice co-eff) 作为损失,会错吗? 这是完整的 Keras 实现(我正在谈论):https://github.com/jocicmarko/ultrasound-nerve-segmentation/blob/master/train.py

smooth = 1. 
 
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) 

我已经与您分享了我的实验日志,尽管只有 2 个时期:

Train on 2001 samples, validate on 501 samples 
Epoch 1/2 
Epoch 00001: loss improved from inf to -0.73789, saving model to unet.hdf5 
 - 3229s - loss: -7.3789e-01 - dice_coef: 0.7379 - val_loss: -7.9304e-01 - val_dice_coef: 0.7930 
Epoch 2/2 
Epoch 00002: loss improved from -0.73789 to -0.81037, saving model to unet.hdf5 
 - 3077s - loss: -8.1037e-01 - dice_coef: 0.8104 - val_loss: -8.2842e-01 - val_dice_coef: 0.8284 
predict test data 
9/9 [==============================] - 4s 429ms/step 
dict_keys(['val_dice_coef', 'loss', 'val_loss', 'dice_coef']) 

请您参考如下方法:

1-dice_coef 或 -dice_coef 对收敛没有影响,但 1-dice_coef 提供了一种更熟悉的监控方式,因为值在 [0, 1] 范围内,而不是 [-1, 0]。