AI Logic

Glossary

Regularization

Updated:

Diagram of one training step (training data → network → loss function from the prediction and the ground-truth label → parameter update, repeated) overlaid with the places where regularization intervenes. Left: data augmentation and Dropout. Right: Label Smoothing, L2 and L1 regularization, and Early Stopping

What is regularization?

Regularization is the umbrella term for techniques added to training to improve performance not on the training data but on unseen data (generalization performance). It is not the name of a single method but a collective name for many approaches. The textbook Deep Learning (Goodfellow et al., 2016) defines regularization as "any modification we make to a learning algorithm that is intended to reduce its generalization error but not its training error" (Section 5.2.2).

A neural network with many parameters can memorize even the fine quirks and noise of the training data, performing well on the training data but worse on new data. This is overfitting. Regularization curbs overfitting by adding constraints or perturbations so that the model does not fit the training data too closely.

For example, memorizing the answers to past exam papers lets a student solve the same questions but not slightly modified ones. Regularization is like making rote memorization of answers harder so that the student learns how to solve the problems.

The similarly named "normalization" is a process that aligns the range or distribution of values of data or layer outputs, and it is a different thing from regularization with a different purpose. However, a normalization method such as batch normalization can have a regularizing effect as a side effect.

Approaches to regularization

Regularization comes in many kinds, depending on which part of training it modifies. The table below summarizes the commonly used ones.

Where it intervenesHowRepresentative methods
Loss functionAdd a penalty that grows with the size of the weights to the loss functionL2 regularization (Weight Decay), L1 regularization
Network (only during training)Randomly disable some units or layersDropout, DropConnect, Stochastic Depth
Training dataTransform or mix data to increase the apparent amount of data (data augmentation)Mixup, Cutout, RandAugment
Ground-truth labelsUse slightly softened values instead of hard 1s and 0s for the targetsLabel Smoothing
Training lengthStop training when performance on the validation data starts to worsenEarly Stopping

All of these methods share the idea of sacrificing a little fit to the training data in exchange for better performance on new data. They are rarely used alone; multiple methods are often combined, for example Weight Decay, data augmentation and Dropout together.

L2 and L1 regularization

The most basic form of regularization adds a penalty based on the size of the weights to the loss function. Let LdataL_{\text{data}} be the original loss, wiw_i the weights, and λ\lambda (0 or greater) the strength of the penalty.

L2 regularization adds the sum of squared weights.

L=Ldata+λ2∑iwi2L = L_{\text{data}} + \frac{\lambda}{2} \sum_i w_i^2

L1 regularization adds the sum of absolute values of the weights.

L=Ldata+λ∑i∣wi∣L = L_{\text{data}} + \lambda \sum_i |w_i|

Since larger weights increase the loss, the model comes to use large weights only where they are truly needed. In linear regression in statistics, the version with L2 regularization is called ridge regression, and the version with L1 regularization is called the lasso.

L2 regularizationL1 regularization
What is addedSum of squared weightsSum of absolute values of weights
Effect on weightsShrinks all weights overallDrives many weights to exactly 0 (makes them sparse)
Suitable useWidely used in training neural networksWhen only the influential features should be selected

Writing the gradient descent update with L2 regularization, with learning rate η\eta, gives:

w←(1−ηλ) w−η∇Ldataw \leftarrow (1 - \eta\lambda)\, w - \eta \nabla L_{\text{data}}

At every update, the weights are first shrunk by a fixed factor (1−ηλ1 - \eta\lambda) and then moved by the gradient of the original loss. This is why L2 regularization is also called "Weight Decay."

L2 regularization and Weight Decay behave the same only with plain stochastic gradient descent (SGD). With an optimizer that adapts the learning rate for each parameter, such as Adam, adding an L2 penalty to the loss does not shrink the weights by a fixed factor. Loshchilov and Hutter showed this and proposed AdamW, which decouples weight decay from the gradient computation (2019). In PyTorch, the weight_decay of torch.optim.Adam acts as an L2 penalty by default, while the weight_decay of torch.optim.AdamW is decoupled Weight Decay.

