Module 4 · Beginner · How models learn and why they fail

Project: diagnose and fix an overfitting model

An overfitting project in Python: diagnose a house price model that fails on test data, then fix it with regularisation, better features and cross-validation.

By theprogrammers team · · 19 min read

A model that scores well in training and badly in testing is the most common problem in machine learning. Reading about overfitting is one thing. Spotting it in your own work, finding the cause and fixing it with evidence is another.

You'll build a house price model that looks better and better on training data while getting worse, then fails spectacularly on the test set. You'll diagnose why with numbers and pictures, try three fixes from this module (simpler models, regularisation and better features), compare them fairly with cross-validation, and test the winner once. Along the way you'll find that the cause is not quite what the textbook diagnosis suggests.

What you need first: the lessons of this module, especially overfitting and underfitting, regularisation explained, cross-validation explained and baseline models. Feature engineering basics helps with fix 3.

Key terms

  • Overfitting: a model fits the training data closely, including its noise and quirks, and does worse on new data.
  • Generalisation gap: the difference between the training error and the test (or validation) error. A big gap is the main sign of overfitting.
  • Polynomial features: new columns made by multiplying features together and raising them to powers, such as income², income × age. They let a linear model fit curves.
  • Extrapolation: predicting for inputs outside the range seen in training. Flexible models can behave wildly there.
  • Ridge regression: linear regression with an L2 penalty that keeps weights small; alpha sets how strong the penalty is.

1. The problem and the metric

A property website shows an estimated typical house value for every district in California, from census data. Buyers use it to judge whether asking prices are reasonable.

  • Who's affected by mistakes: buyers and sellers. An estimate that's far too low or too high misleads them, and a wildly wrong one (say, $3 million for an ordinary district) destroys trust in the whole site.
  • Metric: MAE in dollars, chosen before modelling, because users read the error as "how many dollars off", and every dollar of error matters about equally. We'll also watch the largest errors, because a few absurd estimates are a real problem for a public website even if the average looks fine.

Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("california-housing.csv").

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
print(X_train.shape, X_test.shape)

def dollars(error):
    return f"${error * 100_000:,.0f}"     # house values are in units of $100,000
(16512, 8) (4128, 8)

The test set (20%) is now locked away until step 7. All decisions use the training set, with cross-validation.

2. Explore: how are the features spread?

Overfitting often comes from the data, not only the model, so look first:

print(X_train.describe().loc[["50%", "max"]].T.round(1))
               50%      max
MedInc         3.5     15.0
HouseAge      29.0     52.0
AveRooms       5.2    141.9
AveBedrms      1.0     34.1
Population  1166.0  35682.0
AveOccup       2.8    599.7
Latitude      34.2     42.0
Longitude   -118.5   -114.3

Most columns look ordinary at the median, but the maximums are extreme. A typical district has 5.2 rooms per household; the largest has 141.9. A typical household has 2.8 people; one district averages 599.7. These are probably hostels, care homes, camps or data errors. Keep them in mind.

3. Baseline and a first model

From baseline models: for MAE, the strongest dummy predicts the median for everyone.

from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

baseline = DummyRegressor(strategy="median").fit(X_train, y_train)
linear = LinearRegression().fit(X_train, y_train)
print("baseline test MAE:", dollars(mean_absolute_error(y_test, baseline.predict(X_test))))
print("linear   train MAE:", dollars(mean_absolute_error(y_train, linear.predict(X_train))))
baseline test MAE: $87,546
linear   train MAE: $53,087

(Notice we checked the baseline on the test set, but only the training error of the linear model. The baseline makes no decisions, so looking at its test score costs nothing. Every model we choose between must be judged without the test set.)

A straight-line model is probably too simple: house values curve with income and location. The obvious next step is to let the model bend.

4. Make it more flexible, and watch it break

PolynomialFeatures(degree=3) creates every product of up to three features: income², income × latitude, rooms × occupancy × age, and so on. Linear regression on those columns can fit curves. Scaling comes after, because squared and cubed values have huge ranges. Everything goes in one pipeline, so cross-validation refits each step on its own training folds, as cross-validation explained requires:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

