如何通过向交叉熵添加负熵来创建自定义损失函数?

2024-10-03 13:18:39 发布

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

我最近读了一篇题为“通过惩罚自信输出分布来正则化神经网络”的论文。作者讨论了通过惩罚低熵来正则化神经网络 通过向负对数似然中添加负熵项并创建用于模型训练的自定义损失函数,输出分布

enter image description here

β值控制置信度惩罚的强度。我为分类交叉熵编写了一个自定义函数,如下所示,但需要将负熵项添加到损失函数中

import tensorflow as tf
def custom_loss(y_true, y_pred):
    cce = tf.keras.losses.CategoricalCrossentropy()
    cce_loss = cce(y_true, y_pred)    
    return cce_loss

Tags: 函数模型truetf对数神经网络作者损失
2条回答

y_pred的熵本质上是y_pred与自身之间的分类交叉熵:

enter image description here

def custom_loss(y_true, y_pred, beta):
    cce = tf.keras.losses.CategoricalCrossentropy()
    return cce(y_true, y_pred) - beta*cce(y_pred, y_pred)

您不需要自定义丢失,因为它可以实现为活动正则化器(应用于层输出的正则化器):

def regularizer(beta):
    def entropy_reg(inp):
        return -beta * K.mean(inp * K.log(inp))

然后可以将其应用于输出层:

model = Sequential()
#Add layers here
model.add(Dense(num_classes, activation="softmax",
          activity_regularizer=regularizer(0.01)))

相关问题 更多 >