Project: predict house prices
Last updated
Everything in this stage, on one real problem. You'll predict the median house value of California districts from the 1990 census: decide whether machine learning fits the job, set a baseline, build features inside a pipeline, race a linear model, a random forest and gradient boosting on the same folds, tune the winner, score it once on the test set, and then find out where on the map it goes wrong. You'll finish with a short report that someone else could act on.
By the end of this lesson you can
- Decide whether a problem suits machine learning, and set a baseline to beat
- Build features and preprocessing into pipelines, and compare three models fairly
- Tune the best model with random search, and score it once on a test set
- Analyse the errors by region and value, and write a short model report
Plan it
The question: from a few numbers about a district, its income, its houses, its people and where it is, how well can a model estimate the district's median house value?
The data: 2,000 districts sampled from the California housing data (Pace and Barry, 1997), from the 1990 US census, which lesson 4.2 met. The value is in units of $100,000.
What you'll make: one notebook that, run from the top,
- loads the data and draws it on a map,
- splits off a test set and scores a baseline,
- builds features and preprocessing into three pipelines, and races them on the same folds,
- tunes the winner with random search,
- scores it once on the test set,
- finds where the errors are, by region and by value,
and a short report at the end. On your own computer, make it in the ml-course folder as 04-houses.ipynb, with housing.csv beside it. Here, it runs in the page. The order is lesson 4.14's:
Press Walk through it to follow the work round the chart, one stop at a time.
- Ask the question, and decide whether ML is right (lesson 2.12).
- Get the data, and split off a test set at once.
- Explore, clean and build features, inside a pipeline (lessons 4.1, 4.2).
- Score a baseline.
- Compare a short list of models by cross-validation (lesson 4.14).
- Tune the best one (lesson 4.13).
- Good enough? If no, go back to step 3.
- Score the test set, once; report it, release it, and watch it for drift.
2,000 districts and 9 columns. The median value is 1.79, $179,000. And 103 districts are at exactly 5 or a little over: the census recorded every value above $500,000 as $500,001. Remember that; it matters in step 7. On the map, the dear districts line the coast round San Francisco and Los Angeles.
Is ML the right tool?
Lesson 2.12's questions, asked of this problem:
Press Walk through it to follow the work round the chart, one stop at a time.
- Name the decision the model would help with.
- Can a rule or a lookup decide it? If yes, write the rule; no ML is needed.
- Are there examples, with the right answers? If no, collect and label data first.
- Is it like the data it will meet in use? If no, get data from the real setting.
- Can the people affected live with its mistakes? If no, keep a person deciding, or don’t build it.
- Otherwise, frame it (X, y, a metric, a baseline) and try machine learning.
- Is there a rule that already works? No. Nobody can write down how income, age, crowding and location combine into a price.
- Is there a pattern in the data? Almost certainly: richer districts and coastal ones cost more.
- Are there enough labelled examples? 2,000 here, 20,640 in the full data, each with a true answer.
- Can mistakes be tolerated? For a rough estimate of a district's prices, yes. For valuing one particular house, no: a district's median says little about one house, and nobody should be refused a loan because of this model.
- Will the world stay like the data? No. These are 1990 prices (lesson 4.14's drift). A model for today needs today's data. As an exercise in method, though, it's fine.
So machine learning fits, for the job of estimating districts, on data like this. Write that limit down now; it goes in the report.
Baseline
Split off 20% as a test set before anything else, and don't look at it again until step 6. Then make one set of five folds for the training part, and a helper that scores any model on them by RMSE (lesson 2.11):
A DummyRegressor always predicts the training mean, and is wrong by 1.158 on average, about $116,000. Every model has to beat that.
Features and preprocessing in a pipeline
Lesson 4.2's features, written as one function, add_features:
to_city: the distance in kilometres to the nearer of San Francisco and Los Angeles. A model can't easily learn "near a city" from latitude and longitude, but it can from this.bedroom_share: bedrooms as a share of rooms.log_popandlog_occup: the logs of population and of people per household, two columns with long right tails (lesson 4.1).
FunctionTransformer turns the function into a pipeline step, so the features are made inside every fold, from that fold's rows alone (lesson 4.1's leakage rule). The linear model also needs scaling; the trees don't. Three candidates, from lesson 4.14's short list for a table:
Cross-validation
Because all three were scored on the same five folds, the comparison is fair (lesson 4.14):
| Model | Cross-validated RMSE | Against the baseline |
|---|---|---|
| Baseline (the mean) | 1.158 | |
| Ridge, with the features | 0.663 | 43% lower |
| Random forest | 0.591 | 49% lower |
| Gradient boosting | 0.556 | 52% lower |
Gradient boosting wins, as lesson 4.14 said it often does on tables, and by more than the forest's margin over it. The ridge model is well behind: the effect of location on price isn't a straight line, even with to_city to help it. Boosting goes forward.
Tune the best model
Lesson 4.13's recipe: random search over the settings that matter for boosting, on log scales for the learning rate and the penalty. To keep the page within its time limit, it's only 8 tries on 3 folds; on your own computer, try 50 on 5.
The best of the 8 tries scored 0.558. Boosting with its defaults scored 0.556. The two numbers come from different folds (3 against 5), so they aren't exactly comparable, but the message is plain: tuning gained nothing. scikit-learn's defaults for HistGradientBoostingRegressor are already good. In step 4, to_city and the other features did far more. That's common, and worth knowing before you spend a day on a search.
Now, and only now, the test set, once:
RMSE 0.561 on the test set, close to the cross-validated 0.556, so the cross-validation didn't fool us. The mean absolute error is 0.364, $36,400, and = 0.763: the model explains about three quarters of the spread in values. Don't go back and change anything because of this number; if you do, the test set stops being a test (lesson 2.5).
Error analysis by region on a map
One RMSE hides where the model goes wrong. Split the test districts by region (north of latitude 37, central, south of 35) and by whether they're within 50 km of a city, and look at the error in each group: the bias, the mean of prediction minus truth, and the MAE:
- The bias is small everywhere, at most 0.054 ($5,400). The model doesn't systematically over- or under-price any region.
- The MAE isn't. The quiet central districts are off by 0.19 on average; the districts near San Francisco by 0.49, more than twice as much. Near cities, prices vary much more from district to district, and the features don't capture all of why.
On the map, and as predicted against true:
On the left, red where the model guessed too high and blue where too low; the strong colours gather round the two cities. On the right, a point on the diagonal is a perfect prediction. Notice the column of points at a true value of 5: the capped districts. Their true value is "$500,000 or more", but the model is trained to predict 5 exactly. How does it do on them?
21 capped districts in the test set, predicted too low by 0.75 on average. Some of that is the model being cautious at the top of the range, where it has seen few examples. But the label itself is wrong: these districts are worth at least 5, and some much more. Any model trained on these labels will struggle at the top. The fix isn't a better model; it's better labels, or saying plainly that the model can't value expensive districts.
A short model report
A model nobody can judge won't be trusted, or worse, will be trusted wrongly. Mitchell and others (2019) suggest a model card: a short note that travels with the model. Write yours in a Markdown cell at the end of the notebook. Something like:
What it does. Estimates the median house value of a California census district from eight numbers: income, house age, rooms, bedrooms, population, occupancy, latitude and longitude.
Data. 2,000 districts from the 1990 census (Pace and Barry, 1997). Values above $500,000 were recorded as $500,001.
Model. Gradient-boosted trees with four engineered features (distance to the nearer big city, bedroom share, log population, log occupancy), chosen over ridge regression and a random forest by 5-fold cross-validation.
Performance. On 400 held-out districts: RMSE $56,100, MAE $36,400, 0.76. The mean alone would be off by about $116,000.
Where it's weaker. Districts near San Francisco and Los Angeles (MAE about $37,000 to $49,000, against $19,000 in the central region). Districts worth $500,000 or more are underestimated by $75,000 on average, because their labels are capped.
Don't use it for. Valuing a single house, or today's prices: it knows 1990 districts only.
Five short sections, and every number in them came from this notebook. Anyone reading it knows what the model is good for, how good, and where not to trust it.
Finished
You've taken a real problem from question to report. Your notebook
- asks whether machine learning fits, and writes down the limits,
- scores a baseline, so every result has something to be compared with,
- builds the features and preprocessing inside pipelines, so nothing leaks,
- compares three models on the same folds, and tunes the winner,
- scores the final model once on the test set,
- finds where it goes wrong, by region and by value, and says so in a model card.
Before you call it finished, restart the kernel and run every cell from the top. If the numbers are the same, it's done.
Try next:
- Drop
add_featuresfrom the boosting pipeline. How much worse is it, compared with what tuning gained? - Run the search with 50 tries on 5 folds. Does it beat the defaults now?
- Train a
HistGradientBoostingRegressorwithloss="absolute_error". Its MAE should go down and its RMSE up. Why (lesson 2.11)? - Load the full data with
fetch_california_housing()on your own computer. With ten times the rows, does the ranking of the three models change?
Stage 5 builds the first artificial neurons, the start of models that learn their own features.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Pace and Barry, Sparse spatial autoregressions, Statistics and Probability Letters 33(3), 1997: the California housing data, from the 1990 US census
- scikit-learn: fetch_california_housing: the full 20,640 districts; this project uses a 2,000-row sample
- scikit-learn: HistGradientBoostingRegressor: the model that wins, and its settings
- Mitchell et al., Model cards for model reporting, FAT* 2019: what a short model report should say