def polynomial_model(degree, final_step=None):
    return make_pipeline(PolynomialFeatures(degree, include_bias=False),
                         StandardScaler(),
                         final_step if final_step is not None else LinearRegression())

cubic = polynomial_model(3).fit(X_train, y_train)
print("columns after PolynomialFeatures:", cubic[0].n_output_features_)
print("cubic train MAE:", dollars(mean_absolute_error(y_train, cubic.predict(X_train))))
columns after PolynomialFeatures: 164
cubic train MAE: $41,851

include_bias=False stops it adding a column of 1s, because LinearRegression already fits an intercept. From 8 features to 164, and the training error falls nicely. If you stopped here, you'd think you had a much better model.

Predict: will cross-validation agree? Run 5-fold cross-validation on the training set, for degrees 1 to 4, and record both the training and validation error in each round:

from sklearn.model_selection import KFold, cross_validate

folds = KFold(n_splits=5, shuffle=True, random_state=0)

def cv_mae(model, data=None):
    """Mean training and validation MAE over the 5 folds, plus the spread of validation MAE."""
    data = X_train if data is None else data
    result = cross_validate(model, data, y_train, cv=folds,
                            scoring="neg_mean_absolute_error", return_train_score=True)
    return -result["train_score"].mean(), -result["test_score"].mean(), result["test_score"].std()

for degree in [1, 2, 3, 4]:
    train_err, val_err, spread = cv_mae(polynomial_model(degree))
    print(f"degree {degree}: train MAE {dollars(train_err):>9}   validation MAE {dollars(val_err):>14}")
degree 1: train MAE   $53,063   validation MAE        $53,166
degree 2: train MAE   $46,024   validation MAE        $50,025
degree 3: train MAE   $41,656   validation MAE       $260,772
degree 4: train MAE   $37,252   validation MAE   $166,383,975

cross_validate is like cross_val_score but can return training scores too (return_train_score=True). Scikit-learn's scorers treat "higher is better", so MAE comes back negative (neg_mean_absolute_error), and the minus sign flips it back.

There it is. Training error falls steadily with the degree. Validation error falls at degree 2, then explodes. The textbook picture of overfitting:

degrees = [1, 2, 3, 4]
results = [cv_mae(polynomial_model(d)) for d in degrees]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(degrees, [r[0] * 100_000 for r in results], "o-", color="#0f766e", label="Training MAE")
ax.plot(degrees, [r[1] * 100_000 for r in results], "o-", color="#c2410c", label="Validation MAE")
ax.set_yscale("log")
ax.set_xticks(degrees)
ax.set_xlabel("Polynomial degree (model flexibility)")
ax.set_ylabel("MAE in $ (log scale)")
ax.set_title("Training error keeps falling; validation error explodes")
ax.legend()
plt.show()
Line chart of mean absolute error in dollars, on a log scale, against polynomial degree 1 to 4, from 5-fold cross-validation. The green training line falls steadily from about $53,000 at degree 1 to under $40,000 at degree 4. The orange validation line starts level with it, dips slightly to about $50,000 at degree 2, then rises to about $260,000 at degree 3 and about $166 million at degree 4, thousands of times above the training line.

The y-axis is a log scale (set_yscale("log")): each step up is 10 times bigger. Without it, the degree-4 point would squash every other point flat against the bottom.

5. Diagnose: what exactly is going wrong?

The textbook diagnosis is "too complex, it memorised noise". Look at the actual errors before believing it. Take the cubic model, predict each training fold's held-out rows, and look at the typical error as well as the worst:

from sklearn.model_selection import cross_val_predict

held_out = cross_val_predict(polynomial_model(3), X_train, y_train, cv=folds)
errors = (held_out - y_train).abs()
print("median error:", dollars(errors.median()))
print("mean error:  ", dollars(errors.mean()))
print("5 worst errors:", [dollars(e) for e in errors.nlargest(5)])
median error: $30,820
mean error:   $260,761
5 worst errors: ['$2,745,857,118', '$670,961,666', '$84,504,296', '$39,898,896', '$23,202,489']

