Overfitting and Underfitting
A complete guide to Overfitting and Underfitting: the Bias-Variance Tradeoff, detecting overfitting via loss curves, and prevention techniques (L1/L2 Regularization, Dropout, Early Stopping).
Consider three different students preparing for a history exam: 1. Student A skims only the chapter headings for ten minutes. They never learn key dates, causes, or historical concepts. On exam day, they struggle on both familiar practice questions and new exam questions. This student represents Underfitting (High Bias): their mental model is too simple to capture the subject. 2. Student B memorizes their practice notes word for word, including random typos, line numbers, and marginal scribbles. On practice questions they have seen before, they score 100%. But on the real exam, when questions are phrased slightly differently, they fail because they memorized quirks rather than general concepts. This student represents Overfitting (High Variance). 3. Student C focuses on understanding the underlying historical trends, causes, and themes. They can apply those principles effectively to unfamiliar questions on test day. This student achieves balanced generalization. In machine learning, this tension between underfitting and overfitting is known as the Bias-Variance Tradeoff. Finding the right balance is central to building reliable models.
Definition
Overfitting occurs when a model learns the noise and accidental patterns of the training data so closely that it struggles to generalize to new, unseen test data. Underfitting occurs when a model is too simple to capture the underlying patterns in the data.
Why It Matters
An overfitted model can give developers a false sense of confidence. In the lab, it might score 99% accuracy on training data. However, once deployed into production with fresh real-world inputs, performance can drop sharply, leading to poor customer experiences or costly errors. Techniques that manage overfitting (such as L1/L2 regularization, dropout, data augmentation, and early stopping) help ensure that models perform consistently in real-world use.
How It Works
Let us examine how errors break down and how to diagnose and prevent overfitting: 1. Breaking Down Expected Error (The Bias-Variance Tradeoff): Total test error can be broken down into three mathematical parts: $$\text{Total Error} = \text{Bias}^2 + \text{Variance} + \text{Irreducible Error}$$ • Bias (Underfitting): Error caused by using a model that is too simple to capture the true relationship (for example, fitting a straight line to curved data). • Variance (Overfitting): Error caused by the model being overly sensitive to specific training samples, fitting noise instead of general patterns. • Irreducible Error: Noise inherent in any measurement process that cannot be eliminated by the model. 2. How to Spot Overfitting on Loss Curves: Track Training Loss and Validation Loss across training epochs: • Good Fit: Both training and validation loss decrease steadily and level off close together. • Underfitting: Both curves remain high and flat; the model fails to learn the pattern. • Overfitting: Training loss keeps falling toward zero, but validation loss stops dropping and begins to climb. The growing gap between the curves indicates that the model is memorizing training data. 3. Practical Techniques to Reduce Overfitting: • Collect More Data & Augment Inputs: Giving the model a wider variety of examples helps it learn general patterns rather than memorizing individual points. • L1 Regularization (Lasso): - Adds a penalty based on the absolute sum of weights: $L_{reg} = L_0 + \lambda \sum |w_i|$. - Drives unhelpful weights to zero, effectively selecting useful features and keeping the model simpler. • L2 Regularization (Ridge / Weight Decay): - Adds a penalty based on the sum of squared weights: $L_{reg} = L_0 + \lambda \sum w_i^2$. - Shrinks weights smoothly toward zero, preventing any single feature from dominating. • Dropout (in Neural Networks): - During training, randomly deactivates a percentage of neurons (such as 20% to 50%) at each step. - Encourages neurons to learn independent representations rather than relying on specific neighbors. • Early Stopping: - Halts training once validation loss stops improving, saving the best performing checkpoint.
Bias-Variance Generalization Spectrum & Loss Curves
Key Points
- Underfitting reflects high bias (model is too simple); Overfitting reflects high variance (model memorizes noise).
- The Bias-Variance Tradeoff shows that reducing bias often increases variance, and vice versa.
- Overfitting is diagnosed when training error continues falling while validation error begins to rise.
- L1 Regularization (Lasso) can drive weights to zero; L2 Regularization (Ridge) shrinks weights smoothly.
- Dropout reduces co-dependence between neurons by randomly deactivating units during training.
Steps
Establish a High-Bias Baseline
Start with a simple model (like a linear regressor or shallow tree) to verify that basic signals can be learned before adding complexity.
Scale Capacity to Confirm Learning
Increase model depth or parameters to confirm that the model has sufficient expressive capacity to fit the training data.
Apply Regularization Penalties
Add L2 weight decay or L1 Lasso penalties to keep weight magnitudes bounded and controlled.
Introduce Randomization (Dropout & Augmentation)
In deep networks, insert Dropout layers after dense connections and apply data augmentation to inputs.
Deploy Early Stopping
Set a patience window to halt training when validation loss stops improving, and restore the best historical weights.
Formula
Bias-Variance Decomposition of Expected Mean Squared Error:
\mathbb{E}\left[ (y - \hat{f}(x))^2 \right] = \text{Bias}[\hat{f}(x)]^2 + \text{Var}[\hat{f}(x)] + \sigma^2
\text{where:}
\text{Bias}[\hat{f}(x)] = \mathbb{E}[\hat{f}(x)] - f(x) \quad \text{(Error from overly simplistic assumptions)}
\text{Var}[\hat{f}(x)] = \mathbb{E}\left[ (\hat{f}(x) - \mathbb{E}[\hat{f}(x)])^2 \right] \quad \text{(Error from sensitivity to training noise)}
\sigma^2 \quad \text{(Irreducible Bayes error inherent to the system)}Examples
Polynomial Curve Fitting
Underfitting: Fitting a straight line ($y = mx + b$) to data that clearly forms a curved arch. Balanced: Fitting a quadratic curve ($y = ax^2 + bx + c$). Overfitting: Fitting a 20th-degree polynomial that zig-zags through every individual outlier.
Dropout as Team Practice
If a sports team relies on one star player, other teammates may become passive. If the coach regularly benches random players during practice scrimmages, the rest of the team learns to pass, defend, and score independently. When the full team plays together, they are much more adaptable.
Real-World Examples
Automated Real Estate Valuation Models
Large home-buying platforms have experienced difficulties when algorithmic pricing models overfitted to unusual market conditions during housing booms. When buyer demand shifted, the models continued to overvalue properties based on historical noise, demonstrating the real-world risk of overfitting.
Facial Recognition Across Demographics
Early vision models trained predominantly on homogeneous image sets achieved high accuracy in lab testing, but struggled on diverse real-world populations until balanced datasets and broader data augmentation were used.
Technical Examples
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
# 1. Generate noisy quadratic data
np.random.seed(42)
X = np.random.uniform(-3, 3, size=(20, 1))
y = 0.5 * X.ravel()**2 + np.random.normal(0, 1.0, size=20)
# High-degree polynomial (Degree 10) creates extreme risk of overfitting
poly = PolynomialFeatures(degree=10, include_bias=False)
X_poly = poly.fit_transform(X)
# 2. Unregularized Model (High Variance / Overfitting)
unreg_model = LinearRegression()
unreg_model.fit(X_poly, y)
# 3. L2 Regularization (Ridge: Penalizes large weights smoothly)
ridge_model = Ridge(alpha=10.0)
ridge_model.fit(X_poly, y)
# 4. L1 Regularization (Lasso: Forces useless weights to absolute zero)
lasso_model = Lasso(alpha=0.5)
lasso_model.fit(X_poly, y)
print("Weight Coefficients across models:")
print(f" Unregularized Max Weight: {np.max(np.abs(unreg_model.coef_)):.2f} (Wildly inflated!)")
print(f" L2 Ridge Max Weight: {np.max(np.abs(ridge_model.coef_)):.2f} (Smoothly constrained)")
print(f" L1 Lasso Zeroed Weights: {np.sum(lasso_model.coef_ == 0)} / 10 features zeroed out!")Underfitting (High Bias) vs Overfitting (High Variance)
| Aspect | Underfitting (High Bias) | Overfitting (High Variance) |
|---|---|---|
| Root Cause | Model is too simple to capture the underlying pattern | Model is too complex and memorizes noise in the training set |
| Training Loss | High (model struggles even on training examples) | Very low (often near zero) |
| Validation Loss | High (similar to training loss) | High (diverges and climbs away from training loss) |
| How to Address | Increase model complexity, add features, reduce regularization | Add more data, apply L1/L2 penalties, add dropout, use early stopping |
| Visual Pattern | A straight line across curved data points | A wildly oscillating curve connecting every noisy outlier |
The Double Descent Phenomenon in Deep Learning
Geometric Sparsity Proof: L1 (Lasso) vs L2 (Ridge) Regularization
Advantages
- Regularization techniques help models perform predictably on new test data.
- L1 Lasso provides automated feature selection, keeping models simpler.
- Dropout offers ensemble-like regularization benefits without added inference overhead.
- Early stopping saves compute time by automatically finishing training when gains level off.
Limitations
- Applying too much regularization can choke model capacity, causing underfitting.
- Tuning regularization parameters requires running validation checks.
- Data augmentation must preserve meaningful real-world labels (e.g., flipping a '6' can turn it into a '9').
Interview Questions
Explain the geometric intuition for why L1 Regularization (Lasso) leads to sparse weights while L2 (Ridge) does not.
When minimizing loss subject to a regularization constraint, the solution lies at the point where the elliptical loss contour touches the constraint boundary. The L2 boundary is a smooth circle ($w_1^2 + w_2^2 \le C$), so the contour touches at a point where both weights are non-zero, shrinking them smoothly. The L1 boundary is a diamond with sharp corners located directly on the axes ($|w_1| + |w_2| \le C$). Because the expanding loss contour is far more likely to intersect a sharp corner first, the weights along other axes are driven to exactly zero, producing a sparse model.
What is Double Descent in modern Deep Learning, and how does it challenge the classical Bias-Variance Tradeoff?
Traditional theory states that once model capacity exceeds the data size, variance explodes and test error climbs continuously. In modern deep learning, researchers observed Double Descent: as parameter counts scale far past the interpolation threshold, test error can drop again. Because over-parameterized models trained with stochastic gradient descent tend to find smooth minimum-norm solutions, they can generalize well despite having more parameters than training samples.
Practice Questions
- A model achieves 99.8% training accuracy and 68.2% validation accuracy. Diagnose the issue and prescribe three concrete remediation steps.
- Why must you always call `model.train()` before training and `model.eval()` before evaluation when working with PyTorch networks containing Dropout or BatchNorm?
