A score such as "mean error 0.31" tells you how wrong a model is on average. It doesn't tell you where it's wrong, or why, and those are what point to the next improvement. Error analysis means looking at the mistakes themselves: the worst ones one by one, then the errors grouped by kind of row, until a pattern appears. A doctor doesn't stop at "the patient is unwell"; error analysis is the examination that comes after the temperature reading.
This is often the most valuable hour in a project. A learning curve says whether a model needs more data or more flexibility; error analysis says which data and which features. Here it's done on house prices in California, where it uncovers a flaw in the data itself.
What you need first: learning curves and validation curves, regression metrics, cross-validation and pandas groupby.
Key terms
- Error analysis: studying a model's mistakes to find patterns that suggest improvements.
- Residual: actual value minus predicted value; positive means the model predicted too low.
- Slice: a group of rows sharing something, such as an income band, used to compare errors between groups.
- Out-of-fold prediction: a prediction for a row made by a model that didn't train on that row.
- Censored (capped) value: a value recorded as a limit, such as "500,001 or more", instead of its true amount.
Honest errors for every row
Errors must come from rows the model didn't train on, or the analysis studies memorisation instead of mistakes. cross_val_predict gives every row an out-of-fold prediction: each of the 5 folds is predicted by a model trained on the other 4.
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 KFold, cross_val_predict
from sklearn.ensemble import HistGradientBoostingRegressor
housing = fetch_california_housing(as_frame=True)
X, y = housing.data, housing.target
cv = KFold(n_splits=5, shuffle=True, random_state=0)
model = HistGradientBoostingRegressor(random_state=0)
pred = pd.Series(cross_val_predict(model, X, y, cv=cv), index=y.index)
residual = y - pred
abs_error = residual.abs()
print(f"mean absolute error {abs_error.mean():.3f}, RMSE {np.sqrt((residual ** 2).mean()):.3f}")
mean absolute error 0.312, RMSE 0.467
House values are in units of $100,000, so the typical miss is about $31,000. Wrapping the predictions in a pd.Series with the same index as y keeps every prediction lined up with its district.
Step 1: read the worst mistakes
Start with the ten biggest errors, side by side with what the model knew:
worst = abs_error.sort_values(ascending=False).head(10).index
print(pd.DataFrame({"actual": y[worst], "predicted": pred[worst],
"MedInc": X.loc[worst, "MedInc"], "HouseAge": X.loc[worst, "HouseAge"]}).round(2))
actual predicted MedInc HouseAge
1914 5.0 1.30 1.88 33.0
13766 5.0 1.51 3.06 34.0
4861 5.0 1.53 0.50 29.0
19542 4.5 1.10 1.77 39.0
10448 5.0 1.62 1.64 22.0
489 4.9 1.61 3.04 48.0
10574 5.0 1.72 1.97 6.0
10415 5.0 1.75 3.38 4.0
16642 5.0 1.78 0.70 19.0
20443 5.0 1.81 3.34 50.0
sort_values(ascending=False) puts the biggest errors first, and .index gives the district numbers, so the same rows can be pulled from y, pred and X.
Eight of the ten worst districts have an actual value of 5.0, and the other two are 4.9 and 4.5. The model predicted 1.1 to 1.8 for them, about $150,000, which is what their low incomes suggest: all ten have a median income below the dataset's median of 3.5. Either these are genuinely odd districts, or something is strange about the value 5.0.
Step 2: check what you found
One look suggests a pattern; a count confirms it.
print("largest value in the data:", y.max())
capped = y >= 5
print(f"capped districts: {capped.sum()} ({capped.mean():.1%} of rows)")
print(f"share of all absolute error from capped districts: {abs_error[capped].sum() / abs_error.sum():.1%}")
print(f"mean residual, capped: {residual[capped].mean():+.3f} uncapped: {residual[~capped].mean():+.3f}")
largest value in the data: 5.00001
capped districts: 992 (4.8% of rows)
share of all absolute error from capped districts: 9.4%
mean residual, capped: +0.552 uncapped: -0.029
~capped flips True and False, selecting the uncapped districts. :+.3f always prints a sign.
No district is worth more than 5.00001, which is $500,001. The census recorded every value above $500,000 as "$500,001", 965 districts are recorded at exactly 5.00001 and 27 more at 5.0: 992 in all, 4.8% of the rows. Their true values could be $600,000 or $2 million; the data doesn't say. These districts cause 9.4% of all the error, twice their share of the rows, and the model predicts them too low on average (a mean residual of +0.552), while ordinary districts are almost unbiased (−0.029). That's not a model bug: it's a flaw in the data, and no model setting will fix it.
Step 3: plot residuals against predictions
A residual plot shows the whole picture at once: every district, with its prediction on one axis and its error on the other.
fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(pred[~capped], residual[~capped], s=3, alpha=0.3, label="Ordinary districts")
ax.scatter(pred[capped], residual[capped], s=3, alpha=0.5, color="tab:red", label="Capped at $500,001")
ax.axhline(0, color="black", linewidth=1)
ax.set_xlabel("Predicted value ($100,000s)")
ax.set_ylabel("Residual: actual − predicted")
ax.legend(markerscale=4)
plt.show()
s=3 makes small dots and alpha makes them see-through, so dense areas show as darker. markerscale=4 enlarges the dots in the legend only.
The ordinary districts form a band around zero that widens as predictions grow: dearer districts have bigger errors in dollars. The capped districts form a perfect straight line. Because their actual value is always 5.0, their residual is 5.0 minus the prediction, so the lower the prediction, the higher the dot. A sharp straight edge in a residual plot nearly always means a limit in the data: a cap, a floor or a rounding rule.
Step 4: slice the errors
Next, compare errors between groups. Income is the strongest feature, so split the districts into five equal-sized income bands. Predict first: will the model's errors be bigger for poorer or for richer districts?
band = pd.qcut(X["MedInc"], 5, labels=["lowest", "low", "middle", "high", "highest"])
slices = pd.DataFrame({
"mean value": y.groupby(band, observed=True).mean(),
"mean abs error": abs_error.groupby(band, observed=True).mean(),
"error as share of value": (abs_error / y).groupby(band, observed=True).mean(),
})
print(slices.round(3))
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
slices["mean abs error"].plot.bar(ax=axes[0], color="tab:blue", title="Mean absolute error ($100,000s)")
slices["error as share of value"].plot.bar(ax=axes[1], color="tab:orange", title="Error as a share of the value")
for ax in axes:
ax.set_xlabel("Income band")
ax.tick_params(axis="x", rotation=0)
plt.tight_layout()
plt.show()
mean value mean abs error error as share of value
MedInc
lowest 1.184 0.259 0.231
low 1.570 0.273 0.194
middle 1.939 0.316 0.175
high 2.300 0.334 0.157
highest 3.350 0.379 0.129
pd.qcut(..., 5) cuts a column into 5 groups with equal numbers of rows. observed=True keeps only bands that actually occur.
It depends on how you measure. In dollars, the richest districts have the biggest errors: 0.379 against 0.259. As a share of the house value, it's the reverse: the model is off by 23% in the poorest districts and 13% in the richest. A $26,000 miss on a $118,000 home matters more than a $38,000 miss on a $335,000 one. If the model serves people buying homes, the poorest districts are served worst, the opposite of what the first chart suggests. Always check errors in both absolute and relative terms before deciding which group needs work.
Step 5: test a fix
Error analysis ends with an experiment. The capped districts have unknown true values, so the model is being trained to predict "500,001" for houses that may be worth far more. Experiment: train without the capped districts, and score both models on the ordinary districts only. Predict first: will removing 4.8% of the training data make the model better or worse on the rest?
pred_without = cross_val_predict(HistGradientBoostingRegressor(random_state=0), X[~capped], y[~capped], cv=cv)
print(f"ordinary districts, model trained on everything: MAE {abs_error[~capped].mean():.3f}")
print(f"ordinary districts, model trained without capped rows: MAE {np.abs(y[~capped] - pred_without).mean():.3f}")
ordinary districts, model trained on everything: MAE 0.297
ordinary districts, model trained without capped rows: MAE 0.292
Slightly better: 0.292 against 0.297, a 1.7% improvement, from training on less data. The capped rows were teaching the model that some low-income districts are worth exactly 500,001, which pulled up its predictions for similar ordinary districts. The gain is small, though, and the price is real: this model has never seen an expensive district, so it can't predict one. In practice, you'd report the cap clearly and treat "$500,001" predictions as "$500,000 or more", rather than drop the rows silently.
An error analysis checklist
| Step | Question | Tool |
|---|---|---|
| Honest errors | Are the errors from rows the model never trained on? | cross_val_predict, or a validation set |
| Worst mistakes | What do the ten biggest errors have in common? | sort_values, then read them |
| Check | Is the pattern real, and how much error does it cause? | A count and a share of total error |
| Residual plot | Do errors depend on the size of the prediction? | Scatter of residual against prediction |
| Slices | Which groups get worse predictions? | groupby on bands of key features |
| Fix | Does the obvious fix actually help? | Retrain and compare on the same rows |
For classification, the same steps work with the confusion matrix: read the most confident wrong predictions, and slice the error rate by group, as in the customer churn project's error analysis.
Practice
- Without running code: a model's biggest errors are all on rows where one feature is missing and was filled with the median. What would you try?
Show the answer
Add a column that says "this value was missing" (a missing-value indicator), so the model can treat those rows differently, or use a model that handles missing values itself, such as HistGradientBoostingRegressor. The filled median is hiding information the model needs.
- Slice the errors by
HouseAgein five bands. Which band has the largest mean absolute error?
Show the answer
age_band = pd.qcut(X["HouseAge"], 5)
print(abs_error.groupby(age_band, observed=True).mean().round(3))
HouseAge
(0.999, 17.0] 0.325
(17.0, 25.0] 0.332
(25.0, 33.0] 0.297
(33.0, 40.0] 0.266
(40.0, 52.0] 0.340
dtype: float64
The oldest districts, with houses aged 40 to 52 years, have the largest error (0.340), and the band just below, 33 to 40 years, the smallest (0.266). House age isn't an obvious source of error, which is itself useful to know: slicing finds the groups that matter, and rules out the ones that don't. The top band is worth a second look: 1,273 districts have a house age of exactly 52, the largest value, which suggests the same kind of cap.
- Why must error analysis use out-of-fold predictions rather than predictions on the training rows?
Show the answer
On its own training rows, a flexible model can be nearly perfect, so its errors there are small and unrepresentative. The patterns you'd find would be about what it failed to memorise, not about how it fails on new data.
- What share of all absolute error comes from the worst 5% of districts?
Show the answer
k = int(len(abs_error) * 0.05)
worst_5 = abs_error.sort_values(ascending=False).head(k)
print(f"{worst_5.sum() / abs_error.sum():.1%} of the error, {capped[worst_5.index].mean():.1%} of them capped")
22.8% of the error, 19.8% of them capped
The worst 5% of districts cause 22.8% of all the error, and about a fifth of them are capped. Error is concentrated: a small group of rows does a lot of damage, which is why reading the worst rows first pays off.
- The absolute-error and relative-error slices disagree about which income band is served worst. Which would you report to a house-price website, and why?
Show the answer
It depends on what users care about. A buyer comparing homes cares about relative error: being $30,000 off on a $120,000 home is much worse than on a $500,000 one. So the relative view, which shows the poorest districts are served worst, is usually the fairer report. Show both if in doubt.
Interview questions
What is error analysis in machine learning?
Systematically examining a model's mistakes on held-out data: reading the worst errors, slicing error rates by features or groups, and plotting residuals, to find patterns that suggest specific fixes such as new features, data cleaning or relabelling.
How do you decide what to improve next in a model?
Use learning curves to decide between more data and more model capacity, then error analysis to find which rows and groups cause the most error. Estimate how much each fix could gain (the share of error it addresses) and start with the largest.
What is a residual plot and what should it look like?
A scatter of residuals against predictions or a feature. A good model shows residuals centred on zero with no pattern. Funnels, curves or straight-line edges point to changing variance, missing non-linearity or problems such as capped targets.
Key takeaways
- An average score says how wrong a model is; error analysis says where and why.
- Use out-of-fold predictions, so the errors come from rows the model never trained on.
- Read the worst mistakes, count the pattern, plot residuals, then slice errors by group.
- Absolute and relative errors can tell opposite stories; look at both.
- End with an experiment: here, a known data flaw explained much of the error, but removing it helped only a little.
Frequently asked questions
How much time should error analysis take?
An hour or two per model version is usually enough to find the biggest pattern. Stop when the next fix is clear, and repeat after each change.
What if the worst errors look like wrong labels?
Check a sample by hand. If labels really are wrong, fix them or drop the rows from training, but keep evaluating on a carefully checked test set. Wrong labels in the test set make every model look worse than it is.
Can tools automate error analysis?
Tools can find slices with high error automatically, which helps with many features. They can't tell you why a slice is hard; that still needs someone who knows the data to read the rows.
What to learn next
- Tune a model's settings more efficiently in hyperparameter tuning with Optuna, the next lesson.
- Revisit learning curves and validation curves to decide between more data and a better model.
- See error analysis on a classification problem in the customer churn prediction project.