SeeingML
How Machines Learn Guide 4 of 6 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

Overfitting vs Underfitting & Bias-Variance

How to tell real learning apart from blind memorization, understand the bias-variance tradeoff, and cure overfit models.

Picture a small neighborhood cafe trying to predict daily iced-coffee sales from outside temperature. Sales climb quickly as mornings warm up from 8°C to 24°C, then level off above 30°C when people stay indoors. Matching that smooth curve without chasing random daily noise is the core tension of overfitting vs. underfitting and the bias-variance tradeoff.

You only have 11 past days of noisy sales logs (one sunny Tuesday happened to have a street fair; one warm Friday had a sudden shower). Imagine choosing how bendy a wire you use to trace those 11 days. In machine learning, this “allowed curve bends” dial is called the polynomial degree:

  • Degree 1 (Straight Line): A stiff straight ruler with zero bends. It underfits, missing the smooth summer curve completely.
  • Degree 3 (Smooth Curve): A gentle bendy wire that follows the real rise and summer plateau while ignoring random daily bumps.
  • Degree 9 (Rollercoaster): A wild track allowed so many twists that it overfits, zigzagging through every noisy training dot while producing absurd predictions for tomorrow.

Drag the Allowed Curve Bends (Polynomial Degree) slider below from Degree 1 (Straight Line) up to Degree 9 (Rollercoaster), and watch the U-shaped Test Error curve on the right reveal the sweet spot.

Interactive Lab 1: Curve Complexity & the U-Shaped Error Curve
Underfitting (Too Stiff)
Training dots (11 days)Unseen Test dots (11 days)Model FitTrue Curve (off)
4080120160200Iced Coffees Sold (cups)8°C14°C20°C26°C32°COutside Temperature (°C)
Sweet Spot010203040Error (cups)13579Curve Degree (Allowed Bends)Train Error: 18.7 cupsTest Error: 14.9 cups
Degree 1 (Straight Line)
Degree 1 (Straight Line) underfits: a stiff ruler misses both chilly mornings and the hot afternoon plateau, leaving high error on Train (18.7 cups). Unseen Test Error is 14.9 cups. Slide right to Degree 3 to let the wire bend smoothly.

Notice the unmistakable fingerprint on the right chart:

  • Training error (purple) drops forever as you allow more bends. A model can always look better on past data by memorizing harder.
  • Unseen test error (red) drops into a sweet-spot valley around Degree 2 to 3, then climbs sharply back upward as the curve starts chasing random daily noise.

Overfitting vs. Underfitting and the Bias-Variance Tradeoff

Every mistake a model makes on unseen data splits cleanly into two everyday behaviors:

  1. Bias (Stubborn miss): Even if you retrained the model on ten fresh sets of cafe days, a stiff straight ruler always misses the curved summer peak in the same systematic way.
  2. Variance (Jitters): A wild degree-9 rollercoaster reacts so dramatically to whichever 11 days you happened to collect that retraining on a different two-week stretch produces a totally different squiggle.

Switch between Too Stiff (Deg 1), Just Right (Deg 3), and Too Jumpy (Deg 9) below and click Show All 10 Samples to watch both the overlaid curves and the dartboard react together.

Interactive Lab 2: The Bias-Variance Tradeoff (10 Fresh Samples)
True PatternAverage of 10 ModelsIndividual Samples (5)
50100150200Cups Sold8°C16°C24°C32°COutside Temperature (°C) · 5 Retrained Models Shown
Bullseye = True Pattern
Each dart = 1 retrained model (5/10 shown)
Total Error = Bias2 + Variance + Noise
171=106+11+54
Bias2 (Stubborn miss)106
Variance (Jitters)11
Noise (Random noise)54
Too Stiff (Degree 1): High Bias (106) and Low Variance (11), giving Total Error = 171. All 5 trained lines agree closely, yet every single one stubbornly misses the summer bend, clustering darts off-center from the bullseye.

Every prediction’s expected mistake adds up as Total Error = Bias² + Variance + Irreducible Noise. You can never shrink that third piece (Irreducible Noise, random unrecorded events like a nearby bus breakdown or a pop-up street fair) down to zero. The whole craft of model tuning is finding the sweet spot where Bias² + Variance hits its minimum.


Three real cures when your model is overfitting

Suppose you already have a wildly overfit Degree-9 rollercoaster with huge Unseen Test Error. Why does it spiral so violently between dots? To yank the line sharply up and down from one nearby dot to the next, the model attaches gigantic competing positive and negative multipliers (called weights) that nearly cancel on training days, yet explode everywhere in between.

