以如下模型為例,
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.