liveBook · Manning

Weight decay

As explained in Deep Learning with Python, Third Edition

Weight decay is a model-training regularization technique that discourages large parameter values by penalizing their magnitudes or shrinking them during optimization.

Weight decay helps limit overfitting by discouraging large model weights. It does this by adding a cost for large weights to the loss function. In neural networks, weight decay is mathematically equivalent to L2 regularization; L1 regularization instead penalizes the absolute values of weights. section 5.4.4

A practical starting point is to add L2 regularization when an overfitting model needs better generalization. The example applies it to the kernels of two Dense layers in an IMDb review classifier. section 5.4.4

Listing 5.13 Adding L2 weight regularization to the model
from keras.regularizers import l2

model = keras.Sequential(
    [
        layers.Dense(16, kernel_regularizer=l2(0.002), activation="relu"),
        layers.Dense(16, kernel_regularizer=l2(0.002), activation="relu"),
        layers.Dense(1, activation="sigmoid"),
    ]
)
model.compile(
    optimizer="rmsprop",
    loss="binary_crossentropy",
    metrics=["accuracy"],
)
history_l2_reg = model.fit(
    train_data,
    train_labels,
    epochs=20,
    batch_size=512,
    validation_split=0.4,
)

Keras example adding an L2 regularizer to Dense-layer kernels before compiling and training the model. section 5.4.4

How Deep Learning with Python, Third Edition covers it

How deep it goes
Defines L1 and L2 penalties, equates weight decay with L2, and demonstrates Keras usage without deriving optimizer internals.
Examples
Uses an IMDb review classifier with L2 penalties on two Dense-layer kernels.
What you can do after
Apply it via Keras by attaching an L2 regularizer to Dense-layer kernels.
How it connects
Connects weight decay to L2 regularization, overfitting, dropout, and early stopping.

Also explained in

Compare how 9 books explain weight decay →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with Python, Third Edition. The section links point to the parts of the book it draws on.