tensorflow - 用于 keras/tensorflow 中语义图像分割的多类加权损失

标签 tensorflow keras deep-learning semantic-segmentation

给定批量 RGB 图像作为输入,shape=(batch_size, width, height, 3)

多类目标表示为one-hot,shape=(batch_size, width, height, n_classes)

以及在最后一层具有 softmax 激活的模型(Unet、DeepLab)。

我正在寻找 kera/tensorflow 中的加权分类交叉熵损失函数。
class_weight参数在 fit_generator似乎不起作用,我没有在这里或在 https://github.com/keras-team/keras/issues/2115 中找到答案.

def weighted_categorical_crossentropy(weights):
    # weights = [0.9,0.05,0.04,0.01]
    def wcce(y_true, y_pred):
        # y_true, y_pred shape is (batch_size, width, height, n_classes)
        loos = ?...
        return loss

    return wcce

最佳答案

我来回答我的问题:

def weighted_categorical_crossentropy(weights):
    # weights = [0.9,0.05,0.04,0.01]
    def wcce(y_true, y_pred):
        Kweights = K.constant(weights)
        if not K.is_tensor(y_pred): y_pred = K.constant(y_pred)
        y_true = K.cast(y_true, y_pred.dtype)
        return K.categorical_crossentropy(y_true, y_pred) * K.sum(y_true * Kweights, axis=-1)
    return wcce

用法:
loss = weighted_categorical_crossentropy(weights)
optimizer = keras.optimizers.Adam(lr=0.01)
model.compile(optimizer=optimizer, loss=loss)

关于tensorflow - 用于 keras/tensorflow 中语义图像分割的多类加权损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59520807/

相关文章:

python - 在 TensorFlow 中使用实验的优势

python-3.x - Wasserstein GAN 批评者训练歧义

python - 如果我的任何模型变量为 NaN,如何在 TensorFlow 中检查?

python - 在 Tensorflow 中等同 Subtensor 时出错

python - 如何插入tensorflow中使用的cuda runtime API?

tensorflow - Keras 中具有多个输入/输出的 tf.data

python - 带有 caffe 的 python 中的 VGG 人脸描述符

python - 有没有为 AVX 指令编译的 TensorFlow 版本?

python - 两种不同输入样本大小的 Keras 多任务学习

python - 连接时间序列神经网络和前馈神经网络