关于带有自定义损失的3输出ANN的权重

2024-06-10 02:54:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图定义一个自定义损失函数,它在回归模型中接受3个输出变量

def custom_loss(y_true, y_pred):
    y_true_c = K.cast(y_true, 'float32')  # Shape=(batch_size, 3)
    y_pred_c = K.cast(y_pred, 'float32')  # Shape=(batch_size, 3)

    # Compute error
    num = K.abs(y_true_c - y_pred_c)  # Shape=(batch_size, 3)
    den = K.maximum(y_true_c, y_pred_c)   # Shape=(batch_size, 3)
    err = K.sum(num / den, axis=-1)  # Shape=(batch_size,)

    # Output loss
    return K.mean(err)

在将3个输出的3个损耗相加为单个损耗值之前,我如何对其进行称重

My model.compile()语句当前为:

model.compile(loss=custom_loss, metrics=['mse'],optimizer=optimizer, loss_weights=[0.25,0.5,0.25])

其中,我试图分别对3个输出中的每一个分别进行0.25、0.5、0.25(总和为1)的加权。但是,我认为这个工具可能无法与自定义丢失功能一起工作

我怎样才能做到呢


Tags: truesizemodelcustombatchnum损耗err
1条回答
网友
1楼 · 发布于 2024-06-10 02:54:04

您可以将额外的参数weights传递给自定义丢失,如下所示:

def custom_loss(weights):
    def loss(y_true, y_pred):
        y_true_c = K.cast(y_true, 'float32')  # Shape=(batch_size, 3)
        y_pred_c = K.cast(y_pred, 'float32')  # Shape=(batch_size, 3)

        # Compute error
        num = K.abs(y_true_c - y_pred_c)  # Shape=(batch_size, 3)
        den = K.maximum(y_true_c, y_pred_c)  # Shape=(batch_size, 3)
        aux = weights * (num / den)  # Shape=(batch_size, 3)
        err = K.sum(aux, axis=-1)  # Shape=(batch_size,)

        # Output loss
        return K.mean(err)

    return loss

然后编译模型,如下所示:

# weights shape is (3,)
weights = np.array([0.25, 0.5, 0.25])
model.compile(loss=custom_loss(weights), metrics=['mse'], optimizer=optimizer)

注意:未测试

相关问题 更多 >