Sub topic 13
Overfitting and when plain OLS struggles
This chapter assumes you can fit a LinearRegression, split data with train_test_split, and read R-squared on a test set from earlier chapters.
What overfitting means
A model overfits when it learns noise in the training data as if it were signal. The training error looks excellent, but predictions on new rows are poor. The gap between training and test scores is the symptom to watch.
Ordinary least squares (OLS) has no built-in limit on how closely it follows the training data. It picks the coefficients that minimize training squared error, and nothing more. Each extra feature gives it another coefficient to adjust, so it can fit noise more easily.
Seeing the gap
The code below builds 40 rows with 30 candidate features. Only the first two features affect y. It then fits OLS on the first 2, 5, 10, 20 and 29 features and compares the train and test R-squared.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n_samples = 40
X_all = rng.normal(size=(n_samples, 30))
y = 3.0 * X_all[:, 0] - 2.0 * X_all[:, 1] + rng.normal(0, 1.0, size=n_samples)
print("features train R2 test R2")
for n_features in [2, 5, 10, 20, 29]:
X = X_all[:, :n_features]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression().fit(X_train, y_train)
print(
f"{n_features:>8} {model.score(X_train, y_train):8.3f}"
f" {model.score(X_test, y_test):7.3f}"
)Training R-squared never falls as you add features, and with 29 features it reaches 1.0. The training set has 30 rows, and the model has 29 coefficients plus an intercept, so it can pass through every training point. Test R-squared drops, and it can go below zero. A negative value means the model predicts worse than always guessing the mean of y.
When plain OLS struggles
OLS is most likely to overfit in these situations:
- Few rows per feature. A common rule of thumb is to want many times more rows than features. At or below one row per coefficient, the fit is exact and meaningless.
- Noisy targets. More noise gives the model more to memorize.
- Many irrelevant features. Each one adds variance to the predictions without adding signal.
- Flexible derived features. High-degree polynomial terms, covered later, add coefficients quickly.
The cause is variance. If you refit on a different sample, the coefficients change a lot, and so do the predictions. This is the variance side of the bias-variance trade-off. OLS has low bias when the true relationship is linear, but its variance grows with the number of features.
What to do about it
- Compare train and test scores every time. A high training score alone tells you little.
- Use cross-validation so one lucky or unlucky split does not mislead you.
- Remove features that carry no signal, or collect more rows.
- Constrain the coefficients. Regularization, covered in a later chapter, adds a penalty that stops OLS from using large coefficients to chase noise.
Exercise
A model trained on 50 rows and 60 features reports a training R-squared of 1.0 and a test R-squared of 0.1. Why is the training score so high, and what does it tell you?
Show answer
With more features than rows, OLS has enough coefficients to fit every training point exactly, so training R-squared reaches 1.0 whatever the signal. The score says nothing about generalization. The low test R-squared is the real evidence of overfitting.