【问题标题】:Image segmentation - custom loss function in Keras图像分割 - Keras 中的自定义损失函数
【发布时间】:2018-10-22 00:04:54
【问题描述】:

我正在使用 Keras 中实现的 U-Net (https://arxiv.org/pdf/1505.04597.pdf) 来分割显微镜图像中的细胞器。为了让我的网络识别仅相隔 1 个像素的多个单个对象,我想为每个标签图像使用权重图(公式在出版物中给出)。

据我所知,我必须创建自己的自定义损失函数(在我的情况下为交叉熵)才能使用这些权重图。但是,自定义损失函数只接受两个参数。如何在这样的函数中添加权重图值?

下面是我的自定义损失函数的代码:

def pixelwise_crossentropy(self, ytrue, ypred):

    ypred /= tf.reduce_sum(ypred, axis=len(ypred.get_shape()) - 1, keep_dims=True)

    # manual computation of crossentropy
    _epsilon = tf.convert_to_tensor(epsilon, ypred.dtype.base_dtype)
    output = tf.clip_by_value(ypred, _epsilon, 1. - _epsilon)

    return - tf.reduce_sum(ytrue * tf.log(output))

有没有办法将权重映射值与 ytrue 张量中的标签值组合在一起?

如果这个问题看起来很愚蠢,我深表歉意,正如我所说,我对这个游戏还比较陌生。任何帮助或建议将不胜感激!

【问题讨论】:

    标签: keras image-segmentation loss-function unet


    【解决方案1】:

    如果您尝试实现二元交叉熵加权损失,您可以使用张量流内置损失函数

    pos_weight = tf.constant([[1.0, 2.0]])
    tensorflow.nn.weighted_cross_entropy_with_logits(y_true,
        y_pred,
        pos_weight,
        name=None) 
    

    查看文档 https://www.tensorflow.org/api_docs/python/tf/nn/weighted_cross_entropy_with_logits

    keras 的实现

    def pixel_wise_loss(y_true, y_pred):
        pos_weight = tf.constant([[1.0, 2.0]])
        loss = tf.nn.weighted_cross_entropy_with_logits(
            y_true,
            y_pred,
            pos_weight,
            name=None
        )
    
        return K.mean(loss,axis=-1)
    

    如果您尝试实现 softmax_cross_entropy_with_logits,请点击前面的链接进行解释 softmax_cross_entropy_with_logits

    【讨论】:

    • 感谢您的回答。我试图实现该功能,但我得到一个 ValueError: Cannot create a tensor proto which content is大于 2GB。我的权重图是一个大数组,其形状为 [Nr of image, x, y, channels]。
    猜你喜欢
    • 2020-02-17
    • 2018-09-23
    • 2017-07-24
    • 2018-10-19
    • 1970-01-01
    • 2020-12-19
    • 2017-12-18
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多