【问题标题】:Keras custom loss function (elastic net)Keras 自定义损失函数(弹性网)
【发布时间】:2019-12-09 18:22:31
【问题描述】:

我正在尝试编写 Elastic-Net 代码。它看起来像:

我想在 Keras 中使用这个损失函数:

def nn_weather_model():
    ip_weather = Input(shape = (30, 38, 5))
    x_weather = BatchNormalization(name='weather1')(ip_weather)
    x_weather = Flatten()(x_weather)
    Dense100_1 = Dense(100, activation='relu', name='weather2')(x_weather)
    Dense100_2 = Dense(100, activation='relu', name='weather3')(Dense100_1)
    Dense18 = Dense(18, activation='linear', name='weather5')(Dense100_2)
    model_weather = Model(inputs=[ip_weather], outputs=[Dense18])
    model = model_weather
    ip = ip_weather
    op = Dense18
    return model, ip, op

我的损失函数是:

def cost_function(y_true, y_pred):
        return ((K.mean(K.square(y_pred - y_true)))+L1+L2)
   return cost_function

是mse+L1+L2

而L1和L2是

weight1=model.layers[3].get_weights()[0]
weight2=model.layers[4].get_weights()[0]
weight3=model.layers[5].get_weights()[0]
L1 = Calculate_L1(weight1,weight2,weight3)
L2 = Calculate_L2(weight1,weight2,weight3)

我使用Calculate_L1 函数来计算dense1 &dense2 和dense3 的权重之和 然后Calculate_L2 再做一次。

当我训练RB_model.compile(loss = cost_function(),optimizer= 'RMSprop') 时,L1 和 L2 变量并没有更新每批。所以我尝试在使用批处理开始时使用回调:

class update_L1L2weight(Callback):
    def __init__(self):
        super(update_L1L2weight, self).__init__()
    def on_batch_begin(self,batch,logs=None):
        weight1=model.layers[3].get_weights()[0]
        weight2=model.layers[4].get_weights()[0]
        weight3=model.layers[5].get_weights()[0]
        L1 = Calculate_L1(weight1,weight2,weight3)
        L2 = Calculate_L2(weight1,weight2,weight3)

如何在 batch_begin 中使用回调计算 L1 和 L2 完成, 并将 L1,L2 变量传递给损失函数?

【问题讨论】:

  • 为什么不直接在层上使用权重正则化器?
  • 嗨,我发现 keras 有层的 L1 和 L2,但我认为它与公式不一样。给出成本函数的公式是 MSE+L1+L2 ,但是 keras 层的 L1 和 L2 仅适用于 layer ,并且每一层都有单个 L1,L2 ,我不确定这种方式是否与成本函数+L1+L2 相同,有什么有用的信息吗?
  • 如果你在层上设置正则化器,那么它们将被添加到你指定的任何损失中。
  • 感谢您的 cmets,有没有办法找到当层使用 L1、L2 时 keras 如何计算?干杯。
  • 我在这里找到公式,如果有人想看,github.com/keras-team/keras/blob/master/keras/regularizers.py

标签: python tensorflow machine-learning keras loss-function


【解决方案1】:

您可以简单地为每一层使用内置权重regularization in Keras。为此,您可以使用层的kernel_regularizer 参数并为此指定正则化器。例如:

from keras import regularizers

model.add(Dense(..., kernel_regularizer=regularizers.l2(0.1)))

这些正则化将创建一个损失张量,该张量将添加到损失函数中,如 Keras source code 中所实现的:

# Add regularization penalties
# and other layer-specific losses.
for loss_tensor in self.losses:
    total_loss += loss_tensor

【讨论】:

    猜你喜欢
    • 2020-12-19
    • 2017-12-18
    • 2020-03-27
    • 1970-01-01
    • 2018-10-28
    • 2017-12-29
    • 1970-01-01
    • 2020-02-27
    • 2018-12-26
    相关资源
    最近更新 更多