Skip to content
E
Educatum

How to avoid overfitting?

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

Overfitting happens when a model memorizes training noise and sample-specific quirks rather than generalizable patterns, causing strong training scores alongside poor test accuracy. Key defenses include collecting more diverse data, applying data augmentation, reducing model complexity, adding L1/L2 regularization or dropout, using early stopping on a validation set, and combining models via ensembles.

Study Card: How to avoid overfitting?

Direct Answer

Overfitting occurs when a model’s effective capacity exceeds what the training data supports, causing it to memorize random noise and sample idiosyncrasies rather than the underlying signal. To improve generalization on unseen data, practitioners combine data-centric and model-centric strategies: collecting more representative training data, applying label-preserving data augmentation, reducing model complexity (fewer parameters, shallower trees), adding explicit regularization (L1/L2 weight decay, dropout, batch/layer normalization), monitoring validation loss for early stopping, and averaging variance via ensembles such as bagging or Random Forests.

Key Terms

  • Overfitting: Low training error accompanied by significantly higher validation/test error due to high variance.
  • Regularization: Adding parameter penalties (L1L_1, L2L_2) or stochastic perturbations (dropout) to discourage overly complex functions.
  • Generalization: Consistent predictive performance on unseen data drawn from the target distribution.
  • Early Stopping: Stopping optimization when validation error begins rising and restoring the weights from the lowest validation-loss epoch.
  • Cross-Validation: Partitioning training data into kk folds to diagnose overfitting and tune regularization hyperparameters without leaking the test set.

Example

Imagine training an image classifier for cats vs. dogs where nearly all training cats happen to be striped tabbies sitting indoors. An overparameterized network can latch onto stripes and indoor backgrounds instead of feline facial structure—misclassifying solid-color cats or striped tigers at test time. Expanding dataset diversity, applying label-preserving augmentations (random crops, shifts, slight color jitter), penalizing large weights with L2 weight decay and dropout, and stopping training as soon as validation loss diverges upward from training loss keep the learned representations focused on generalizable features.

Code Implementation

from sklearn.model_selection import train_test_split
from tensorflow import keras

# Load MNIST dataset and hold out a validation split cleanly from training data
(x_train_full, y_train_full), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train, x_val, y_train, y_val = train_test_split(
    x_train_full, y_train_full, test_size=0.2, random_state=42, stratify=y_train_full
)

# Normalize all splits consistently to [0, 1]
x_train = x_train.astype("float32") / 255.0
x_val = x_val.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0

# Define model with L2 weight regularization and Dropout
model = keras.Sequential([
    keras.Input(shape=(28, 28)),
    keras.layers.Flatten(),
    keras.layers.Dense(
        128,
        activation='relu',
        kernel_regularizer=keras.regularizers.l2(0.001)
    ),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(10, activation='softmax')
])

model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# Stop training when validation loss stops improving and restore best weights
early_stopping = keras.callbacks.EarlyStopping(
    monitor='val_loss', patience=3, restore_best_weights=True
)

history = model.fit(
    x_train,
    y_train,
    epochs=15,
    batch_size=64,
    validation_data=(x_val, y_val),
    callbacks=[early_stopping],
    verbose=1
)

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"\nTest accuracy: {test_acc:.4f}")
  • Bias-Variance Tradeoff: Overfitting reflects high variance; regularization and simpler models trade a slight increase in bias for substantially lower variance and total error.
  • L1 vs. L2 Regularization & Dropout: L1 promotes sparse weights (feature elimination), L2 shrinks weights smoothly toward zero (weight decay), and dropout trains an implicit ensemble of sub-networks to reduce neuron co-adaptation.
  • Ensemble Methods (Bagging & Random Forests): Bagging trains models on bootstrap samples of rows to reduce variance; Random Forests additionally subsample features at each split to decorrelate trees further.
  • Tree-Specific Pruning: For decision trees and gradient boosting, setting max_depth, min_samples_leaf, ccp_alpha pruning, and shrinkage (learning_rate) prevents memorizing noisy leaves.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.