python - 如何在自定义 Keras 损失中将 softmax 输出转换为 one-hot 格式

标签 python tensorflow keras loss-function

二维语义分割任务中。我想计算自定义 Keras 损失函数中每个类别的平均骰子系数。

所以我认为第一步是计算每个类别的dice系数,然后平均系数以获得avg_dice。

现在我的损失函数看起来像

def avg_dice_coef(y_true, y_pred, n_classes, smooth=1e-5):
    # y_pred_new = K.variable(np_utils.to_categorical(K.argmax(y_pred), num_classes=OPTIONS.nb_classes))

    avg_dice = 0.  # 用于求和每个类别的骰子系数,之后求平均
    for class_index in range(n_classes):  # 对每个类别进行循环
        intersection = K.sum(y_true[:, :, :, class_index] * y_pred_new[:, :, :, class_index], axis=[1, 2])
        union = K.sum(y_true[:, :, :, class_index], axis=[1, 2]) + K.sum(y_pred_new[:, :, :, class_index], axis=[1, 2])
        dice_one_class = K.mean((2. * intersection + smooth) / (union + smooth), axis=0)
        avg_dice += dice_one_class
    return avg_dice / n_classes  # 之后求平均

在此函数中,y_pred是经过softmax后网络的输出,labels_shape=(batch_size, 1024, 512, n_classes),predicts_shape=(batch_size, 1024, 512, n_classes)

我认为我的损失是错误的,因为我使用了 float y_pred。根据方程

enter image description here

我认为我应该使用整数 0 或 1 y_pred 值而不是 float 。所以我需要1)使用K.argmax()来获取每个像素的最大值的索引,2)将K.argmax()的结果转换为one-hot格式。(一个简单的例子:convert [0.1, 0.1 , 0.8] 到 [0, 0, 1])

但是当我添加

y_pred_new = K.variable(np_utils.to_categorical(K.argmax(y_pred), num_classes=OPTIONS.nb_classes))

为了实现这个目标,我遇到了一个错误:

ValueError:使用序列设置数组元素。

我如何弥补我的损失以及我的平均想法是否正确?

最佳答案

在我看来,函数np_utils.to_categorical()需求array但它得到了 sequence喜欢 tensor

我也遇到了这个问题,然后我改了np_utils.to_categorical()进入tf.one_hot , 有用。

希望这有帮助:D

关于python - 如何在自定义 Keras 损失中将 softmax 输出转换为 one-hot 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257509/

相关文章:

python - 在目标检测中使用步长为 1 的最大池化层的目的是什么

Keras-CNTK 保存模型-v2 格式

python - 为复杂的 View 生成器函数定义 API(具有许多可配置项)

Python:同时调用多个递归

python - 在 google colab notebook 中看不到 Tensorflow 日志

python - TensorFlow 模型不执行任何训练

machine-learning - keras 卷积神经网络 - 输出形状

python - 使用 dtype 读取二进制文件会导致 ValueError

python - Pandas 在多列上搜索子字符串

python - deeplab在自己的数据集上训练时从检查点恢复失败