What Is Overfitting and Underfitting in Machine Learning?

upGradWritten by

Share:

Updated on Dec 02, 2026|10 min read|16.84K+ views
Quick Summary

Overfitting and underfitting in machine learning are two opposite ways a model fails. An overfit model memorises its training data, noise included, so it scores well there but poorly on new data. An underfit model is too simple to learn the real pattern, so it does badly on both. Comparing training and test scores shows which problem you have.

Quick Overview

  • Short answer: Overfitting means strong training results but weak results on new data; underfitting means weak results on both.
  • Root cause: Model complexity that does not match the problem, too much in one case and too little in the other.
  • How to tell: Compare training performance with validation or test performance, ideally across a learning curve.
  • Inside this guide: Definitions, a side-by-side table, a worked Python example, detection methods, fixes, five scenarios and the bias–variance link.

Getting models fit right is one of the first practical skills in any ML role. Explore upGrad's Machine Learning Courses to find a program that takes you from these fundamentals to building and tuning real models.

Overfitting vs Underfitting in Machine Learning at a Glance

Basis

Underfitting

Overfitting

Model complexity

Too simple for the data

Too complex for the data

Training performance

Poor

Very good, sometimes near perfect

Unseen-data performance

Poor

Noticeably worse than training

Likely issue

High bias

High variance

Possible response

Add features, use a richer model, train longer

Simplify, regularise, add data, stop earlier

What is Overfitting in Machine Learning?

Overfitting is what happens when a model treats random noise in its training data as if it were a real pattern. It fits the examples it has seen extremely well, sometimes perfectly, and then stumbles on anything new.

A quick illustration: A spam filter trained on a few hundred emails notices that every spam message in its sample happened to arrive on a Tuesday. It starts flagging Tuesday emails. On the training set, accuracy looks superb. On next month's inbox, it misfires constantly, because the Tuesday link was a coincidence.

Overfitting usually comes from a mix of a very flexible model (deep trees, high-degree polynomials, large neural networks), too little training data and too many features relative to the number of examples. It is most common in supervised learning, where the model is fitted to labelled examples.

What is Underfitting in Machine Learning?

Underfitting is the reverse problem. The model is too simple, or too briefly trained, to capture the structure in the data, so its errors stay high everywhere.

Example: Predicting house prices with a straight line based only on floor area. Prices also depend on location, age and amenities, and the relationship with area may curve. The line misses most of that, so predictions are off on the training houses and on new listings.

Typical causes are an overly simple algorithm, too few useful features, heavy regularisation or stopping training too early.

Difference Between Overfitting and Underfitting in Machine Learning

The table near the top summarises the main contrasts. In short, the difference between overfitting and underfitting in machine learning comes down to where the errors appear:

  • Underfitting: High error on training data and on unseen data. The model has not learned enough.
  • Overfitting: Low error on training data, much higher error on unseen data. The model has learned too much of the wrong thing.
  • Good fit: Low error on both, with only a small gap between them.

No single metric defines these states. A 5% gap may be fine for one problem and worrying for another; what matters is the pattern relative to the task.

A Worked Example

The short script below fits three polynomial models to 40 noisy points from a sine curve, using 70% for training and 30% for testing. It shows overfitting and underfitting examples side by side:

import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

rng = np.random.default_rng(0)
X = np.sort(rng.uniform(0, 1, 40)).reshape(-1, 1)
y = np.sin(2 * np.pi * X).ravel() + rng.normal(0, 0.2, 40)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=1)

for d in (1, 4, 15):
    m = make_pipeline(PolynomialFeatures(d), LinearRegression()).fit(X_tr, y_tr)
    tr = mean_squared_error(y_tr, m.predict(X_tr)) ** 0.5
    te = mean_squared_error(y_te, m.predict(X_te)) ** 0.5
    print(f"degree {d:>2}: train RMSE {tr:.2f} | test RMSE {te:.2f}")

Output from one run:

Model

Train error (RMSE)

Test error (RMSE)

Degree 1 (straight line)

0.54

0.60

Degree 4

0.18

0.25

Degree 15

0.16

0.36

The straight line underfits: both errors are high. Degree 4 fits well. Degree 15 has the lowest training error, yet its test error climbs back up, the signature of overfitting. These figures are illustrative and will shift with different random data.

How to Detect Overfitting and Underfitting

Detection starts with keeping data separate. The model learns from a training set, is tuned on a validation set and is judged once on a test set it has never seen; this split is explained in the guide to the difference between training and testing data.

Three checks do most of the work:

  1. Compare scores: Training accuracy far above validation accuracy suggests overfitting. Both suggest underfitting.
  2. Read a learning curve: Plot training and validation error as training data or training time grows. If the two lines stay high and close together, the model is underfitting. If training error keeps falling while validation error flattens or rises, a gap is opening and overfitting is setting in.
  3. Use cross-validation: With limited data, cross-validation rotates which rows act as validation, giving a steadier estimate than one split. This walkthrough of cross-validation in Python shows the code.

Strategies to Avoid Overfitting and Underfitting

1. Strategies to Avoid Overfitting

  • Simplify the model: Fewer layers, shallower trees or fewer features.
  • Regularisation: L1 (lasso) and L2 (ridge) add a penalty for large weights, nudging the model toward simpler patterns.
  • More training data: Extra varied examples make noise harder to memorise.
  • Early stopping: Halt training when validation error stops improving.
  • Dropout (neural networks): Randomly switch off a share of units during training so the network cannot lean on any single path.
  • Clean inputs: Careful data preprocessing removes duplicates and leaks that make memorising easier.

