Lesson 4 of 10
The Bias-Variance Tradeoff & Generalization Error
The Bias-Variance Decomposition is the governing law of supervised learning generalization. Total Expected Generalization Error is mathematically decomposed into: Error = (Bias)² + Variance + Irreducible Noise σ². Bias quantifies systematic error caused by overly restrictive inductive assumptions (underfitting). Variance quantifies sensitivity to random perturbations in the training set (overfitting). Managing this balance via capacity control and regularization is the core objective of the ML engineer.
Empirical Demonstration of Underfitting vs Overfitting
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import mean_squared_error
# Generate true non-linear sinusoidal function corrupted by Gaussian noise
np.random.seed(42)
n_pts = 40
X = np.sort(np.random.uniform(0, 1, n_pts))
y_true = np.sin(2 * np.pi * X)
y = y_true + np.random.normal(0, 0.2, n_pts)
X_train, X_test = X[:25, np.newaxis], X[25:, np.newaxis]
y_train, y_test = y[:25], y[25:]
degrees = [1, 4, 15] # 1: High Bias, 4: Optimal Balance, 15: High Variance
results = {}
for deg in degrees:
model = Pipeline([
('poly', PolynomialFeatures(degree=deg)),
('reg', LinearRegression())
])
model.fit(X_train, y_train)
train_mse = mean_squared_error(y_train, model.predict(X_train))
test_mse = mean_squared_error(y_test, model.predict(X_test))
results[deg] = (train_mse, test_mse)
print(f"Degree {deg:2d} | Train MSE: {train_mse:.4f} | Test MSE: {test_mse:.4f} -> {'Overfitting (High Variance)' if test_mse > train_mse * 4 else 'Balanced' if deg == 4 else 'Underfitting (High Bias)'}")
# Regularization to cure High Variance:
regularized_model = Pipeline([
('poly', PolynomialFeatures(degree=15)),
('ridge', Ridge(alpha=0.1))
])
regularized_model.fit(X_train, y_train)
reg_test_mse = mean_squared_error(y_test, regularized_model.predict(X_test))
print(f"Degree 15 + Ridge Regularization -> Test MSE stabilized to: {reg_test_mse:.4f}")Pro Tip: Diagnosing Bias vs Variance via Loss Gaps
If both training loss and validation loss are high and plateaued near each other, your model suffers from High Bias (increase model capacity, add polynomial features, or decrease L1/L2 penalty). If training loss is negligible but validation loss is substantially higher, your model suffers from High Variance (gather more training samples, apply regularization, use dropout/pruning, or reduce feature count).
MlOverfittingBiasVariance Visual Representation
Hands-On Challenge: Plotting Validation Curves
Using `sklearn.model_selection.validation_curve`, compute and plot training and test scores for a `RandomForestClassifier` across `max_depth` values from 1 to 20. Identify the inflection point where validation accuracy begins to degrade while training accuracy continues toward 100%.
Quick Quiz & Key Concept Checks
Common Pitfall: The Double Descent Phenomenon
In classical statistical learning, error follows a U-shaped curve as model capacity grows. However, in modern deep neural networks and overparameterized interpolating models, error can decrease again past the interpolation boundary (Double Descent). Do not assume a complex model will always overfit if modern implicit regularization (SGD, weight decay) is applied.
Finished this lesson?