Python 如何将softmax输出转换为自定义Keras损耗中的一种热格式

Python 如何将softmax输出转换为自定义Keras损耗中的一种热格式,python,tensorflow,keras,loss-function,Python,Tensorflow,Keras,Loss Function,在2D语义分割任务中。我想计算自定义Keras损失函数中每个类别的平均骰子系数 因此我认为第一步是计算每个类别的骰子系数,然后平均系数以获得平均骰子 现在我的损失函数看起来像 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)

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

因此我认为第一步是计算每个类别的骰子系数,然后平均系数以获得平均骰子

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

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之后的网络输出,标签_形状=(批大小,1024,512,n类),预测_形状=(批大小,1024,512,n类)

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

我想我应该使用整数0或1 y_pred值而不是float。因此,我需要1)使用K.argmax()获取每个像素的最大值索引,2)将K.argmax()的结果转换为一种热格式(一个简单的示例:将[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\u utils.to\u category()
需要
array
但是它得到了一个
序列,就像一个
张量

我也遇到了这个问题,然后我将
np\u utils.to\u category()
更改为
tf.one\u hot
,它可以工作

希望这有帮助:D