cross_val_predict gives each training row a prediction from the model that didn't see it during its fold. That's the honest way to inspect validation errors row by row.

This is the key finding. The median error is about $30,000, better than the linear model's mean error. For a typical district, the cubic model is good. The mean is ruined by a handful of absurd predictions, millions or even billions of dollars off. So which districts are they?

worst = errors.nlargest(3).index
print(X_train.loc[worst, ["MedInc", "AveRooms", "AveBedrms", "Population", "AveOccup"]].round(1))
print("predicted:", np.round(held_out[X_train.index.get_indexer(worst)], 1))
print("actual:   ", y_train.loc[worst].round(2).tolist())
       MedInc  AveRooms  AveBedrms  Population  AveOccup
3364      5.5       5.1        1.1      4198.0     599.7
16669     4.3       9.1        1.3      6532.0     502.5
13034     6.1       8.3        1.5      6675.0     230.2
predicted: [-27457.9   6713.1    847.3]
actual:    [0.68, 3.5, 2.25]

get_indexer turns the row labels into positions, so the matching predictions can be picked from the held_out array. The worst rows are the oddballs from step 2: districts averaging 600, 500 and 230 people per household, where a typical district has under 3. Only 3 training districts have more than 100, so when one of them is in the held-out fold, the fold's model has almost nothing like it to learn from. A cubic model multiplies feature values together and cubes them, so a value 100 times bigger than usual can make a term a million times bigger. The model extrapolates wildly: one prediction is −27,458 (in units of $100,000), which means minus $2.7 billion for a district actually worth $68,000.

So the diagnosis is more precise than "too complex": a flexible model plus extreme feature values. That suggests three fixes:

  1. A simpler model (degree 2): less room to blow up, but also less ability to curve.
  2. Regularisation (Ridge): keep the cubic model, but stop any weight from getting large.
  3. Better features: tame the extreme values with logs, so nothing is far outside the usual range.

6. Try the fixes, compared fairly

Every fix is judged by the same 5-fold cross-validation on the training set. First, regularisation. Recall from regularisation explained: Ridge adds alpha × (sum of squared weights) to the loss, so bigger alpha means smaller weights.

from sklearn.linear_model import Ridge

for alpha in [0.1, 1, 10, 100, 1000]:
    train_err, val_err, spread = cv_mae(polynomial_model(3, Ridge(alpha=alpha)))
    print(f"cubic + Ridge(alpha={alpha:<6}): train {dollars(train_err)}   validation {dollars(val_err)} ± {dollars(spread)}")
cubic + Ridge(alpha=0.1   ): train $43,006   validation $55,788 ± $14,129
cubic + Ridge(alpha=1     ): train $44,288   validation $50,768 ± $6,943
cubic + Ridge(alpha=10    ): train $45,712   validation $47,919 ± $2,705
cubic + Ridge(alpha=100   ): train $47,346   validation $48,528 ± $1,178
cubic + Ridge(alpha=1000  ): train $49,826   validation $50,215 ± $870

Regularisation rescues the cubic model. With small alpha, it still overfits, and the ± (the spread across folds) is large: a fold with an oddball does badly. Around alpha=10 the validation error is lowest. With alpha=1000 the penalty is so strong that the model is pushed back towards a straight line, and both errors rise together: that's underfitting.

Now the feature fix. A helper takes logs of the four skewed columns; FunctionTransformer turns it into a pipeline step, so it's applied the same way to every fold and to new data:

from sklearn.preprocessing import FunctionTransformer

def log_skewed(data):
    data = data.copy()
    for column in ["AveRooms", "AveBedrms", "Population", "AveOccup"]:
        data[column] = np.log(data[column])        # all four are always above 0
    return data

def log_model(degree, final_step=None):
    return make_pipeline(FunctionTransformer(log_skewed), polynomial_model(degree, final_step))

