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 and RMSE. It also assumes you know what coef_ means. Here you will see how an ordinary least squares (OLS) model can fit its training data very well and still predict new data badly. You will also learn which situations cause this.
What overfitting means
A model overfits when it learns noise in the training sample as if it were signal. Noise is the random part of the target that no feature explains. A model that has memorized noise scores well on the data it saw and poorly on data it did not see.
The practical symptom is a gap between training and test scores:
- Training R-squared is high, and test R-squared is much lower, or even negative.
- Training RMSE is small, and test RMSE is large.
A negative test R-squared means the model predicts worse than a constant guess equal to the training mean.
Why OLS can overfit
OLS picks the coefficients that minimize squared error on the training rows. Nothing in that objective penalizes large or unnecessary coefficients. Every added feature can only lower (or keep equal) the training error, even if the feature is pure noise. Training error therefore always looks better as you add columns, while test error eventually gets worse.
The cause is variance. If you drew a different training sample from the same population, an overfit model would produce noticeably different coefficients and different predictions. For OLS, the variance of the coefficient estimates depends on the matrix X^T X, which is inverted in the solution. When there are few rows per feature, or when columns are nearly copies of each other, that matrix is close to singular. Its inverse then has very large entries, and small changes in the data move the coefficients a lot.
Seeing it happen
The script below builds data where only the first three of 70 features matter. The rest are noise. It then fits OLS using the first k features, for increasing k.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
def make_data(rng, n, p):
X = rng.normal(size=(n, p))
y = X[:, :3] @ np.array([3.0, -2.0, 1.5]) + rng.normal(0, 2.0, size=n)
return X, y
rng = np.random.default_rng(0)
X, y = make_data(rng, 100, 70)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.4, random_state=0
)
for k in [3, 10, 20, 40, 59]:
model = LinearRegression().fit(X_train[:, :k], y_train)
train_r2 = r2_score(y_train, model.predict(X_train[:, :k]))
test_r2 = r2_score(y_test, model.predict(X_test[:, :k]))
print(f"k={k:2d} train R2={train_r2:6.3f} test R2={test_r2:7.3f}")Expect training R-squared to rise with k and approach 1.0 at k=59. There the model has 60 parameters (59 coefficients plus the intercept) for 60 training rows, so it can pass through every point. Test R-squared should peak near k=3 and then decline. At k=59 it is typically far below zero. Exact numbers depend on the random draw, but the pattern does not.
Measuring variance directly
You can measure the variance by refitting on many fresh training samples and watching how much one coefficient moves. The true coefficient of the first feature is 3.0.
import numpy as np
from sklearn.linear_model import LinearRegression
def make_data(rng, n, p):
X = rng.normal(size=(n, p))
y = X[:, :3] @ np.array([3.0, -2.0, 1.5]) + rng.normal(0, 2.0, size=n)
return X, y
rng = np.random.default_rng(1)
for k in (3, 55):
first_coefs = []
for _ in range(200):
X, y = make_data(rng, 60, 70)
model = LinearRegression().fit(X[:, :k], y)
first_coefs.append(model.coef_[0])
print(f"k={k:2d} mean={np.mean(first_coefs):.2f} std={np.std(first_coefs):.2f}")Both settings average close to 3.0, so OLS is unbiased in both cases. The spread is very different. With 55 features and 60 rows, the standard deviation is several times larger than with 3 features. An individual fit can land far from the truth even though the average is right. That is variance, and it is why a single overfit model cannot be trusted.
When plain OLS struggles
| Situation | What goes wrong | How you notice |
|---|---|---|
| Many features compared with rows | Coefficients chase noise | Large train/test gap, negative test R-squared |
| Features at least as many as rows (`p >= n`) | `X^T X` is singular, so there are infinitely many perfect fits | Train R-squared near 1.0, `model.rank_` below the number of columns |
| Highly correlated features | Coefficients become unstable and can flip sign | Coefficients change greatly between folds or resamples |
| High-degree polynomial terms | Flexible curves wiggle between data points | Excellent training fit, erratic predictions |
| Few rows and heavy noise | Any flexible fit is mostly noise | Large spread of cross-validation scores |
When p >= n, scikit-learn does not raise an error. It uses a least-squares solver that returns the minimum-norm solution among the many perfect fits. You get an answer with no warning, and it is almost always overfit. You can check the numerical rank of the design matrix through the fitted attributes rank_ and singular_.
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(2)
X = rng.normal(size=(30, 40))
y = rng.normal(size=30)
model = LinearRegression().fit(X, y)
print("columns:", X.shape[1], "rank:", model.rank_)
print("train R2:", model.score(X, y))The target here is pure noise, yet the training R-squared is essentially 1.0. The rank is at most 30, the number of rows, which is less than the 40 columns. A perfect training score on random targets shows that the score reflects the model's capacity and not any real signal.
Detecting overfitting in practice
- Always compare training and test scores. A single test score tells you little. The gap tells you whether the model is memorizing.
- Use cross-validation for a steadier estimate. A large standard deviation across folds is itself a warning about variance.
- Compare the number of parameters with the number of training rows. A rough rule is to be suspicious when you have fewer than about 10 rows per feature, though noisy targets need more.
- Check how much the coefficients change between folds or resamples.
What to do about it
You have several options, in rough order of effort:
- Collect more rows, which reduces variance directly.
- Remove features that carry no signal, using domain knowledge.
- Replace correlated columns with one summary column.
- Add a penalty on coefficient size, which is what Ridge, Lasso and ElasticNet do.
- Lower the flexibility of added terms, for example a smaller polynomial degree.
The next chapters cover correlated features and the penalized models in detail. The rule to carry forward is that a better training score is never evidence of a better model. Only held-out data can show that.
Exercise
You fit LinearRegression on 50 rows and 80 features. Training R-squared is 1.000 and test R-squared is -0.8. Name two things that explain this, and one check you could run on the fitted model.
Show answer
There are more features than rows (p >= n), so X^T X is singular and many coefficient sets fit the training data perfectly. The solver returns one of them, which has memorized noise and therefore predicts badly on new data. A negative test R-squared means it does worse than predicting the training mean. A check is to read model.rank_, which will be at most 50 and so below the 80 columns. You could also compare train and test scores across cross-validation folds.
Exercise
In the variance experiment, the mean of the first coefficient was close to 3.0 for both k=3 and k=55, but the standard deviation was much larger for k=55. Does this mean OLS with 55 features is a good estimator? Explain.
Show answer
No. The near-3.0 mean shows OLS is unbiased, meaning it is right on average over many samples. In practice you have one sample, and with 55 features and 60 rows a single fit can be far from 3.0 because the variance is large. Low bias does not help if the individual estimate is unreliable.