Choosing the regularization strength

The strength of regularization (the λ\lambda of L2, the fraction of units dropped by Dropout, etc.) is a setting chosen by a person before training (a hyperparameter).

  • Too weak: Overfitting remains. Performance on the training data is good, but performance on the validation data stays low.
  • Too strong: The model can no longer learn even the important patterns in the training data (underfitting), and performance is low on both the training and validation data.

The strength is chosen by comparing performance on validation data held out separately from the training data. Methods for trying several values include random search and Bayesian optimization.

Do not use the test data, which is reserved for measuring final performance, to choose the strength. Tuning to the test data makes performance on it look better than the model's true ability.

In general, the less training data there is and the more parameters the model has, the more likely overfitting becomes and the more likely regularization is needed.

PyTorch example

Show code
python
import torch
import torch.nn as nn

'''
Combine commonly used regularization methods in a single training loop
'''

model = nn.Sequential(
  nn.Linear(20, 64),
  nn.ReLU(),
  nn.Dropout(p=0.5),       # Dropout: randomly zero half of the units, only during training
  nn.Linear(64, 3)
)

# Weight Decay: AdamW's weight_decay shrinks the weights a little at every update
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)

# Label Smoothing: soften the ground-truth labels slightly
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)

l1_lambda = 1e-5  # Strength of L1 regularization (0 when not used)

# Random data as an example (in practice, prepare separate training and validation data)
x_train, y_train = torch.randn(256, 20), torch.randint(0, 3, (256,))
x_val, y_val = torch.randn(64, 20), torch.randint(0, 3, (64,))

best_val, patience, wait = float('inf'), 5, 0
best_state = None
for epoch in range(100):
  model.train()                      # Enable Dropout
  optimizer.zero_grad()
  loss = criterion(model(x_train), y_train)
  # L1 regularization: add the sum of absolute weights to the loss (biases included here for simplicity)
  loss = loss + l1_lambda * sum(p.abs().sum() for p in model.parameters())
  loss.backward()
  optimizer.step()

  model.eval()                       # Disable Dropout for validation and inference
  with torch.no_grad():
    val_loss = criterion(model(x_val), y_val).item()

  # Early Stopping: stop if the validation loss does not decrease for 5 consecutive epochs
  if val_loss < best_val:
    best_val, wait = val_loss, 0
    best_state = {k: v.clone() for k, v in model.state_dict().items()}
  else:
    wait += 1
    if wait >= patience:
      print(f'Stopped at epoch {epoch}')
      break

model.load_state_dict(best_state)    # Restore the weights that performed best on the validation data

FAQ

Q. What is the difference between regularization and normalization?
A.

Regularization is the umbrella term for techniques that curb overfitting and improve generalization performance. Normalization is a process that aligns the range or distribution of values of data or layer outputs. They have different purposes and are different things.

Q. Should regularization always be used?
A.

Overfitting is more likely, and regularization more likely to be needed, with models that have many parameters or when training data is scarce. Too much regularization causes underfitting, so choose the strength by looking at performance on the validation data.

Q. Which regularization should be tried first?
A.

A common approach for many models is to start with Weight Decay, then add data augmentation for images and Dropout for models with many fully connected layers.

References

  1. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," Chapter 7: Regularization for Deep Learning, MIT Press, 2016.
  2. I. Loshchilov and F. Hutter, "Decoupled Weight Decay Regularization," ICLR, 2019.
  3. N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever, and R. Salakhutdinov, "Dropout: A Simple Way to Prevent Neural Networks from Overfitting," Journal of Machine Learning Research, 15(56), 1929–1958, 2014.
  4. S. Ioffe and C. Szegedy, "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift," ICML, 2015.
  5. PyTorch Documentation, "torch.optim.AdamW."
  6. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," Chapter 5: Machine Learning Basics (5.2.2 Regularization), MIT Press, 2016.
  7. A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, "Dive into Deep Learning," Section 3.7 Weight Decay.
  8. PyTorch Documentation, "torch.optim.Adam."