我正在尝试为模型建立骰子损失(需要使用蒙版进行分割,因此我使用的是IoU指标)。
至于最后一部分,即相交和并集之间的除法,我无法克服“零除以浮点数除法”这一部分。我试过对if else
使用平滑常数(1e-6),try except
和ZeroDivisionError
子句。
这是代码:
import numpy as np
def arith_or(array1, array2):
res = []
for a, b in zip(array1, array2):
if a == 1.0 or b == 1.0:
res.append(1.0)
else:
res.append(0.0)
return res
def arith_and(array1, array2):
res = []
for a, b in zip(array1, array2):
if a == 1.0 and b == 1.0:
res.append(1.0)
else:
res.append(0.0)
return res
def dice_loss(y_true, y_pred):
y_true_f = np.ravel(y_true)
y_pred_f = np.ravel(y_pred)
intersection = arith_and(y_true_f, y_pred_f).sum((1, 2))
union = arith_or(y_true_f, y_pred_f).sum((1, 2))
score = ((2.0 * intersection + 1e-6) / (union + 1e-6))
return 1 - score
错误:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-40-886068d106e5> in <module>()
65 output_layer = build_model(input_layer, 16)
66 model = Model(input_layer, output_layer)
---> 67 model.compile(loss=dice_loss, optimizer="adam", metrics=["accuracy"])
2 frames
/content/losers.py in dice_loss(y_true, y_pred)
30 intersection = arith_and(y_true_f, y_pred_f).sum((1, 2))
31 union = arith_or(y_true_f, y_pred_f).sum((1, 2))
---> 32 score = ((2.0 * intersection + 1e-6) / (union + 1e-6))
33
34 return 1 - score
ZeroDivisionError: float division by zero
最佳答案
我不是专家,但是我使用的骰子损失功能来自Raymond Yuan(https://ej.uz/hk9s)的“使用tf.keras进行图像分割”,它一次也没让我失败。
功能:
def dice_coeff(y_true, y_pred):
smooth = 1.
y_true_f = tf.reshape(y_true, [-1])
y_pred_f = tf.reshape(y_pred, [-1])
intersection = tf.reduce_sum(y_true_f * y_pred_f)
score = (2. * intersection + smooth) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth)
return score
def dice_loss(y_true, y_pred):
loss = 1 - dice_coeff(y_true, y_pred)
return loss
似乎分子和分母都被加上了浮点数1。
使用numpy,它将是:
def dice_loss(y_true, y_pred):
smooth = 1.
y_true_f = np.ravel(y_true)
y_pred_f = np.ravel(y_pred)
intersection = np.sum(y_true_f * y_pred_f)
score = (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)
return 1 - score