TensorFlow regularization loss和model.losses

以如下模型为例,

l2_reg = keras.regularizers.l2(0.05)
model = keras.models.Sequential([
    keras.layers.Dense(30, activation="elu", kernel_initializer="he_normal",
                       kernel_regularizer=l2_reg),
    keras.layers.Dense(1, kernel_regularizer=l2_reg)
])

两个Dense层都带有regularizer,因此都有regularization loss项。

访问model.losses可以得到当前的regularization loss

[<tf.Tensor: id=719712, shape=(), dtype=float32, numpy=0.07213736>,
 <tf.Tensor: id=719720, shape=(), dtype=float32, numpy=0.06456626>]

当前状态下第一层和第二层的regularization loss分别是0.07213736和0.06456626。

下面验证一下。L2 regularization下的损失函数的表达式

\(L=\mathrm{error}+\lambda\sum w^2_i\)

其中第二项即regularization loss。

wt = model.layers[1].get_weights()[0]
np.sum(wt**2)*0.05

输出结果0.06456626057624817,等于model.losses的第二项,即第二层的regularization loss.

以如下模型为例,

l2_reg = keras.regularizers.l2(0.05)
model = keras.models.Sequential([
    keras.layers.Dense(30, activation="elu", kernel_initializer="he_normal",
                       kernel_regularizer=l2_reg),
    keras.layers.Dense(1, kernel_regularizer=l2_reg)
])

两个Dense层都带有regularizer,因此都有regularization loss项。

访问model.losses可以得到当前的regularization loss

[<tf.Tensor: id=719712, shape=(), dtype=float32, numpy=0.07213736>,
 <tf.Tensor: id=719720, shape=(), dtype=float32, numpy=0.06456626>]

当前状态下第一层和第二层的regularization loss分别是0.07213736和0.06456626。

下面验证一下。L2 regularization下的损失函数的表达式

\(L=\mathrm{error}+\lambda\sum w^2_i\)

其中第二项即regularization loss。

wt = model.layers[1].get_weights()[0]
np.sum(wt**2)*0.05

输出结果0.06456626057624817,等于model.losses的第二项,即第二层的regularization loss.