How do real machine learning teams calm a wild model back down? You have three reliable levers:

  1. Collect more training examples: Random daily blips average out when the model sees 35 days instead of 11.
  2. Shrink gigantic weights (Ridge / L2 regularization): Charge the model a gentle penalty whenever its weights grow huge (officially called Ridge or L2 regularization). Because massive competing weights now cost extra, the rollercoaster relaxes into a smooth curve unless the data genuinely demands a bend.
  3. Simplify the model: Lower its allowed curve bends (degree) or drop noisy input clues.

Start from the wild overfit state below and test each cure one by one. Watch Weight Magnitude shrink dramatically as the weight-shrinking penalty tames the wild swings!

Interactive Lab 3: Three Real Cures for an Overfit Model
Fitted Curve (wild red)True Curve (dashed green)Training dots (11 days)Unseen Test dots (11 days)
4080120160200Iced Coffees Sold (cups)8°C14°C20°C26°C32°COutside Temperature (°C) · Training Size: 11 Days
Train Error
9.3 cups
Unseen Test Error
23.2 cups
Weight Magnitude
4,637
Tip: Test one cure at a time, then click “Reset to Wild Overfit” above to compare all three from the same broken curve.
Cure 1: Collect More Training Days
Cure 2: Weight-Shrinking Penalty (Ridge L2)Off
Degree 9 (Rollercoaster)
Simpler (Deg 2)Wilder (Deg 9)
Starting state: wildly overfit Degree-9 rollercoaster on 11 days. Unseen Test Error is 23.2 cups and Weight Magnitude is 4,637. Try any of the three cures below to calm it down!
✓ Tip

Different model families, same calming idea: Keeping a model from memorizing noise is broadly called regularization. For curve and linear models, you shrink huge weights (L2 regularization). For neural networks, you can randomly switch off a fraction of neurons during each training step so no single pathway memorizes the data (dropout). For decision trees, you cap how many stacked yes/no questions a tree may ask so it cannot isolate single noisy rows (tree depth limit).


Should you collect more data, or build a smarter model?

One of the most expensive mistakes in real-world AI projects is spending six months collecting ten times more training data when the model is actually underfitting.

You can tell in five minutes by plotting Learning Curves (Training Error vs. Validation Error as dataset size grows). Switch between Overfitting Model and Underfitting Model below and drag Training Examples Available from 20 to 500 to read both signatures immediately.

Interactive Lab 4: Reading Learning Curves (More Data vs. Smarter Model)
Validation Error: 25.6 cupsTraining Error: 6.3 cupsGap: 19.3 cups
Target (~11 cups)
010203040Prediction Error (cups)20100200300400500Number of Training Examples CollectedDesired target error (~11 cups)
120 examples
20 (Tiny dataset)250500 (Large dataset)
Wide overfitting gap at 120 examples: Training Error is tiny (6.3 cups), while Validation Error sits much higher (25.6 cups, a 19.3-cup gap). Drag Training Examples right toward 350 to 500 to test whether more data cures it!
See the Bias-Variance theorem, Ridge regularization & modern double descentThesis / Reference

1. Exact Bias-Variance Decomposition: Suppose true outcomes follow y=f(x)+εy = f(x) + \varepsilon with E[ε]=0\mathbb{E}[\varepsilon]=0 and Var(ε)=σε2\text{Var}(\varepsilon)=\sigma_\varepsilon^2. For any estimator f^(x)\hat{f}(x) trained on random sample SS, the expected squared prediction error at an unseen test point xx decomposes exactly into three non-negative terms:

ES,ε ⁣[(y−f^(x))2]=(ES[f^(x)]−f(x))2⏟Bias2+ES ⁣[(f^(x)−ES[f^(x)])2]⏟Variance+σε2⏟Irreducible Noise\mathbb{E}_{S,\varepsilon}\!\left[(y - \hat{f}(x))^2\right] = \underbrace{\left(\mathbb{E}_S[\hat{f}(x)] - f(x)\right)^2}_{\text{Bias}^2} + \underbrace{\mathbb{E}_S\!\left[\left(\hat{f}(x) - \mathbb{E}_S[\hat{f}(x)]\right)^2\right]}_{\text{Variance}} + \underbrace{\sigma_\varepsilon^2}_{\text{Irreducible Noise}}

2. Penalized Empirical Risk (Ridge L2 vs. Lasso L1): Regularization constrains effective hypothesis complexity by adding a norm penalty on the slope weights (leaving the intercept bb unpenalized so baseline shifts remain free):

