Sub topic 2
Underfitting and overfitting
This chapter assumes you know the basics of supervised learning (features, labels, train and test splits) and have used scikit-learn estimators with fit, predict and score. It also assumes you can read short NumPy code. The previous chapter compared training and validation scores. This chapter explains what the two scores reveal about a model's fit.
What the two terms mean
A model is trained to do well on data it has seen. We care about data it has not seen. Two failures can separate those goals.
- Underfitting means the model is too limited to capture the real pattern. It scores poorly on the training data, and it scores poorly on new data too.
- Overfitting means the model has captured noise and quirks of the training sample as if they were pattern. It scores very well on the training data and noticeably worse on new data.
The pattern comes from the data-generating process. The noise is the part of each label that no function of your features can predict. An underfit model misses the pattern. An overfit model learns the pattern and also memorizes noise that will not repeat.
Reading the symptoms from scores
You can't see fit directly. You see two numbers, a training score and a validation score, and you compare them to each other and to what you consider a good result.
| Situation | Training score | Validation score | Gap |
|---|---|---|---|
| Underfitting | Low | Low | Small |
| Good fit | High | High, close to training | Small |
| Overfitting | Very high | Clearly lower | Large |
Two cautions apply to this table.
- "Low" and "high" depend on the task. An accuracy of 0.70 is low on handwritten digits and may be excellent on a task with noisy labels. You need a reference, such as a simple baseline, a human error rate, or a known ceiling from the problem.
- A small gap does not prove a good fit. An underfit model has a small gap because both scores are bad. Looking at the gap alone is a common mistake.
Why complexity drives the pattern
Model flexibility is the main lever. A flexible model can bend to follow many shapes. A rigid model can follow only a few. Examples of flexibility in common estimators:
- the degree of a polynomial feature expansion
- the depth of a decision tree
- the number of neighbors in k-nearest neighbors (fewer neighbors means more flexibility)
- the inverse regularization strength
Cin logistic regression or SVMs (largerCmeans more flexibility) - the width and depth of a neural network
As flexibility rises, training error falls almost without exception, because the model has more freedom to fit each training point. Validation error usually falls at first, then flattens, then rises once the model starts fitting noise. The sweet spot is near the lowest validation error. Validation curves, covered later in this tutorial, plot exactly this relationship.
Flexibility is not the only cause. The amount of data matters too. A model that overfits on 50 samples may fit well on 5,000, because more samples make it harder to memorize noise and easier to average it out. Learning curves, also covered later, plot that relationship. For now, keep both levers in mind: model flexibility and training set size.
A worked example
The following script fits polynomials of three degrees to noisy samples from a sine curve. It reports the R² score on a training half and a held-out half. For regression, score returns R², where 1.0 is perfect and values near 0 mean the model does no better than predicting the mean.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
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, size=40)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0
)
for degree in (1, 4, 15):
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
model.fit(X_train, y_train)
train_r2 = model.score(X_train, y_train)
test_r2 = model.score(X_test, y_test)
print(f"degree={degree:2d} train R2={train_r2:.3f} test R2={test_r2:.3f}")Run it and compare the three lines. The numbers depend on the random seed, but the usual pattern is:
- Degree 1 is a straight line. It can't follow a sine wave, so both scores are mediocre and close together. This is underfitting.
- Degree 4 can follow one full wave. Both scores are high and close. This is a reasonable fit.
- Degree 15 has 16 parameters and only 20 training points. Its training score is the highest of the three, but its test score is lower than degree 4's, and can even turn negative. This is overfitting.
Notice that training R² rises with every step in degree. If you had picked the degree by training score, you would have picked the worst model. That is the main reason to evaluate on data the model has not seen.
The test set is a single noisy estimate
The example above uses one split with 20 held-out points. That is a small sample, and the test score carries its own noise. A different split could change the numbers noticeably, and the ranking of two close models could flip. This does not undermine the idea, but it limits how far you can trust a single comparison.
Two consequences follow:
- Differences of a few hundredths in a score often mean nothing. Only large patterns, such as a big gap or a clear trend, are reliable.
- To get a steadier estimate, average over several splits. That is what cross-validation does, and the next chapters build on it. The curves in this tutorial are all computed from cross-validated scores for this reason.
Edge cases and common confusions
A large gap with a low training score is not typical overfitting. If training is mediocre and validation is worse, check for a problem in how you split or preprocess the data before changing the model. Distribution shift between the two sets can cause it.
Validation above training happens. It is usually a sign of a small or unrepresentative validation fold, regularization such as dropout that is active only during training, or a score computed on different data conditions. A tiny negative gap is noise. A large one deserves investigation.
Perfect training scores are not always a problem. A deep unpruned decision tree or a 1-nearest-neighbor classifier reaches 100% training accuracy by construction. What matters is whether the validation score is also good. A random forest often has near-perfect training accuracy and still generalizes well.
Overfitting is relative to the data you have. A model can overfit with respect to 100 samples and be well matched to 100,000. The same model is not "an overfitting model" in general. The diagnosis applies to a model, a dataset size, and a metric together.
Overfitting to the validation set is also possible. If you try many models or hyperparameters and keep the one with the best validation score, that winning score is slightly optimistic, because you selected it for being high. A final, untouched test set gives an unbiased check. The tuning workflow chapter returns to this.
A quick decision flow
When you have both scores, ask the questions in this order.
This flow gives a first reading, not a verdict. It uses one pair of numbers from one configuration. Learning curves and validation curves give you many pairs, so you can see how the situation changes when you add data or change flexibility. Later chapters use them to choose between remedies such as more data, a simpler model, or more regularization.
Summary of the key ideas
- Underfitting shows as low training and low validation scores with a small gap.
- Overfitting shows as a high training score and a clearly lower validation score.
- Flexibility and training set size are the two main levers. More flexibility raises the risk of overfitting, and more data lowers it.
- A single split gives a noisy estimate, so trust large patterns and not small differences.
- Judge "high" and "low" against a baseline or known ceiling for the task.
Exercise
You fit a decision tree with no depth limit on a classification task. It reaches a training accuracy of 1.00 and a validation accuracy of 0.78. A colleague fits a depth-2 tree and gets 0.74 on training and 0.72 on validation. Which model overfits, which underfits (if either), and what is the one comparison you would make before choosing between them?
Show answer
The unlimited tree overfits: its training score is perfect, and its validation score is 0.22 lower. The depth-2 tree may underfit mildly, since its training score is low, but its small gap (0.02) shows it is stable. To choose, compare the validation scores, because that is the estimate of performance on unseen data. The unlimited tree has the higher validation accuracy (0.78 against 0.72), so on this one comparison it is still the better predictor, despite overfitting. Before trusting that difference, repeat the evaluation with cross-validation, since a single split is noisy. A tree of intermediate depth would likely beat both.
Exercise
In the polynomial example, the degree-15 model has a higher training score than the degree-4 model. Why is training score a poor way to choose the degree?
Show answer
Training score rises with flexibility almost always, because a more flexible model can fit the training points, noise included, more closely. Choosing by training score would always pick the most flexible model. The held-out score measures performance on data not used for fitting, so it reveals where extra flexibility stops helping and starts fitting noise.