gpt4 book ai didi

python - 如何避免Python中除零错误

转载 作者:行者123 更新时间:2023-11-30 09:41:56 25 4
gpt4 key购买 nike

我正在尝试为我的模型构建骰子损失(需要使用掩码进行分割,因此我使用 IoU 指标)。

当谈到最后一部分,即交集和并集之间的除法时,我无法克服“ float 除以零”部分。我尝试过使用平滑常量 (1e-6)、if elsetry 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 ) 的“Image Segmentation with 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

看起来,分子和分母都添加了 float 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

关于python - 如何避免Python中除零错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com