Sub topic 9
Generalization, Overfitting, and Underfitting
This chapter assumes you know what a supervised model is, what features and labels are, and how a loss function drives training. You should be able to read short scikit-learn scripts. Here you will learn why a model that scores well on its training data can still fail in use, and how to detect and fix that failure.
Generalization is the real goal
A model is trained on a finite sample of examples, but you deploy it on examples it has never seen. Generalization is how well the model's performance on the training data carries over to new data drawn from the same source.
Training loss alone cannot measure this. A model can reduce training loss by learning real structure, or by memorizing the particular examples it was given, including their noise. Both look identical on the training set. They differ only on new data.
Two assumptions sit behind this idea:
- The training and future examples come from the same distribution. If they do not, for example because customers change their behavior, even a well-generalizing model degrades.
- The examples are independent enough that a test sample is a fair stand-in for the future. Duplicated rows or several rows from the same patient split across training and test sets break this.
Two ways to fail
Every example's label can be thought of as signal plus noise. Signal is the repeatable relationship between features and label. Noise is everything else: measurement error, missing factors, and randomness.
Underfitting happens when the model is too simple or too constrained to capture the signal. It performs poorly on both the training set and the test set. A straight line fitted to data that follows a curve is the standard case.
Overfitting happens when the model is flexible enough to fit the noise as well as the signal. It performs very well on the training set and noticeably worse on the test set. The size of the gap is the symptom.
| Symptom | Training score | Test score | Likely cause |
|---|---|---|---|
| Underfitting (high bias) | Low | Low, close to training | Model too simple, too few features, too much regularization |
| Good fit | High | High, slightly below training | Model complexity matches the signal |
| Overfitting (high variance) | Very high | Clearly lower | Model too flexible, too little data, too many features |
"Bias" and "variance" are the statistical names for these failures. A high-bias model makes systematic errors because its assumptions are too rigid. A high-variance model changes a lot if you retrain it on a different sample, because it follows that sample's noise.
Complexity and the error curve
As you make a model more flexible, training error almost always keeps falling. Test error falls at first, then bottoms out and rises. The best model sits near the minimum of the test curve.
Complexity can mean different things depending on the model: tree depth, polynomial degree, number of neurons, number of features, or number of training iterations. The shape of the curve is the same in each case.
Seeing it with a decision tree
The tree example below compares a depth-1 tree (a single yes/no split) with an unrestricted tree on the iris data. It prints the depth, the training accuracy, and the test accuracy.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
for depth in (1, None):
tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
tree.fit(X_train, y_train)
print(depth, tree.score(X_train, y_train), tree.score(X_test, y_test))A single split can separate at most two of the three species cleanly, so the depth-1 tree scores about 0.67 on both sets. That is underfitting: training accuracy is itself low. The unrestricted tree keeps splitting until every training example is classified correctly, so its training accuracy is 1.0. Its test accuracy is usually a little lower.
Iris is small and easy, so the gap is modest. On noisier data the same pattern produces a much larger gap. Do not conclude that deep trees are harmless from this example alone.
A clearer demonstration with polynomial regression
Regression makes the effect easy to see because you can vary complexity with one number, the polynomial degree. The script below fits noisy samples of a sine curve with three degrees and reports mean squared error on each split.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
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 = rng.uniform(0, 1, size=(40, 1))
y = np.sin(2 * np.pi * X[:, 0]) + 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_mse = mean_squared_error(y_train, model.predict(X_train))
test_mse = mean_squared_error(y_test, model.predict(X_test))
print(degree, round(train_mse, 3), round(test_mse, 3))Expect the following pattern:
- Degree 1 is a straight line. Both errors are high and similar.
- Degree 4 follows the sine shape. Both errors are near the noise level, which is about 0.04 for a standard deviation of 0.2.
- Degree 15 has 16 coefficients and only 20 training points. Training error is very small, but test error is much larger.
The exact numbers depend on the random seed and the split, so check the pattern rather than the digits.
Why a held-out test set is required
If you evaluate on the data you trained on, an overfit model looks excellent. You need examples that played no part in fitting. The common arrangement has three parts:
- Training set: used to fit the parameters.
- Validation set: used to compare models and choose hyperparameters such as tree depth or polynomial degree.
- Test set: used once, at the end, to report the final performance.
The validation set exists because choosing among many configurations by looking at test scores quietly overfits the test set too. After enough comparisons, the test score is no longer an honest estimate. When data is scarce, cross-validation replaces a single validation split. It divides the training data into k folds, trains on k−1 of them, validates on the remaining one, and averages the k scores.
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
for depth in (1, 2, 3, None):
tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
scores = cross_val_score(tree, X, y, cv=5)
print(depth, scores.mean().round(3), scores.std().round(3))Pick the setting with the best mean cross-validation score. Then evaluate once on a separate test set. The standard deviation tells you how much the score depends on the split. If two settings differ by less than that spread, you cannot reliably tell them apart.
Diagnosing which problem you have
Compare the training score, the validation score, and the gap between them.
- Both scores are poor: underfitting. Add features, use a more flexible model, or reduce regularization.
- Training score is high and validation score is much lower: overfitting. Use the fixes in the next section.
- Both are good and close: the model generalizes. Check that the score meets your requirement.
A learning curve adds one more diagnostic. It plots training and validation scores against the number of training examples. If the two curves have converged at a poor score, more data will not help, and you need a more expressive model or better features. If a large gap remains between them, more data is likely to help.
Reducing overfitting
No single fix works everywhere. Common options:
- Get more data. This is often the most effective remedy, because noise averages out and memorization becomes harder.
- Simplify the model. Limit tree depth, lower the polynomial degree, or remove features.
- Regularize. Add a penalty on large parameter values to the loss. Ridge regression penalizes the sum of squared coefficients, and in
LogisticRegressiona smallerCmeans stronger regularization. - Stop early. For iterative training, halt when validation loss stops improving.
- Use ensembles. Averaging many trees, as in a random forest, reduces variance.
Reducing underfitting
- Use a more flexible model family.
- Add informative features or interaction terms.
- Lower the regularization strength.
- Train longer, if training has not converged.
Increasing complexity to fix underfitting can push you into overfitting, so re-check the validation score after every change.
Common mistakes
Other frequent errors:
- Random splits on time-ordered data. If the model must predict the future, test on later dates than the training data, not on a random sample.
- Ignoring class imbalance. A model that always predicts the majority class can have high accuracy and no skill. Use
stratify=ywhen splitting and choose metrics suited to the task. - Tuning on the test set. Repeated peeking turns the test set into a second validation set.
- Reading a single split as truth. On small datasets, one split can be lucky. Repeat or cross-validate.
Exercise
A classifier gets 99% accuracy on its training data and 71% on a validation set. Name the problem, and give two changes you could try, plus the one measurement you would repeat afterward.
Show answer
The model is overfitting: the large gap between training and validation scores shows it has fit noise or memorized examples. Two changes are to add regularization (or reduce model complexity, such as limiting tree depth) and to collect more training data. Afterward, re-measure the validation score (ideally with cross-validation) to confirm the gap has shrunk, without touching the test set.
Exercise
A regression model has a high error on both the training set and the validation set, and a learning curve shows the two errors have converged at the same high value. Will adding more training examples help? What should you try instead?
Show answer
No. Converged curves at a poor score indicate underfitting (high bias), so more data of the same kind will not fix it. Try a more flexible model, add informative features, or reduce regularization, then recheck the validation error.