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

标签 python machine-learning

我正在尝试为我的模型构建骰子损失(需要使用掩码进行分割,因此我使用 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/

相关文章:

machine-learning - 使用 sklearn 并行训练多个模型?

python - 曲线拟合为指数

python - 生成一串数字python

python - 避免在 iPython Notebook 中对 R 图进行抗锯齿处理

python - 在 Python 中使用正则表达式获得和平的数字

machine-learning - 如何理解多类神经网络的输出

machine-learning - 我可以使用 Kinect 的深度图像重新训练 Inception 的最终层吗?

machine-learning - keras自动编码器 "Error when checking target"

machine-learning - Erlang 中的感知器在训练后不学习

python - 值错误 : y contains new labels: ['#' ]