w^Ridge=arg⁡min⁡w{1n∑i=1n(yi−b−ϕ(xi)⊤w)2+λ∥w∥22}\hat{\mathbf{w}}_{\text{Ridge}} = \arg\min_{\mathbf{w}} \left\{ \frac{1}{n}\sum_{i=1}^n \left(y_i - b - \mathbf{\phi}(x_i)^\top \mathbf{w}\right)^2 + \lambda \|\mathbf{w}\|_2^2 \right\}

With Ridge (ℓ2\ell_2), the closed-form solution becomes w^=(Φ⊤Φ+nλI)−1Φ⊤y\hat{\mathbf{w}} = (\mathbf{\Phi}^\top\mathbf{\Phi} + n\lambda \mathbf{I})^{-1}\mathbf{\Phi}^\top\mathbf{y}, shrinking correlated weights smoothly toward zero. Replacing ∥w∥22\|\mathbf{w}\|_2^2 with Lasso (ℓ1\ell_1, ∥w∥1\|\mathbf{w}\|_1) drives irrelevant feature weights to exact zero, performing automatic feature selection.

3. Modern Thesis Note (Double Descent): In classical parametric models (linear models, fixed-basis polynomials, shallow trees), test error follows the U-shaped curve shown in Lab 1. In heavily overparameterized deep neural networks, Belkin et al. (2019, PNAS) documented double descent: test error peaks sharply at the interpolation threshold where parameters match sample count, then descends a second time as gradient descent selects minimum-norm interpolating solutions. Even there, validation curves and regularization (weight decay, dropout, data augmentation) remain the primary guardrails.

See Ridge regularization & learning curves in PythonOptional Code
python
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import root_mean_squared_error

# Compare unregularized degree-9 vs Ridge-regularized degree-9
raw_poly = make_pipeline(PolynomialFeatures(9), StandardScaler(), Ridge(alpha=1e-7))
calm_poly = make_pipeline(PolynomialFeatures(9), StandardScaler(), Ridge(alpha=0.5))

raw_poly.fit(X_train, y_train)
calm_poly.fit(X_train, y_train)

print("Overfit Test RMSE:", round(root_mean_squared_error(y_test, raw_poly.predict(X_test)), 2))
print("Ridge   Test RMSE:", round(root_mean_squared_error(y_test, calm_poly.predict(X_test)), 2))

Quick diagnosis cheat sheet

  1. Train error high AND Validation error high? You are underfitting. Add richer features, relax regularization, or try a more flexible model. Don’t waste budget collecting more of the same data yet.
  2. Train error tiny AND Validation error much higher? You are overfitting. Collect more training examples, dial up regularization (weight-shrinking L2, neuron dropout, or a tree depth limit), or simplify the model.
  3. Not enough rows for a trustworthy single validation curve? Next up in Cross-Validation, you will learn how to rotate every slice of a small dataset through the exam seat for a rock-solid score.
✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Your house-price model gets $4k average error on the training set, but $58k average error on unseen test homes. What is happening?

Pick an option first, or peek anytime
2

Both your training error (32%) and validation error (34%) are painfully high and stay completely flat even when you double your training data. What should you try next?

Pick an option first, or peek anytime
3

How does weight-shrinking with Ridge (L2) regularization calm down a wildly wiggly rollercoaster curve?

Pick an option first, or peek anytime
4

With a powerful enough model and enough tuning, you can reduce unseen test error all the way to 0.0 even when real-world measurements contain random unrecorded noise.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is overfitting in machine learning in simple terms?
Overfitting happens when a model memorizes random quirks and noise inside its training data instead of learning the true underlying pattern. It looks brilliant on training examples (near-zero error) but makes wild mistakes on fresh unseen data.
What is the difference between overfitting and underfitting?
Underfitting means a model is too rigid to capture the real pattern, causing high error on both training and test data. Overfitting means a model is overly flexible and chases noise, causing tiny training error alongside high test error.
What is the bias-variance tradeoff?
Bias is systematic error from an overly simple model consistently missing the true curve. Variance is instability from an overly complex model changing wildly whenever the training sample changes. Lowering one tends to raise the other, so you tune model flexibility to minimize their sum.
How do you fix overfitting in practice?
The three most reliable fixes are: collecting more diverse training examples, adding regularization (such as Ridge L2 or Lasso L1 penalties that discourage extreme weights), and simplifying the model or pruning excess features.
Will adding more training data always fix a bad model?
No. More data shrinks variance and helps an overfit model dramatically, but if a model is underfitting (for example, fitting a straight line to curved data), even a million extra rows will still plateau at high error.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/overfitting-underfitting/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026overfittingunderfitting,
  author       = {Irshad, Muhammad Aashir},
  title        = {Overfitting vs Underfitting & Bias-Variance: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/overfitting-underfitting/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Overfitting vs Underfitting & Bias-Variance: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/overfitting-underfitting/