liveBook · Manning

Weight decay

As explained in Deep Learning with Python, Third Edition

Weight decay is a regularization technique that discourages large model parameters by penalizing their magnitudes in the objective or shrinking them during optimization.

When a model overfits, constraining its weights can help improve generalization. Weight decay adds a cost for large weights; in neural networks, it is mathematically equivalent to L2 regularization. section 5.4.4 section 5.5

The idea is to favor simpler models by encouraging smaller parameter values. Weight decay is one option alongside reducing model capacity, dropout, and early stopping. section 5.4.4 section 5.5

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,
)

This Keras example applies L2 regularization with strength 0.002 to the kernels of two dense layers in an IMDb review classifier. section 5.4.4

How Deep Learning with Python, Third Edition covers it

How deep it goes
Defines the penalty on large weights and its equivalence to L2 regularization, without deriving the optimization mechanics.
Examples
Shows Keras L2 regularization on dense layers in an IMDb review classifier.
What you can do after
Apply it via Keras by adding an L2 regularizer to a layer’s kernel.
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.