What is Weight Decay?
Weight decay is a regularization technique used in machine learning to prevent overfitting by discouraging large weights in the model. It works by adding a penalty term to the loss function that scales with the magnitude of the weights, encouraging the model to keep weights small unless they significantly improve the loss.
Mathematically, weight decay is equivalent to L2 regularization, where the loss function is modified as:
[
\text{Loss}{\text{total}} = \text{Loss}{\text{original}} + \lambda \sum_{i} w_i^2
]
- ( \lambda ) (lambda) is the weight decay coefficient, controlling the strength of regularization.
- ( w_i ) are the model's weights.
How Does Weight Decay Work?
- Penalizes Large Weights: By adding a term proportional to the squared weights, the optimizer is encouraged to keep weights small.
- Improves Generalization: Prevents the model from fitting noise in the training data, leading to better performance on unseen data.
- Works with Gradient Descent: During backpropagation, the gradient update includes an additional term from the weight decay:
[
w_{t+1} = w_t - \eta \left( \nabla \text{Loss} + 2 \lambda w_t \right)
]
where ( \eta ) is the learning rate.
How to Choose the Right Weight Decay Value?
Selecting an appropriate ( \lambda ) is crucial—too high leads to underfitting, too low may not prevent overfitting. Here’s how to choose it:
-
Start with Common Defaults:
- Typical range: ( 10^{-6} ) to ( 10^{-2} ).
- Common choices: ( 0.01, 0.001, 0.0001 ).
-
Use Cross-Validation:
- Try multiple values (e.g., ( [0.1, 0.01, 0.001, 0.0001] )) and pick the one with the best validation performance.
-
Balance with Learning Rate:
- Higher learning rates may require smaller weight decay to avoid excessive regularization.
-
Model-Specific Adjustments:
- Simpler models (e.g., linear regression) may need stronger decay.
- Deep neural networks often use smaller decay (e.g., ( 0.0001 ) or ( 0.0005 )).
-
Empirical Testing:
- Monitor training/validation loss—if the model underfits, reduce ( \lambda ); if it overfits, increase it.
Practical Tips
- AdamW Optimizer: Modern optimizers like AdamW decouple weight decay from gradient updates, making tuning more stable.
- Batch Normalization: If your model uses batch norm, weight decay may have less impact (since BN already regularizes activations).
- Dataset Size: Larger datasets may need less weight decay.
Example (PyTorch)
optimizer = torch.optim.AdamW(model.parameters(), lr=0.001, weight_decay=0.01)
Conclusion
Weight decay is a powerful tool to prevent overfitting. The right value depends on your model, dataset, and optimization setup. Experiment with different values and use validation performance to guide your choice.