You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Keras/TensorFlow自定义层中L2正则化不生效问题咨询

问题原因及解决方法

你的L2正则化没生效,核心问题出在自定义层的权重构建逻辑上:

  • Keras自定义层的权重初始化逻辑必须放在build方法里,而你写的是build_model——这个方法不会被Keras的内部机制自动调用,哪怕你手动调用了,Keras也无法正确收集权重的正则化损失,最终导致正则化完全没起作用。
  • 另外你的偏置b也没添加正则化(这不是当前问题核心,仅作额外提示)。

修正后的代码如下:

class Linear(keras.layers.Layer):
    def __init__(self, units=32, regularizer_amount=0.01, name="linear", **kwargs):
        super(Linear, self).__init__(**kwargs)
        self.units = units
        self.regularizer_amount = regularizer_amount

    def build(self, input_shape):
        # 用input_shape自动获取输入维度,无需手动传input_dim更灵活
        self.w = self.add_weight(
            shape=(input_shape[-1], self.units),
            initializer="random_normal",
            regularizer=keras.regularizers.L2(self.regularizer_amount),
            trainable=True,
            name="kernel"
        )
        self.b = self.add_weight(
            shape=(self.units,),
            initializer="random_normal",
            trainable=True,
            name="bias"
        )
        # 必须调用父类build方法完成初始化流程
        super().build(input_shape)

    def call(self, inputs):
        return tf.matmul(inputs, self.w) + self.b

关键修正点:

  1. 把权重初始化代码移到build方法中,Keras会在层第一次接收输入时自动调用该方法,同时正确注册正则化损失。
  2. 移除手动传入的input_dim,改用input_shape[-1]自动获取输入特征维度,更符合Keras使用习惯且更灵活。
  3. 调用super().build(input_shape)确保父类构建逻辑执行完成,这是自定义层的标准流程。

修改后,L2正则化的损失会被自动加入模型总损失,训练时就能看到正则化的效果了。

内容的提问来源于stack exchange,提问作者uiag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 06:34:59