What is Regularization?
Regularization means making the model a little less free so that it cannot just memorize the training data. It encourages simple solutions that work well on new data.
1. Dropout
During training, dropout randomly switches off a fraction of the neurons in each step. The network cannot rely on any single neuron, so it learns more robust features.
Simple example: A football team where random players are asked to sit out during practice. The team learns to play well even when someone is missing.
python
from keras import layers
model = keras.Sequential([
keras.Input(shape=(784,)),
layers.Dense(256, activation="relu"),
layers.Dropout(0.3), # drop 30% of neurons while training
layers.Dense(128, activation="relu"),
layers.Dropout(0.3),
layers.Dense(10, activation="softmax"),
])
- Typical rates are between 0.2 and 0.5
- Dropout is active only during training. Keras turns it off automatically when you call
predict()
2. L2 Regularization (Weight Decay)
L2 adds a penalty to the loss for large weights. The model prefers smaller weights, which usually means a smoother, simpler function.
python
from keras import regularizers
layers.Dense(
128,
activation="relu",
kernel_regularizer=regularizers.L2(0.001)
)
# L1 pushes some weights to exactly zero
layers.Dense(128, activation="relu", kernel_regularizer=regularizers.L1(0.0001))
3. Batch Normalization
Batch normalization rescales the outputs of a layer so that they have a stable mean and spread. It makes training faster and more stable, and also gives a mild regularizing effect.
python
model = keras.Sequential([
keras.Input(shape=(784,)),
layers.Dense(128),
layers.BatchNormalization(),
layers.Activation("relu"),
layers.Dense(10, activation="softmax"),
])
| Technique | Helps with | Where to put it |
| Dropout | Overfitting | After Dense layers |
| L2 / L1 | Overfitting, large weights | Inside a layer as kernel_regularizer |
| BatchNormalization | Training speed and stability | After Dense or Conv layers |
| EarlyStopping | Overfitting | As a callback |
Before and After
python
def build(use_dropout):
layers_list = [keras.Input(shape=(784,)),
layers.Dense(512, activation="relu")]
if use_dropout:
layers_list.append(layers.Dropout(0.4))
layers_list.append(layers.Dense(10, activation="softmax"))
m = keras.Sequential(layers_list)
m.compile("adam", "sparse_categorical_crossentropy", metrics=["accuracy"])
return m
# Train both versions and compare the gap between train and validation accuracy
Tip: Do not apply every technique at once. Add one, test, and keep it only if the validation score improves.
Conclusion
Dropout, L2 and batch normalization are standard tools in every deep learning toolbox. Use them whenever the model overfits or training is unstable.
Quick Summary: Dropout switches off random neurons, L2 penalizes big weights and BatchNormalization stabilizes training.