2. Strategies to Avoid Underfitting

  • Use a richer model: Move from linear to polynomial terms, or from a shallow to a deeper tree.
  • Add better features: Location and age for house prices, not just area.
  • Reduce regularisation: A penalty that is too strong can flatten useful patterns.
  • Train longer: Some models simply need more passes over the data.

3. Balancing Both Issues

Fixes for one problem can cause the other. Cutting complexity to stop overfitting may push a model into underfitting, and the reverse is also true. The practical approach is to change one setting at a time and let validation results decide, rather than relying on training scores.

Learning to tune models against validation data is central to applied ML work. IIITB's Executive Diploma programme in Data Science & Artificial Intelligence builds these skills through hands-on projects in model building, evaluation and deployment.

Common Use-Cases and Real-World Scenarios

The scenarios below are illustrations of how each problem tends to show up, not reports on specific systems.

Scenario

How underfitting looks

How overfitting looks

Image classification

Simple model confuses cats and dogs in most photos

Model learns the studio background of training photos and fails on outdoor shots

Sentiment analysis

Counting a few positive words misses sarcasm and negation

Model latches onto rare words that appeared only in training reviews

Stock price prediction

A flat trend line ignores recent moves

Model traces past price noise and fails next quarter

Fraud detection

Rules too broad to catch new fraud patterns

Model flags harmless habits that happened to coincide with past fraud

Housing price prediction

Area-only straight line misprices most homes

Deep tree memorises individual sales and misprices new listings

How Bias and Variance Relate to Model Fit

Two terms explain most fit problems. Bias is the error that comes from wrong or overly simple assumptions; a model with high bias misses the real pattern, which is underfitting. Variance is how much a model's predictions change when it is trained on a different sample of data; a model with high variance chases noise, which is overfitting. The idea of variance in a model is worth reading on its own.

Every model makes assumptions to generalise at all, a property known as inductive bias. Too strong an assumption underfits; too weak an assumption leaves the model free to overfit. As complexity rises, bias usually falls and variance rises, and the best model sits where total error on unseen data is lowest. This is the bias–variance trade-off.

Conclusion

Underfitting and overfitting in machine learning are two sides of one question: does the model's complexity match the problem? A model that underfits needs more capacity or better features; one that overfits needs restraint, more data or regularisation. In my view, the single most useful habit is never to trust a training score on its own. Check every change against data the model has not seen, and the right balance usually becomes clear. Those exploring where these ideas fit in the wider field can start with the main types of ML, and upGrad's free course on the Fundamentals of Deep Learning and Neural Networks is a good next step for hands-on practice.

Not sure which learning path suits your career goals? Talk to upGrad's counsellors and get guidance on programmes that match your background.

Frequently Asked Questions (FAQs)

What is overfitting and underfitting in machine learning?

Think of them as two opposite misses. An overfit model has soaked up its training examples, quirks and all, so it shines there and slips on anything new. An underfit model never got the pattern in the first place, so its errors stay high even on data it trained on. The goal is the middle ground: a model that copes with fresh inputs. 

How can you identify overfitting and underfitting in machine learning?

Put two numbers side by side: the score on training data and the score on a validation set the model never saw. Training at 98% and validation at 75%? That gap says overfitting. Both stuck near 60%? The model is underfitting. A learning curve shows how the gap moves, and cross-validation stops one lucky split from fooling you.

What is an example of overfitting in machine learning?

A decision tree grown until every leaf holds one training example can score close to 100% on training data. On new data, its accuracy drops sharply because it has memorised quirks of individual rows, such as one unusual customer, rather than general rules.

What is an example of underfitting in machine learning?

Take mileage and speed. A car uses fuel most efficiently at moderate speeds and burns more at both crawl and highway pace, so the real curve bends. Fit a straight line to that data and it can only slope one way. It gets the training cars wrong and the new ones wrong too, and more training will not fix it.

What is the difference between overfitting and underfitting in machine learning?

Overfitting means the model is too complex: low training error, high error on new data. Underfitting means it is too simple: high error on both. The first is linked to high variance and the second to high bias, and they call for opposite fixes.

How do you detect overfitting using validation sets?

Hold back a validation set that the model does not train on, then track its error alongside training error. If training error keeps falling while validation error stalls or rises, the model has started to overfit. Early stopping uses this exact signal to end training.

What is the bias-variance trade-off?

It describes the tension between two sources of error. Simple models have high bias and underfit; complex models have high variance and overfit. Increasing complexity lowers bias but raises variance, so the aim is the level of complexity that gives the lowest error on unseen data.

What does a good fit look like in machine learning?

A good fit captures the real pattern without chasing noise. Training and validation errors are both reasonably low and close to each other. What counts as "low" depends on the problem and the data, so there is no universal threshold; comparisons against a sensible baseline help.

Can a model move from underfitting to overfitting during training?

Yes. Early in training, a model often underfits because it has not learned enough. As training continues, it improves, then may begin memorising noise. Tracking training and validation performance together shows when that turn happens, which is why validation checks matter more than training scores.

Speak with AI & ML expert

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive Program in Generative AI for Leaders

76%

seats filled

View Program

Top Resources

Recommended Programs

LJMU

Liverpool John Moores University

Master of Science in Machine Learning & AI

Double Credentials

Master's Degree

18 Months

IIITB
bestseller

IIIT Bangalore

Executive Diploma in Machine Learning and AI

360° Career Support

Executive Diploma

12 Months

IIITB

IIIT Bangalore

Executive Programme in Generative AI & Agentic AI for Leaders

India’s #1 Tech University

Dual Certification

5 Months