for degree in [1, 2, 3]:
    train_err, val_err, spread = cv_mae(log_model(degree))
    print(f"logs + degree {degree}: train {dollars(train_err)}   validation {dollars(val_err)} ± {dollars(spread)}")
for alpha in [1, 10]:
    train_err, val_err, spread = cv_mae(log_model(3, Ridge(alpha=alpha)))
    print(f"logs + degree 3 + Ridge({alpha}): train {dollars(train_err)}   validation {dollars(val_err)} ± {dollars(spread)}")
logs + degree 1: train $48,511   validation $48,569 ± $654
logs + degree 2: train $42,753   validation $43,059 ± $633
logs + degree 3: train $40,162   validation $41,496 ± $1,244
logs + degree 3 + Ridge(1): train $41,425   validation $42,146 ± $967
logs + degree 3 + Ridge(10): train $42,508   validation $42,988 ± $648

The log transform is a step that learns nothing from the data (each row's log uses only that row), so it can't leak. And it's the best fix by a clear margin. Once 599 people per household becomes log(599) ≈ 6.4 instead of 599, the cubic terms can't explode. The training and validation errors are now close together, the sign of a model that generalises. With logs, Ridge makes little difference either way: once the features are tame, there's not much left for the penalty to do.

Experiment: in log_skewed, remove "AveOccup" from the list and rerun the degree 3 line. The validation MAE jumps back to about $291,000: the damage returns, because occupancy has the most extreme values.

Choose the final model

The results, from the cross-validation runs above:

ModelValidation MAE (CV)Why it is or isn't chosen
Median baselineabout $88,000The floor
Linear regressionabout $53,000Underfits: can't curve
Cubic, no fixesenormousOverfits and extrapolates wildly
Cubic + Ridge(10)about $48,000Works, but still hurt by extreme values
Logs + quadraticabout $43,000Good and simple
Logs + cubicabout $41,500Best average
Logs + cubic + Ridge(1)about $42,000Within the fold-to-fold spread of the best

Logs + cubic and logs + cubic + Ridge(1) are within each other's ± spread: a tie. Choose logs + cubic + Ridge(1). Costing almost nothing in validation error, the penalty limits how far any weight can grow, which is cheap insurance against the next unusual district that a public website will certainly meet. When two models tie, prefer the safer one.

7. One final test

Fit the chosen pipeline on the whole training set and score it once on the test set. For comparison, also show what the original cubic model would have reported:

final = log_model(3, Ridge(alpha=1)).fit(X_train, y_train)
final_errors = np.abs(final.predict(X_test) - y_test)
cubic_errors = np.abs(cubic.predict(X_test) - y_test)

print("original cubic: test MAE", dollars(cubic_errors.mean()), "  worst", dollars(cubic_errors.max()))
print("final model:    test MAE", dollars(final_errors.mean()), "  worst", dollars(final_errors.max()))
original cubic: test MAE $970,925   worst $3,830,292,458
final model:    test MAE $42,308   worst $1,594,435

The final model's test MAE is close to its cross-validation estimate, so the estimate was honest. Compared with the original cubic model, the average error is far smaller, and so is the worst. That's the number to report: about $42,000, against $88,000 for the baseline and $53,000 for a straight line.

8. Error analysis: what's left?

Where does the final model still go wrong? Group its test errors by the true value:

bands = pd.cut(y_test, bins=[0, 1, 2, 3, 4, 4.9, 5.01], labels=["<1", "1-2", "2-3", "3-4", "4-4.9", "capped 5"])
print(final_errors.groupby(bands, observed=True).agg(["count", "mean"]).round(2))
             count  mean
MedHouseVal             
<1             736  0.33
1-2           1666  0.36
2-3            976  0.38
3-4            414  0.55
4-4.9          143  0.87
capped 5       193  0.98

pd.cut groups the true values into bands (in $100,000s). The errors grow with the value, and the last band is the worst. That band is special: the census recorded any value above $500,000 as 5.0. A district really worth $900,000 is labelled $500,000, so no model can learn the top end properly. This is a limit of the data, not the model. The honest response is to tell users "over $500,000" for those districts rather than a precise figure.

9. Explain one prediction

A degree-3 model with 164 columns has no simple weights to read. But you can still ask what drives a prediction: take one district, change one feature, and watch the prediction move:

district = X_test.iloc[[0]].copy()          # double brackets keep it a one-row DataFrame
print(district[["MedInc", "HouseAge", "AveOccup", "Latitude", "Longitude"]].round(2))
for income in [2, 4, 6, 8]:
    district["MedInc"] = income
    print(f"median income {income} (×$10,000): predicted value {dollars(final.predict(district)[0])}")
       MedInc  HouseAge  AveOccup  Latitude  Longitude
14740    4.15      22.0      4.18     32.58    -117.05
median income 2 (×$10,000): predicted value $102,109
median income 4 (×$10,000): predicted value $172,966
median income 6 (×$10,000): predicted value $262,975
median income 8 (×$10,000): predicted value $359,936

Holding everything else about this district fixed, raising median income raises the predicted house value, by a different amount at each step: the curve that the polynomial features allow. This "change one thing" check is a simple version of what tools like partial dependence plots and SHAP do, which you'll meet in the "Building reliable models" module.

10. Limitations and harm

  • Capped labels. Values above $500,000 are recorded as $500,000, so the model can't estimate expensive districts.
  • Old data. The data is from the 1990 census. Prices and neighbourhoods have changed completely since then.
  • District averages, not houses. It estimates a district's median, not any one house. Showing it as "your house is worth..." would be misleading.
  • Unusual districts. Districts unlike any in training (very high occupancy, tiny populations) still get less reliable estimates. A website should flag them.
  • Fairness. Values reflect historical patterns, including past discrimination in housing. A model trained on them can repeat those patterns, for example by under-valuing certain neighbourhoods.

11. Save and use it

import joblib

joblib.dump(final, "house_value_model.joblib")
model = joblib.load("house_value_model.joblib")
new_district = pd.DataFrame([{"MedInc": 5.0, "HouseAge": 20, "AveRooms": 5.5, "AveBedrms": 1.05,
                              "Population": 1500, "AveOccup": 2.9, "Latitude": 34.1, "Longitude": -118.3}])
print("estimated value:", dollars(model.predict(new_district)[0]))
estimated value: $242,602

The saved file includes the log step, the polynomial features, the scaler and Ridge, so raw district data goes straight in. (Because log_skewed is your own function, the code that loads the model must also define log_skewed. Put it in a small module both scripts import.)

Take it further

  1. Clip instead of log. Replace log_skewed with a step that caps each of the four columns at its 99th percentile, learned from the training rows. Hint: a custom transformer needs fit to learn the caps; or use np.clip with caps computed from X_train outside the pipeline and say why that's safe. Compare with the log fix.
  2. Learning curve. Train the plain cubic model and the final model on 10%, 25%, 50% and 100% of the training rows, and plot validation MAE against training size. Does more data fix the plain cubic model?
  3. Tune more carefully. Try alpha values of 0.3, 1, 3 and 10 with the log features, and degree 2 against degree 3, using GridSearchCV. Hint: parameter names follow the step names, such as pipeline__ridge__alpha.
  4. Flag unusual districts. Write a function that flags a district whose features fall outside the 1st to 99th percentile of the training data, and count how many test districts it flags. Are their errors larger?
  5. Drop the capped districts. Remove districts with a value of 5.0 from training and testing, retrain, and compare the error on the remaining districts.

Practice

  1. Training MAE keeps falling as the polynomial degree rises. Why doesn't that mean the model keeps improving?
Show the answer

More columns give the model more ways to fit the training rows, including their noise and oddities, so training error almost always falls. What matters is error on rows the model didn't see. Validation error fell from degree 1 to 2 and then exploded, so degrees 3 and 4 were fitting the training data in ways that don't carry over.

  1. The cubic model's median error was about $30,000 but its mean error was huge. What does that tell you, and what would you look at next?
Show the answer

Most predictions are fine, and a few are extremely wrong. Means are dragged by extreme values; medians aren't. Next, look at the rows with the largest errors and their feature values, which is how we found the districts with extreme occupancy and rooms.

  1. Predict: what happens to the cubic + Ridge validation error if you set alpha=100000? Check with cv_mae.
Show the answer
train_err, val_err, spread = cv_mae(polynomial_model(3, Ridge(alpha=100000)))
print(dollars(train_err), dollars(val_err))
$65,356 $65,481

The penalty is so large that the weights are squeezed towards zero, so the model can barely use the features. Training and validation errors are both high and close together: underfitting.

  1. Why can the log_skewed step go inside the pipeline without causing leakage, while a step that clips at the 99th percentile must be fitted on training data only?
Show the answer

log_skewed uses only each row's own values; it learns nothing from other rows, so it behaves the same whatever data it sees. A 99th-percentile cap is learned from many rows. If computed with test rows (or with the held-out fold), information from those rows shapes the training data. It must be learned from the training rows in each fold.

  1. Logs + cubic had a slightly lower CV error than logs + cubic + Ridge(1). Why choose the Ridge version anyway?
Show the answer

The difference was smaller than the fold-to-fold spread, so it's effectively a tie. For a public website, the cost of a rare absurd prediction is high, and Ridge limits how large weights can become, which reduces the risk of extreme predictions on unusual new districts. When two models tie, choose the more stable one.

  1. A teammate suggests fixing the overfitting by checking the test MAE after each change until it's as low as possible. What's wrong with that?
Show the answer

Using the test set to make choices turns it into a validation set. After many checks, the chosen model will look better on the test set than it really is. Make every choice with cross-validation on the training data, and score the test set once at the end.

Interview questions

How do you diagnose overfitting?

Compare training error with validation or cross-validated error. A large gap, where training error is low and validation error much higher, is overfitting. Then look at the worst predictions to find out why: here, extreme feature values that the flexible model extrapolated from.

What are the main ways to fix an overfitting model?

Use a simpler model, add regularisation, get more data, or improve the features, for example by capping or transforming extreme values. Compare each fix with the same cross-validation folds and pick the simplest one that works.

Why compare median error as well as mean error?

A handful of huge errors can dominate the mean. If the median error is reasonable but the mean is enormous, the model works for most rows and fails badly on a few, which points to outliers or extrapolation rather than a generally poor model.

Key takeaways

  • The sign of overfitting is a gap: training error keeps falling while validation error rises.
  • Diagnose before fixing: compare median and mean errors, and look at the worst rows. Here, a flexible model extrapolated wildly on extreme feature values.
  • Three fixes: a simpler model, regularisation, and better features. Better features worked best.
  • Compare every fix with the same cross-validation folds; treat differences smaller than the fold spread as ties.
  • Score the test set once. The final model cut test MAE from absurd to about $42,000, against $88,000 for the baseline.
  • Some errors come from the data itself (capped values), and no model can fix them.

Frequently asked questions

How do I know if my model is overfitting?

Compare training and validation (or cross-validation) errors. If training error is much lower than validation error, and validation error rises as you make the model more complex, it's overfitting. Also look at the worst individual predictions: a few absurd ones are a common symptom.

Is regularisation always the best fix for overfitting?

No. It's one of several. Simpler models, more data, better features and early stopping also help. In this project, fixing the extreme feature values helped more than regularisation, because the root cause was extrapolation on outliers.

Why did the model only fail on a few districts?

Polynomial features multiply and cube feature values. For normal districts this gives sensible curves, but for a district with values far beyond the training range, the cubed terms become enormous, and so does the prediction. Flexible models are most dangerous outside the range of their training data.

What to learn next

  1. Linear regression explained: the next module, and the model you've been using, from the inside.
  2. Hyperparameter tuning: search settings automatically instead of by hand.
  3. Regularisation explained: revisit Ridge and Lasso.