Capstone 3 — House price regression
A property platform lists houses for sale in one city. The head of pricing wants an automated valuation model (AVM): a model that estimates the market value of a house from its features. The platform will show the estimate on every new listing page, next to the asking price. Sellers use it to set a price. Agents use it to spot listings that look too cheap or too expensive.
The head of pricing has two conditions:
- Honest accuracy. The model will price houses that come on the market after training. So the accuracy number must come from sales that the model has never seen and that happened later than every training sale.
- Honest error bars. A single number is not enough. The page must show a range, for example “350k to 460k”, and about 9 out of 10 sale prices must fall inside it. The range must hold in cheap and expensive areas alike.
The decision this work supports: launch the estimate and its range on the listing pages, or not yet.
Deliverables:
- One script,
valuation.py, that runs from the project folder and prints every number it uses. - A comparison of baselines and model families on the same validation folds, a tuned final model and one test report in dollars (MAE, RMSE, R², MAPE).
- A residual report by neighborhood and price band, with figures.
- A 90% error band whose coverage is checked on validation folds and then on the test set.
- An interpretability check and a short model card: a one-page summary of what the model is for, how well it works, where it is weak and what it must not be used for.
Skills practiced:
| Module | What you use it for |
|---|---|
| 32. Math for ML | log transforms, least squares behind the linear baseline |
| 33. Feature engineering | imputation, one-hot encoding, age and trend features, leakage rules |
| 34. scikit-learn workflow | Pipeline, ColumnTransformer, FunctionTransformer, cross_validate |
| 35. Regression | TransformedTargetRegressor, regression metrics, residual analysis |
| 37. Model evaluation and tuning | TimeSeriesSplit, RandomizedSearchCV, one look at the test set |
| 38. Ensembles | random forest, HistGradientBoostingRegressor, VotingRegressor, paired fold comparison |
| 43. Interpretability | permutation importance on held-out data, responsible communication |
The house-price mini-projects of modules 33, 34 and 38 used one random hold-out split, and module 35 used shuffled K-fold. Module 38 already compared ridge, a forest, gradient boosting and an ensemble on shuffled folds. Here you redo that comparison forward in time, which is how the model will be used: train on the past, predict the future. Then you go further, with error bands, segment tests and a model card.
Dataset
Section titled “Dataset”data/houses.csv: 3,000 house sales from 2022-01-03 to 2024-12-30, sorted by sold_date. The data dictionary describes every column.
| Use | Columns |
|---|---|
| Target | price in USD |
| Features | neighborhood (8 values), sqft, bedrooms, bathrooms, year_built, lot_sqft, garage_spaces, has_pool, condition, distance_to_center_km, school_rating |
| Derived | age at sale and years since 2022-01-01 (both from sold_date), log(sqft) |
| Split key | sold_date: train on sales before 2024-07-01, test on the rest |
| Not a feature | house_id |
Known quirks, from the data dictionary:
lot_sqftandschool_ratingeach have 90 blanks (3.0%), placed completely at random.- The dictionary lists 8 price outliers: 5 inflated and 3 deflated sales. Keep them: an AVM meets odd sales in production too. MAE is less sensitive to them than RMSE.
- Price is right-skewed; log price is close to normal.
- The reference scores in the dictionary use a random split. Your scores differ, because your test set is the last six months.
Milestones
Section titled “Milestones”Milestone 1 — Explore the data and choose the target scale
Section titled “Milestone 1 — Explore the data and choose the target scale”Goal: know the data well enough to choose the target transform and the split.
Acceptance criteria:
- Print the shape, the date range and the blanks per column.
- Print the skewness of
priceand oflog(price), and plot both histograms. - Print the median price per half-year and its change over the period. State what the trend means for the split.
- Write down the decision: which target scale, and why.
Review: 35. Regression, 27. Exploratory data analysis.
Milestone 2 — Split by time and build a leakage-safe pipeline
Section titled “Milestone 2 — Split by time and build a leakage-safe pipeline”Goal: a preprocessing pipeline that learns only from training rows, and validation folds that mimic production.
Acceptance criteria:
- Test set: every sale from 2024-07-01. Assert that the last training date is before the first test date.
- One
Pipelinewith a row-wise feature step (FunctionTransformer) and aColumnTransformer: median imputing and scaling for numbers, one-hot encoding withhandle_unknown="ignore"forneighborhood. - Prove that the imputer learned the training medians, and that no blank is left after the transform.
- A forward validation splitter on the training rows (
TimeSeriesSplit). Print the date range of each validation fold.
Review: 33. Feature engineering, 34. scikit-learn workflow, 37. Model evaluation and tuning.
Milestone 3 — Baselines and model families on the same folds
Section titled “Milestone 3 — Baselines and model families on the same folds”Goal: know what “good” means before you tune anything.
Acceptance criteria:
- Baselines: the median price, and a linear regression on
priceand onlog(price). - At least three more families on
log(price): for example ridge, k-nearest neighbors, a random forest and histogram gradient boosting. - Every model sees the same folds. Print MAE (mean and standard deviation), RMSE, R² and MAPE per model, sorted by MAE.
- Show what a shuffled
KFoldwould have reported for two models. Separate the effect of the time direction from the other differences between the two protocols.
Review: 35. Regression, 38. Ensembles.
Milestone 4 — Tune with a small budget and choose the final model
Section titled “Milestone 4 — Tune with a small budget and choose the final model”Goal: improve the best family without overspending, then choose one model with a stated rule.
Acceptance criteria:
RandomizedSearchCV(or Optuna) with at most 15 candidates on the same forward folds, scored by MAE.- Print the best parameters and the spread of scores over all draws.
- Choose the final model by the lowest mean forward-CV MAE. It must also beat the best linear model (ridge or linear regression on
log(price)) on at least 3 of the 4 folds. Print the per-fold MAE and the decision.
Review: 37. Model evaluation and tuning, 38. Ensembles.
Milestone 5 — Evaluate once on the test set
Section titled “Milestone 5 — Evaluate once on the test set”Goal: one honest accuracy report in dollars.
Acceptance criteria:
- Fit the chosen model on all training rows. Predict the test set once.
- Print MAE, RMSE, R², MAPE, the median absolute percentage error and the median signed error, for the chosen model and for two baselines.
- Compare the test MAE with the forward-CV MAE. Report every metric honestly, including any metric where a baseline wins.
- Print the 5 largest errors of the chosen model and of the best baseline. Show how much the single largest error changes RMSE and R².
Review: 35. Regression, 37. Model evaluation and tuning.
Milestone 6 — Residual analysis by segment
Section titled “Milestone 6 — Residual analysis by segment”Goal: find where the model is weaker or biased.
Acceptance criteria:
- A table per neighborhood and per predicted price band: count, MAPE with its standard error, median signed error and MAE in USD.
- The median signed error per test month, to check for drift.
- One figure with two panels: the error distribution per neighborhood and the error per price band.
- Test which differences are larger than the noise: a sign test or a bootstrap interval for each neighborhood’s median signed error, and the standard error of the difference for the price-band MAPE gaps. Print the results and assert them.
Review: 35. Regression, 29. Statistics and probability.
Milestone 7 — Error bands with checked coverage
Section titled “Milestone 7 — Error bands with checked coverage”Goal: a 90% range around each estimate that really holds 90% of sale prices.
Acceptance criteria:
- Two candidate methods: quantiles of forward-validation residuals, and quantile gradient boosting at 5% and 95%.
- Measure each method’s coverage and width on the forward folds. Calibrate the residual band of each fold on earlier folds only. Choose the method on the folds, not on the test set.
- Apply the chosen band to the test set once. Print the overall coverage, the coverage per price band and the lowest coverage per neighborhood. Plot the band.
Review: 37. Model evaluation and tuning, 38. Ensembles.
Milestone 8 — Interpretability check and model card
Section titled “Milestone 8 — Interpretability check and model card”Goal: check that the model relies on sensible features, and summarize the model for its users.
Acceptance criteria:
- Permutation importance of the final pipeline on the test set, scored by MAE, on the raw columns (so
neighborhoodcounts as one feature). Plot it with error bars. - A sanity check:
house_idmust have an importance of exactly 0. - A model card printed from computed values: intended use, data, test metrics, baselines, error band, weak segments, main drivers, limits and a fairness note.
Review: 43. Interpretability.
Grading rubric
Section titled “Grading rubric”Score each criterion at one level. The maximum is 32 points.
| Criterion | Needs work (0–1) | Meets (2–3) | Excellent (4) | Max |
|---|---|---|---|---|
| EDA and target | No skew or trend check | Skew and trend printed; log target chosen | Plus the split decision linked to the trend | 4 |
| Leakage safety | Preprocessing fitted on all rows | Pipeline inside CV; test set separate | Plus a printed proof that the imputer used training medians only | 4 |
| Validation design | Shuffled folds only | Forward folds, same for every model | Plus the time-direction effect separated from the other differences | 4 |
| Baselines and families | One model | Median and linear baselines plus 3 families | Mean ± sd of MAE and means of the other 3 metrics, sorted, with comments | 4 |
| Tuning and choice | Best test score picks the model | Small random search; choice on CV | A stated rule against the best linear model, per-fold wins, budget justified | 4 |
| Test report | Test set used several times | One test run, 4 metrics, errors in USD | Plus baselines, CV-vs-test gap, the largest errors and their effect on RMSE and R² | 4 |
| Residuals and error bands | No segment view | Segment tables and a 90% band | Printed noise tests with asserts, drift check, past-only band calibration, coverage per segment | 4 |
| Interpretability and model card | No explanation | Permutation importance and a card | Sanity check; every fact on the card computed and shown on the page; limits and fairness stated | 4 |
| Total | 32 |
26 points or more: you are ready for Capstone 4.
Reference solution
Section titled “Reference solution”Try each milestone yourself first. Your names and layout can differ; your numbers must not. The blocks run top to bottom as one script, valuation.py, in well under a minute on a laptop.
Reference solution — Milestone 1: explore the data and choose the target scale
Step 1 — Imports and display options. threadpool_limits(limits=1) keeps OpenMP and BLAS to one thread. Gradient boosting would otherwise start a thread per core inside every one of the many cross-validation fits, and on a busy laptop the threads compete. The scores are the same; only the run time is steadier.
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy.stats import binomtest, loguniform, randint, skewfrom sklearn.base import clonefrom sklearn.compose import ColumnTransformer, TransformedTargetRegressorfrom sklearn.dummy import DummyRegressorfrom sklearn.ensemble import ( HistGradientBoostingRegressor, RandomForestRegressor, VotingRegressor,)from sklearn.impute import SimpleImputerfrom sklearn.inspection import permutation_importancefrom sklearn.linear_model import LinearRegression, RidgeCVfrom sklearn.metrics import ( mean_absolute_error, mean_absolute_percentage_error, r2_score, root_mean_squared_error,)from sklearn.model_selection import ( KFold, RandomizedSearchCV, TimeSeriesSplit, cross_validate,)from sklearn.neighbors import KNeighborsRegressorfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScalerfrom threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # one OpenMP/BLAS thread: same scores, steady runtimepd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)Step 2 — Load and check the blanks.
houses = pd.read_csv("data/houses.csv", parse_dates=["sold_date"])print(houses.shape)print(houses["sold_date"].min().date(), "to", houses["sold_date"].max().date())print("blanks:", houses.isna().sum()[lambda s: s > 0].to_dict())(3000, 14)2022-01-03 to 2024-12-30blanks: {'lot_sqft': 90, 'school_rating': 90}The blanks match the data dictionary. The pipeline will impute them, so no row is dropped.
Step 3 — Look at the target and the time trend.
price = houses["price"]log_price = np.log(price)print(f"price: median {price.median():,.0f}, mean {price.mean():,.0f}")print(f"skewness: price {skew(price):.2f}, log(price) {skew(log_price):.2f}")half = houses["sold_date"].dt.year.astype(str) + np.where( houses["sold_date"].dt.month <= 6, "-H1", "-H2")trend = houses.groupby(half.rename("half"))["price"].median()print("median price by half-year:")print(trend.astype(int).to_string())print(f"2024-H2 vs 2022-H1: {trend.iloc[-1] / trend.iloc[0] - 1:+.1%}")
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))axes[0].hist(price / 1000, bins=60, color="tab:blue")axes[0].set(title="Sale price", xlabel="thousand USD", ylabel="houses")axes[1].hist(log_price, bins=60, color="tab:green")axes[1].set(title="log(price)", xlabel="log USD")axes[2].plot(trend.index, trend.to_numpy() / 1000, marker="o")axes[2].set(title="Median price by half-year", ylabel="thousand USD")axes[2].tick_params(axis="x", rotation=45)fig.tight_layout()plt.show()price: median 376,000, mean 476,466skewness: price 2.66, log(price) 0.70median price by half-year:half2022-H1 3485002022-H2 3685002023-H1 3775002023-H2 3730002024-H1 3815002024-H2 4040002024-H2 vs 2022-H1: +15.9%
Decision. The skewness drops from 2.66 to 0.70 with the log. A model trained on log(price) treats a 10% error on a cheap house like a 10% error on an expensive one, which fits a valuation product. Every model except the median baseline trains on log(price), through TransformedTargetRegressor, and reports errors in USD.
The median price rose by 15.9% over the period. A model that prices future listings must cope with a moving market, so the test set is the most recent sales, not a random sample.
Reference solution — Milestone 2: split by time and build a leakage-safe pipeline
Step 1 — Split by date. The last six months are the test set. They stay untouched until milestone 5.
CUTOFF = pd.Timestamp("2024-07-01")train = houses[houses["sold_date"] < CUTOFF]test = houses[houses["sold_date"] >= CUTOFF]X_train, y_train = train.drop(columns="price"), train["price"]X_test, y_test = test.drop(columns="price"), test["price"]print(f"train: {len(train)} sales up to {train['sold_date'].max().date()}")print(f"test: {len(test)} sales from {test['sold_date'].min().date()}")
listed_outliers = [ "H0537", "H0542", "H0751", "H0914", "H2277", # inflated prices "H0887", "H0957", "H1990", # deflated prices]print("listed outliers in train:", int(train["house_id"].isin(listed_outliers).sum()), "| in test:", int(test["house_id"].isin(listed_outliers).sum()))assert train["sold_date"].max() < test["sold_date"].min()train: 2493 sales up to 2024-06-30test: 507 sales from 2024-07-01listed outliers in train: 8 | in test: 0All 8 listed outliers fall in the training period. The test MAE is therefore not inflated by them; the training data still contains them.
Step 2 — The pipeline. add_features computes row-wise features only: it learns nothing, so it cannot leak. The imputer, the scaler and the encoder learn from data, so they sit inside the pipeline and are refitted in every fold. make_model clones the preprocessing for each candidate, so no two models share fitted state.
START = pd.Timestamp("2022-01-01")NUMERIC = [ "sqft", "log_sqft", "bedrooms", "bathrooms", "year_built", "lot_sqft", "garage_spaces", "has_pool", "condition", "distance_to_center_km", "school_rating", "age_at_sale", "years_since_2022",]
def add_features(df: pd.DataFrame) -> pd.DataFrame: """Row-wise features: nothing is learned, so nothing can leak.""" out = df.drop(columns=["house_id", "sold_date"]) out["log_sqft"] = np.log(df["sqft"]) out["age_at_sale"] = df["sold_date"].dt.year - df["year_built"] out["years_since_2022"] = (df["sold_date"] - START).dt.days / 365.25 return out
preprocess = Pipeline([ ("features", FunctionTransformer(add_features)), ("columns", ColumnTransformer([ ("num", Pipeline([ ("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler()), ]), NUMERIC), ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["neighborhood"]), ])),])
def make_model(estimator, log_target: bool = True): """A fresh preprocess + estimator pipeline, trained on log(price) by default.""" pipe = Pipeline([("prep", clone(preprocess)), ("model", estimator)]) if not log_target: return pipe return TransformedTargetRegressor(regressor=pipe, func=np.log, inverse_func=np.exp)Step 3 — Prove that nothing leaks. Fit the preprocessing on the training rows, then look at what it learned.
prep = clone(preprocess).fit(X_train)imputer = prep.named_steps["columns"].named_transformers_["num"].named_steps["impute"]learned = dict(zip(NUMERIC, imputer.statistics_.tolist(), strict=True))print("imputer medians:", {c: learned[c] for c in ["lot_sqft", "school_rating"]})print("train medians: ", X_train[["lot_sqft", "school_rating"]].median().to_dict())print("test medians: ", X_test[["lot_sqft", "school_rating"]].median().to_dict())Z_test = prep.transform(X_test)print("encoded test matrix:", Z_test.shape, "| NaN left:", int(np.isnan(Z_test).sum()))assert learned["lot_sqft"] == X_train["lot_sqft"].median()imputer medians: {'lot_sqft': 7500.0, 'school_rating': 6.0}train medians: {'lot_sqft': 7500.0, 'school_rating': 6.0}test medians: {'lot_sqft': 7670.0, 'school_rating': 6.0}encoded test matrix: (507, 21) | NaN left: 0The imputer stored 7,500 for lot_sqft, the training median. The test median is 7,670, and the pipeline never saw it. After the transform, the 10 numeric inputs, log_sqft and the 2 derived features give 13 numeric columns, and neighborhood gives 8 one-hot columns: 21 in total, with no blank left.
Step 4 — Forward validation folds. TimeSeriesSplit(n_splits=4, test_size=250) is a backtest: each fold trains on all earlier sales and validates on the next 250. This mimics production, where the model always prices the future.
cv = TimeSeriesSplit(n_splits=4, test_size=250)for k, (fit_idx, val_idx) in enumerate(cv.split(X_train), 1): dates = X_train["sold_date"].iloc[val_idx] print(f"fold {k}: fit on {len(fit_idx):4d} sales, validate on " f"{dates.min().date()} .. {dates.max().date()}")fold 1: fit on 1493 sales, validate on 2023-07-21 .. 2023-10-09fold 2: fit on 1743 sales, validate on 2023-10-09 .. 2023-12-30fold 3: fit on 1993 sales, validate on 2023-12-30 .. 2024-04-02fold 4: fit on 2243 sales, validate on 2024-04-02 .. 2024-06-30The training window grows from 1,493 to 2,243 sales. Each validation window covers about three months. TimeSeriesSplit splits by row, not by date, so folds 2–4 each start on the date where the previous fit window ends: one sale date is shared between fit and validation rows. With about three sales a day, the effect is negligible.
Reference solution — Milestone 3: baselines and model families on the same folds
Step 1 — Score every candidate on the same folds. cv_scores flips the sign of the error scores so that every column reads “smaller is better”, except R².
SCORING = { "MAE": "neg_mean_absolute_error", "RMSE": "neg_root_mean_squared_error", "R2": "r2", "MAPE": "neg_mean_absolute_percentage_error",}
def cv_scores(model, splitter=cv) -> dict[str, np.ndarray]: """Fold scores for the four metrics, with errors as positive numbers.""" res = cross_validate(model, X_train, y_train, cv=splitter, scoring=SCORING) return {m: res[f"test_{m}"] * (1 if m == "R2" else -1) for m in SCORING}
def summary(scores: dict[str, dict[str, np.ndarray]]) -> pd.DataFrame: rows = { name: {"MAE": s["MAE"].mean(), "MAE_sd": s["MAE"].std(), "RMSE": s["RMSE"].mean(), "R2": s["R2"].mean(), "MAPE": s["MAPE"].mean()} for name, s in scores.items() } table = pd.DataFrame(rows).T.sort_values("MAE").round(3) usd = ["MAE", "MAE_sd", "RMSE"] table[usd] = table[usd].round().astype(int) return table
candidates = { "median": make_model(DummyRegressor(strategy="median"), log_target=False), "linear (price)": make_model(LinearRegression(), log_target=False), "linear (log)": make_model(LinearRegression()), "ridge (log)": make_model(RidgeCV(alphas=np.logspace(-3, 3, 13))), "knn (log)": make_model(KNeighborsRegressor(n_neighbors=10, weights="distance")), "forest (log)": make_model(RandomForestRegressor( n_estimators=200, max_features=0.5, min_samples_leaf=2, random_state=42)), "hist gb (log)": make_model(HistGradientBoostingRegressor(random_state=42)),}scores = {name: cv_scores(model) for name, model in candidates.items()}first_board = summary(scores)print(first_board)assert first_board.index[0] == "hist gb (log)" and first_board.index[-1] == "median"assert scores["linear (log)"]["MAE"].mean() < scores["linear (price)"]["MAE"].mean() MAE MAE_sd RMSE R2 MAPEhist gb (log) 62338 5395 97819 0.901 0.123ridge (log) 64708 2620 101255 0.894 0.131linear (log) 64747 2656 101348 0.894 0.131forest (log) 66044 6245 107957 0.880 0.128knn (log) 77227 4399 130187 0.825 0.148linear (price) 88421 4606 132141 0.822 0.201median 204287 7144 333637 -0.135 0.380What the table says:
- The asserts check the ranking: gradient boosting first, the median last, and the log target better than the raw price.
- The median baseline has an R² below 0: it is worse than predicting each fold’s own mean. Every real model beats it by far.
- The log target is the biggest single gain: the same linear regression drops from 88,421 to 64,747 USD MAE.
- Ridge and plain linear regression are almost equal: with 1,493 to 2,243 training rows and 21 columns, regularization has little to do.
- k-nearest neighbors is the weakest model family here. It weighs all 13 scaled numeric columns and 8 one-hot columns equally when it measures how similar two houses are.
- Histogram gradient boosting leads, but its standard deviation (5,395) is twice that of ridge (2,620). The gap between them is smaller than one standard deviation.
Step 2 — Why not shuffled folds? A shuffled KFold differs from the forward folds in three ways at once: other validation rows, other training sizes, and training sales from after the validation sales. To isolate the time direction, the middle protocol keeps the forward validation rows and trains on a random sample of the same size drawn from all other training sales, past and future.
shuffled = KFold(5, shuffle=True, random_state=42)rng = np.random.default_rng(42)mixed = [] # the forward validation rows, trained on past AND future salesfor fit_idx, val_idx in cv.split(X_train): others = np.setdiff1d(np.arange(len(X_train)), val_idx) mixed.append((rng.choice(others, size=len(fit_idx), replace=False), val_idx))
val_rows = np.concatenate([val_idx for _, val_idx in cv.split(X_train)])print(f"mean price: all training sales {y_train.mean():,.0f}, " f"forward validation sales {y_train.iloc[val_rows].mean():,.0f}")penalty = {}for name in ["ridge (log)", "hist gb (log)"]: runs = { "shuffled KFold": cv_scores(candidates[name], shuffled), "forward rows, mixed training": cv_scores(candidates[name], mixed), "forward": scores[name], } print(name) for label, s in runs.items(): print(f" {label:29} MAE {s['MAE'].mean():7,.0f} MAPE {s['MAPE'].mean():.3f}") penalty[name] = runs["forward"]["MAE"].mean() - runs[ "forward rows, mixed training"]["MAE"].mean()print("time-direction penalty (forward - mixed):", {k: round(v) for k, v in penalty.items()})assert penalty["hist gb (log)"] > penalty["ridge (log)"]mean price: all training sales 470,122, forward validation sales 481,335ridge (log) shuffled KFold MAE 61,596 MAPE 0.128 forward rows, mixed training MAE 64,602 MAPE 0.131 forward MAE 64,708 MAPE 0.131hist gb (log) shuffled KFold MAE 57,126 MAPE 0.118 forward rows, mixed training MAE 58,989 MAPE 0.118 forward MAE 62,338 MAPE 0.123time-direction penalty (forward - mixed): {'ridge (log)': 106, 'hist gb (log)': 3349}Shuffled folds report errors 3,100 to 5,200 USD lower than the forward folds. The step from “shuffled” to “forward rows, mixed training” changes only the validation rows and the training sizes. The forward validation sales are a little more expensive (mean 481,335 vs 470,122 USD), and dollar errors grow with price. That step costs ridge 3,006 USD and gradient boosting 1,863 USD.
The step from “mixed” to “forward” changes only the time direction. It costs ridge 106 USD, which is nothing, because its linear years_since_2022 term extrapolates the trend. It costs gradient boosting 3,349 USD: trees cannot extrapolate, so after the last training date they predict the level they last saw. The forward folds are the honest choice for an AVM, and they shrink the apparent lead of gradient boosting over ridge. The assert checks that the time penalty is larger for the trees.
Reference solution — Milestone 4: tune with a small budget and choose the final model
Step 1 — Random search on gradient boosting. 15 draws × 4 folds = 60 fits. refit=False skips a 61st fit on all training rows, because the final model is built later. The parameter names follow the nesting: regressor (the parameter of TransformedTargetRegressor that holds the pipeline) → model (the pipeline step) → the parameter.
search = RandomizedSearchCV( make_model(HistGradientBoostingRegressor(random_state=42)), param_distributions={ "regressor__model__learning_rate": loguniform(0.02, 0.2), "regressor__model__max_iter": randint(100, 600), "regressor__model__max_leaf_nodes": randint(8, 48), "regressor__model__min_samples_leaf": randint(5, 60), "regressor__model__l2_regularization": loguniform(1e-3, 10), }, n_iter=15, cv=cv, scoring="neg_mean_absolute_error", refit=False, # the final model is chosen and fitted later random_state=42,)search.fit(X_train, y_train)best_params = {k.split("__")[-1]: v for k, v in search.best_params_.items()}for key, value in best_params.items(): print(f" {key:18} {value:.3g}")print(f"tuned hist gb: forward-CV MAE {-search.best_score_:,.0f}")ranks = pd.DataFrame(search.cv_results_).sort_values("rank_test_score")print("MAE of the 15 draws, best to worst (thousand USD):")print((-ranks["mean_test_score"] / 1000).round(1).tolist()) l2_regularization 7.58 learning_rate 0.136 max_iter 393 max_leaf_nodes 9 min_samples_leaf 25tuned hist gb: forward-CV MAE 60,014MAE of the 15 draws, best to worst (thousand USD):[60.0, 60.0, 60.1, 60.2, 60.5, 60.7, 61.3, 61.5, 61.8, 62.0, 62.1, 62.4, 62.6, 62.6, 62.8]Tuning cut the forward-CV MAE from 62,338 to 60,014 USD. The best draw uses small trees (9 leaves) and strong L2 regularization (7.58). The 15 draws span only 60.0 to 62.8 thousand: the model is not very sensitive to these settings, so a larger budget would buy little. The best score is slightly optimistic, because it is the best of 15 tries on the same folds.
Step 2 — Add a blend and apply the decision rule. Step 2 of milestone 3 showed it: ridge extrapolates the time trend, and the trees do not. A VotingRegressor averages the two on the log scale, which combines the trend of ridge with the nonlinear effects of the trees.
tuned_hgb = HistGradientBoostingRegressor(random_state=42, **best_params)candidates["tuned hist gb (log)"] = make_model(clone(tuned_hgb))candidates["blend ridge+gb (log)"] = make_model(VotingRegressor([ ("ridge", RidgeCV(alphas=np.logspace(-3, 3, 13))), ("gb", clone(tuned_hgb)),]))for name in ["tuned hist gb (log)", "blend ridge+gb (log)"]: scores[name] = cv_scores(candidates[name])board = summary(scores)print(board.drop(index=["median", "linear (price)"]))
folds = pd.DataFrame({name: s["MAE"] for name, s in scores.items()}, index=pd.RangeIndex(1, 5, name="fold"))shown = ["ridge (log)", "hist gb (log)", "tuned hist gb (log)", "blend ridge+gb (log)"]print("\nMAE per forward fold:")print(folds[shown].round(-2).astype(int).to_string())choice = board.index[0]best_linear = board.loc[["linear (log)", "ridge (log)"], "MAE"].idxmin()wins = int((folds[choice] < folds[best_linear]).sum()) # unrounded scoresprint(f"\nchoice: {choice} (beats {best_linear} on {wins} of 4 folds)")assert choice == "blend ridge+gb (log)" and wins >= 3 MAE MAE_sd RMSE R2 MAPEblend ridge+gb (log) 56854 2950 90411 0.915 0.113tuned hist gb (log) 60014 3793 97885 0.901 0.116hist gb (log) 62338 5395 97819 0.901 0.123ridge (log) 64708 2620 101255 0.894 0.131linear (log) 64747 2656 101348 0.894 0.131forest (log) 66044 6245 107957 0.880 0.128knn (log) 77227 4399 130187 0.825 0.148
MAE per forward fold: ridge (log) hist gb (log) tuned hist gb (log) blend ridge+gb (log)fold1 68300 68500 65700 614002 61000 53700 55000 535003 65200 64000 59300 553004 64300 63200 60000 57200
choice: blend ridge+gb (log) (beats ridge (log) on 4 of 4 folds)The blend has the lowest mean MAE (56,854 USD), and its standard deviation (2,950) is close to that of ridge (2,620). Ridge is the best linear model. The blend beats it on all 4 forward folds (compared on the unrounded scores), so the rule chooses it. Its tuned gradient-boosting member reused the folds of the search, so its CV score is a little optimistic too. The test set will tell.
Reference solution — Milestone 5: evaluate once on the test set
Step 1 — Fit on all training rows, predict the test set once. The two baselines are scored on the same test rows for context; they are not candidates any more.
final = clone(candidates[choice]).fit(X_train, y_train)pred = pd.Series(final.predict(X_test), index=X_test.index)
def report(y_true: pd.Series, y_pred: pd.Series) -> dict[str, float]: return { "MAE": mean_absolute_error(y_true, y_pred), "RMSE": root_mean_squared_error(y_true, y_pred), "R2": r2_score(y_true, y_pred), "MAPE": mean_absolute_percentage_error(y_true, y_pred), "MdAPE": float(np.median(np.abs(y_pred - y_true) / y_true)), "bias": float(np.median((y_pred - y_true) / y_true)), }
test_rows = {choice: report(y_test, pred)}base_pred = {}for name in ["median", "ridge (log)"]: base_pred[name] = clone(candidates[name]).fit(X_train, y_train).predict(X_test) test_rows[name] = report(y_test, base_pred[name])test_table = pd.DataFrame(test_rows).Ttest_table = test_table.round(3)test_table[["MAE", "RMSE"]] = test_table[["MAE", "RMSE"]].round().astype(int)print(test_table)m = test_rows[choice]print(f"\n{choice}: mean absolute error {m['MAE']:,.0f} USD;")print(f"half of the test houses are within {m['MdAPE']:.1%} of their sale price")assert m["MAE"] < test_rows["ridge (log)"]["MAE"] < test_rows["median"]["MAE"]cv_mae = board.loc[choice, "MAE"]print(f"forward-CV MAE {cv_mae:,} vs test MAE {m['MAE']:,.0f}") MAE RMSE R2 MAPE MdAPE biasblend ridge+gb (log) 57943 102648 0.915 0.110 0.096 -0.003median 218306 378336 -0.150 0.377 0.339 -0.082ridge (log) 62865 100346 0.919 0.122 0.102 -0.011
blend ridge+gb (log): mean absolute error 57,943 USD;half of the test houses are within 9.6% of their sale priceforward-CV MAE 56,854 vs test MAE 57,943The test MAE (57,943 USD) is close to the forward-CV MAE (56,854 USD), so the validation design predicted the future well. The blend beats ridge on MAE (−7.8%), MAPE (11.0% vs 12.2%) and median absolute percentage error (9.6% vs 10.2%). Its median signed error is −0.3%: no systematic under-pricing of the later market.
Ridge wins on RMSE (100,346 vs 102,648 USD) and R² (0.919 vs 0.915). These test scores only report the result; the choice stays the one made on the forward folds, and the test set must not reopen it. RMSE squares the errors, so look at the largest ones.
Step 2 — The largest errors.
err = pd.DataFrame({"house_id": test["house_id"], "neighborhood": test["neighborhood"], "price": y_test, "blend": pred, "ridge": base_pred["ridge (log)"]})top5 = err.loc[(err["blend"] - err["price"]).abs().nlargest(5).index]print(top5.round(-2).astype({"blend": int, "ridge": int}).to_string(index=False))for name in ["blend", "ridge"]: sq = (err[name] - err["price"]) ** 2 print(f"{name}: the 5 largest errors are {sq.nlargest(5).sum() / sq.sum():.1%} " "of the squared error")print(f"largest price: training {y_train.max():,}, test {y_test.max():,}")keep = y_test < y_test.max()without_top = {}for name in ["blend", "ridge"]: without_top[name] = root_mean_squared_error(y_test[keep], err.loc[keep, name]) print(f"without that sale, {name}: RMSE {without_top[name]:,.0f}, " f"R2 {r2_score(y_test[keep], err.loc[keep, name]):.3f}")assert y_test.max() > y_train.max() and without_top["blend"] < without_top["ridge"]house_id neighborhood price blend ridge H2921 Lakeview 3730500 2397100 2933700 H2980 Lakeview 2055000 1451000 1338900 H2599 Oak Hill 2043000 1623700 1786500 H2669 Oak Hill 2184000 1797500 1769400 H2673 Oak Hill 1636000 1269700 1317800blend: the 5 largest errors are 48.7% of the squared errorridge: the 5 largest errors are 31.1% of the squared errorlargest price: training 2,772,500, test 3,730,500without that sale, blend: RMSE 83,926, R2 0.932without that sale, ridge: RMSE 93,991, R2 0.915All 5 largest errors are expensive Lakeview and Oak Hill houses that both models underprice. The largest is H2921, sold for 3,730,500 USD, above the largest training price of 2,772,500 USD. The blend predicts 2,397,100 and ridge 2,933,700: the tree member cannot predict above the prices it has seen, ridge can. The 5 largest errors make up 48.7% of the blend’s squared error, against 31.1% for ridge.
Without that one sale, the ranking flips: the blend’s RMSE is 83,926 against 93,991 for ridge, and its R² is 0.932 against 0.915. So one sale above the training range decides RMSE and R². The blend is better for the typical house, and it may underprice houses above the training price range. The model card says both.
Reference solution — Milestone 6: residual analysis by segment
Step 1 — Tables and figure. The price bands use the predicted price, not the sale price. At valuation time, only the estimate is known. Bands built on the actual price also bias the residuals by construction: the cheapest sales are, on average, the ones the model overestimated.
res = pd.DataFrame({ "neighborhood": test["neighborhood"], "pred": pred, "pct_error": (pred - y_test) / y_test,})res["abs_pct"] = res["pct_error"].abs()res["abs_err"] = (pred - y_test).abs()res["band"] = pd.cut(res["pred"], [0, 250_000, 400_000, 700_000, np.inf], labels=["<250k", "250-400k", "400-700k", "700k+"])
def segment_table(by: str) -> pd.DataFrame: g = res.groupby(by, observed=True) return pd.DataFrame({ "n": g.size(), "MAPE": g["abs_pct"].mean(), "MAPE_se": g["abs_pct"].std() / np.sqrt(g.size()), "bias": g["pct_error"].median(), "MAE_usd": g["abs_err"].mean().round().astype(int), }).round(3)
by_hood = segment_table("neighborhood").sort_values("MAPE")by_band = segment_table("band")print(by_hood)print()print(by_band)month = test["sold_date"].dt.month_name().str[:3].rename("month")monthly = res.groupby(month, sort=False)["pct_error"].median()print("\nmedian signed error by test month:")print(monthly.round(3).to_frame("bias").T.to_string()) n MAPE MAPE_se bias MAE_usdneighborhoodDowntown 49 0.098 0.011 0.027 35893Westfield 73 0.099 0.009 -0.020 28551Maple Grove 82 0.106 0.009 0.007 48314Cedar Park 70 0.108 0.009 -0.006 31156Riverside 59 0.114 0.011 -0.053 57869Lakeview 63 0.118 0.011 0.021 116396Oak Hill 62 0.119 0.011 0.017 101167Old Town 49 0.123 0.014 -0.010 48406
n MAPE MAPE_se bias MAE_usdband<250k 66 0.102 0.009 0.000 22682250-400k 188 0.110 0.006 -0.016 35732400-700k 160 0.106 0.006 0.012 53802700k+ 93 0.123 0.009 -0.024 134992
median signed error by test month:month Jul Aug Sep Oct Nov Decbias -0.045 0.022 0.04 0.004 -0.007 -0.039
What the residuals say:
- Percentage errors are similar everywhere. MAPE ranges from 9.8% (Downtown) to 12.3% (Old Town). Each MAPE has a standard error of about 1 point (0.9–1.4), so neighborhoods 1–2 points apart are not reliably different with 49–82 test sales each.
- Dollar errors are not similar. The MAE is 28,551 USD in Westfield and 116,396 USD in Lakeview, because Lakeview houses cost more. A fixed dollar range would be useless; the band in milestone 7 is a percentage.
- No drift trend within the test period. The monthly median signed error moves between −4.5% and +4.0% with no direction.
Two patterns need a test: Riverside’s median signed error (−5.3%) is the largest bias, and the 700k+ band has the highest MAPE (12.3%).
Step 2 — Test the differences against the noise. For the bias, a sign test asks: if over- and under-pricing were equally likely, how surprising is the number of underpriced sales? Testing 8 neighborhoods gives 8 chances of a false alarm, so the p-values are multiplied by 8 (the Bonferroni correction). A bootstrap interval of the median gives the size of the bias. For the price bands, the gap between two MAPEs is divided by the standard error of the difference, .
def median_ci(x: pd.Series, n_boot: int = 2000) -> np.ndarray: """Bootstrap 95% interval of the median.""" draws = np.random.default_rng(42).choice(x.to_numpy(), size=(n_boot, len(x))) return np.quantile(np.median(draws, axis=1), [0.025, 0.975])
rows = {}for hood, d in res.groupby("neighborhood"): under = int((d["pct_error"] < 0).sum()) p_value = binomtest(under, len(d), 0.5).pvalue lo, hi = median_ci(d["pct_error"]) rows[hood] = {"n": len(d), "under": under, "bias": d["pct_error"].median(), "ci_low": lo, "ci_high": hi, "p_adj": min(1.0, 8 * p_value)}bias_test = pd.DataFrame(rows).T.astype({"n": int, "under": int}).round(3)print(bias_test.sort_values("p_adj"))flagged = bias_test.index[bias_test["p_adj"] < 0.05].tolist()print("bias beyond noise (sign test, Bonferroni for 8 areas):", flagged)
top = by_band.loc["700k+"]z = {band: (top["MAPE"] - r["MAPE"]) / np.hypot(top["MAPE_se"], r["MAPE_se"]) for band, r in by_band.drop(index="700k+").iterrows()}print("700k+ MAPE gap in standard errors:", {k: round(float(v), 2) for k, v in z.items()})assert flagged == ["Riverside"] and bias_test.loc["Riverside", "ci_high"] < 0assert all(abs(v) < 1.96 for v in z.values())
fig, axes = plt.subplots(1, 2, figsize=(12, 4))order = by_hood.index.tolist()axes[0].boxplot([res.loc[res["neighborhood"] == h, "pct_error"] * 100 for h in order], tick_labels=order, orientation="horizontal")axes[0].axvline(0, color="gray", lw=1)axes[0].set(title="Test error by neighborhood", xlabel="(predicted - actual) / actual, %")x = np.arange(len(by_band))axes[1].bar(x - 0.2, by_band["MAPE"] * 100, width=0.4, label="MAPE")axes[1].bar(x + 0.2, by_band["bias"] * 100, width=0.4, label="median signed error")axes[1].axhline(0, color="gray", lw=1)axes[1].set_xticks(x, by_band.index.astype(str))axes[1].set(title="Test error by predicted price band", xlabel="predicted price", ylabel="%")axes[1].set_ylim(-4, 16)axes[1].legend(loc="upper left", ncols=2)fig.tight_layout()plt.show() n under bias ci_low ci_high p_adjRiverside 59 41 -0.053 -0.088 -0.019 0.03Cedar Park 70 36 -0.006 -0.061 0.034 1.00Downtown 49 21 0.027 -0.018 0.064 1.00Lakeview 63 30 0.021 -0.023 0.035 1.00Maple Grove 82 38 0.007 -0.037 0.037 1.00Oak Hill 62 27 0.017 -0.050 0.057 1.00Old Town 49 25 -0.010 -0.043 0.071 1.00Westfield 73 41 -0.020 -0.041 0.016 1.00bias beyond noise (sign test, Bonferroni for 8 areas): ['Riverside']700k+ MAPE gap in standard errors: {'<250k': 1.65, '250-400k': 1.2, '400-700k': 1.57}- Riverside is underpriced beyond the noise. 41 of its 59 test sales are underpriced. The corrected p-value is 0.03, and the 95% bootstrap interval of its median signed error, −8.8% to −1.9%, excludes 0. No other neighborhood comes close: every other corrected p-value is 1.00.
- The 700k+ band is not reliably harder. Its MAPE gaps are 1.2 to 1.65 standard errors of the difference, all below 1.96 (the 5% level). With 93 test sales in that band, the higher MAPE may be noise.
Reference solution — Milestone 7: error bands with checked coverage
Step 1 — Forward predictions. Refit the chosen model on each forward fold and keep its predictions for the validation rows. In the same loop, fit two quantile gradient-boosting models at 5% and 95% on log(price). They minimize the pinball loss, a loss that penalizes errors on one side more than on the other, so the model learns a quantile instead of the mean. A quantile of log(price) gives the same quantile of price, because the log keeps the order.
fwd_parts = []for k, (fit_idx, val_idx) in enumerate(cv.split(X_train), 1): X_fit, y_fit = X_train.iloc[fit_idx], y_train.iloc[fit_idx] X_val, y_val = X_train.iloc[val_idx], y_train.iloc[val_idx] point = clone(candidates[choice]).fit(X_fit, y_fit).predict(X_val) lower, upper = ( make_model(HistGradientBoostingRegressor( loss="quantile", quantile=q, random_state=42, **best_params)) .fit(X_fit, y_fit).predict(X_val) for q in (0.05, 0.95) ) fwd_parts.append(pd.DataFrame({"fold": k, "y": y_val, "pred": point, "q05": lower, "q95": upper}))fwd = pd.concat(fwd_parts)fwd["log_res"] = np.log(fwd["y"] / fwd["pred"])print(len(fwd), "forward predictions;", "log residual quantiles 5%, 50%, 95%:", np.quantile(fwd["log_res"], [0.05, 0.5, 0.95]).round(3).tolist())1000 forward predictions; log residual quantiles 5%, 50%, 95%: [-0.231, 0.006, 0.242]The 1,000 forward log residuals are centered (median 0.006). Their 5% and 95% quantiles are −0.231 and 0.242.
Step 2 — Compare the two methods on the folds. The residual method is a form of split conformal prediction: it takes the band from the quantiles of residuals on data the model did not train on. To score it fairly, each fold’s band uses only the residuals of the earlier folds, as in production, where only past errors are known. Fold 1 has no earlier fold, so the comparison uses folds 2–4.
rows = []for k in range(2, 5): # fold 1 has no earlier residuals to calibrate on held = fwd[fwd["fold"] == k] lo, hi = np.quantile(fwd.loc[fwd["fold"] < k, "log_res"], [0.05, 0.95]) rows.append({ "fold": k, "resid_cover": held["log_res"].between(lo, hi).mean(), "resid_width": np.exp(hi) - np.exp(lo), "qgb_cover": held["y"].between(held["q05"], held["q95"]).mean(), "qgb_width": ((held["q95"] - held["q05"]) / held["pred"]).median(), })intervals = pd.DataFrame(rows).set_index("fold")print(intervals.round(3))print(intervals.mean().round(3).to_string())gap = (intervals[["resid_cover", "qgb_cover"]].mean() - 0.90).abs()closer = gap["resid_cover"] < gap["qgb_cover"]method = "residual quantiles" if closer else "quantile GB"print("chosen interval method:", method) resid_cover resid_width qgb_cover qgb_widthfold2 0.932 0.512 0.768 0.3713 0.916 0.482 0.748 0.3814 0.908 0.479 0.768 0.366resid_cover 0.919resid_width 0.491qgb_cover 0.761qgb_width 0.373chosen interval method: residual quantilesThe residual band covers 91.9% on average (93.2%, 91.6% and 90.8%), close to the 90% target. Quantile gradient boosting gives narrower bands (37.3% vs 49.1% of the estimate) but covers only 76.1%. Its quantiles were learned on the training rows, where a boosted model fits better than on new data, so its band is likely too narrow for new sales. The rule picks the method whose coverage is closer to 90%: the residual quantiles.
Step 3 — Apply the band to the test set, once. The band uses all 1,000 forward residuals.
LO, HI = np.quantile(fwd["log_res"], [0.05, 0.95])res["lower"] = pred * np.exp(LO)res["upper"] = pred * np.exp(HI)res["inside"] = y_test.between(res["lower"], res["upper"])print(f"band: {np.exp(LO) - 1:+.1%} to {np.exp(HI) - 1:+.1%} around the estimate")print(f"test coverage {res['inside'].mean():.1%} (target 90%), " f"mean width {(res['upper'] - res['lower']).mean():,.0f} USD")cover = pd.DataFrame({ "by band": res.groupby("band", observed=True)["inside"].mean(),}).round(3)print(cover.T.to_string())hood_cover = res.groupby("neighborhood")["inside"].mean().sort_values().round(3)print("lowest neighborhood coverage:", hood_cover.index[0], hood_cover.iloc[0])ci = binomtest(int(res["inside"].sum()), len(res), 0.9).proportion_ci(method="wilson")print(f"95% interval of the test coverage: {ci.low:.1%} to {ci.high:.1%}")test_log_res = np.log(y_test / pred)print("test log residual quantiles 5%, 95%:", np.quantile(test_log_res, [0.05, 0.95]).round(3).tolist())assert 0.85 <= res["inside"].mean() <= 0.95
fig, ax = plt.subplots(figsize=(6, 5))grid = np.geomspace(res["pred"].min(), res["pred"].max(), 50)ax.fill_between(grid / 1000, grid * np.exp(LO) / 1000, grid * np.exp(HI) / 1000, color="tab:blue", alpha=0.15, label="90% band")ax.plot(grid / 1000, grid / 1000, color="tab:blue", lw=1, label="estimate = actual")inside = res["inside"]ax.scatter(pred[inside] / 1000, y_test[inside] / 1000, s=8, color="gray", label="inside")ax.scatter(pred[~inside] / 1000, y_test[~inside] / 1000, s=14, color="tab:red", label="outside")ax.set(xscale="log", yscale="log", xlabel="estimate, thousand USD", ylabel="sale price, thousand USD", title="Test sales and the 90% band")ticks = [200, 300, 500, 1000, 2000, 3000]ax.set_xticks(ticks, [str(t) for t in ticks])ax.set_yticks(ticks, [str(t) for t in ticks])ax.minorticks_off()ax.legend()fig.tight_layout()plt.show()band: -20.7% to +27.4% around the estimatetest coverage 92.3% (target 90%), mean width 237,907 USDband <250k 250-400k 400-700k 700k+by band 0.909 0.926 0.938 0.903lowest neighborhood coverage: Old Town 0.89895% interval of the test coverage: 89.7% to 94.3%test log residual quantiles 5%, 95%: [-0.214, 0.23]
The band runs from 20.7% below to 27.4% above the estimate. It is nearly symmetric on the log scale (−0.231 to 0.242), and exp turns equal log steps into unequal percentage steps. On the test set it covers 92.3% of sales, and at least 90.3% in every price band. The lowest neighborhood, Old Town, still reaches 89.8%.
The 95% interval of the test coverage, 89.7% to 94.3%, contains the 90% target, so the over-coverage is within the noise of 507 sales. It also has a likely cause: the test log residuals (5% and 95% quantiles −0.214 and 0.230) are a little tighter than the forward residuals the band was built from. The forward models trained on 1,493–2,243 sales; the final model trained on 2,493. The mean width is 237,907 USD: an honest band for a 400k estimate is roughly 317k to 510k.
Reference solution — Milestone 8: interpretability check and model card
Step 1 — Permutation importance on the test set. The model is frozen, so this analysis does not change any decision. Shuffling a raw column breaks its link to the price; the MAE increase measures how much the model relies on it.
perm = permutation_importance( final, X_test, y_test, scoring="neg_mean_absolute_error", n_repeats=5, random_state=42,)importance = pd.DataFrame( {"MAE_increase": perm.importances_mean, "sd": perm.importances_std}, index=X_test.columns,).sort_values("MAE_increase", ascending=False)print(importance.round(0).astype(int))assert importance.loc["house_id", "MAE_increase"] == 0
top = importance.drop(index="house_id").iloc[::-1]fig, ax = plt.subplots(figsize=(7, 4.5))ax.barh(top.index, top["MAE_increase"] / 1000, xerr=top["sd"] / 1000, color="tab:blue")ax.set(xlabel="MAE increase when the column is shuffled, thousand USD", title="Permutation importance on the test set")fig.tight_layout()plt.show() MAE_increase sdsqft 114962 5297neighborhood 66681 3117condition 26750 1466distance_to_center_km 22092 2500school_rating 21251 2092year_built 7783 1144bathrooms 7374 864garage_spaces 3476 584has_pool 3024 750lot_sqft 1786 760bedrooms 911 267sold_date 128 69house_id 0 0
The ranking is sensible for house prices: size first, then location (neighborhood, distance) and quality (condition, school rating). house_id scores exactly 0, as it must, because the pipeline drops it. sold_date scores only 128 USD. That does not mean the trend is unimportant: inside a six-month test window, shuffling the dates moves years_since_2022 by at most half a year. Permutation importance measures reliance within the test data, not the effect of the trend over three years. A low score does not mean useless: correlated columns such as bedrooms and sqft can stand in for each other, so shuffling one of them costs little. Importance is reliance, not causation: adding a bedroom to a house does not change its value by this amount.
Step 2 — The model card. Every number and date comes from the variables above, so the card cannot drift from the results. Each statement on it is shown earlier on the page: the trend in milestone 1, the Riverside test and the band tests in milestone 6, the largest training price and its effect on RMSE in milestone 5. The final assert guards the RMSE statement. The OneHotEncoder ignores unknown neighborhoods, but the page never tests what the model does with one, so the card supports only the 8 known neighborhoods.
period = f"{train['sold_date'].min():%Y-%m}..{train['sold_date'].max():%Y-%m}"rise = trend.iloc[-1] / trend.iloc[0] - 1band_note = "no price band differs beyond noise" if all( abs(v) < 1.96 for v in z.values()) else "see the price-band table"card = f"""MODEL CARD: house valuation model, version 1Model : {choice}; trained on log(price); {len(train)} sales up to { train['sold_date'].max().date()}Intended : first estimate for a listing in the 8 known neighborhoods, reviewed by an agent; not a mortgage appraisalTest set : {len(test)} sales from {test['sold_date'].min().date()}, scored onceAccuracy : MAE {m['MAE']:,.0f} USD | RMSE {m['RMSE']:,.0f} USD | R2 {m['R2']:.3f} \| MAPE {m['MAPE']:.1%}Baselines : median MAE {test_rows['median']['MAE']:,.0f} USD; ridge (log) MAE \{test_rows['ridge (log)']['MAE']:,.0f} USDError band: estimate {np.exp(LO) - 1:+.0%} / {np.exp(HI) - 1:+.0%}; \test coverage {res['inside'].mean():.0%} (target 90%)Watch : underpriced beyond noise: {', '.join(flagged)} (median signed error \{bias_test.loc[flagged[0], 'bias']:+.1%}); {band_note}Drivers : {', '.join(importance.index[:4])}Limits : trained on {period}; the median price rose {rise:+.1%} over the data, so monitor the monthly signed error and retrain when it drifts; may underprice houses above the largest training price \({y_train.max():,} USD); RMSE is above ridge (log) because of one such sale; only the 8 known neighborhoods are supportedFairness : neighborhood may proxy for who lives there; check errors by area"""print(card)assert m["RMSE"] > test_rows["ridge (log)"]["RMSE"] # the limit stated aboveMODEL CARD: house valuation model, version 1Model : blend ridge+gb (log); trained on log(price); 2493 sales up to 2024-06-30Intended : first estimate for a listing in the 8 known neighborhoods, reviewed by an agent; not a mortgage appraisalTest set : 507 sales from 2024-07-01, scored onceAccuracy : MAE 57,943 USD | RMSE 102,648 USD | R2 0.915 | MAPE 11.0%Baselines : median MAE 218,306 USD; ridge (log) MAE 62,865 USDError band: estimate -21% / +27%; test coverage 92% (target 90%)Watch : underpriced beyond noise: Riverside (median signed error -5.3%); no price band differs beyond noiseDrivers : sqft, neighborhood, condition, distance_to_center_kmLimits : trained on 2022-01..2024-06; the median price rose +15.9% over the data, so monitor the monthly signed error and retrain when it drifts; may underprice houses above the largest training price (2,772,500 USD); RMSE is above ridge (log) because of one such sale; only the 8 known neighborhoods are supportedFairness : neighborhood may proxy for who lives there; check errors by areaStretch goals
Section titled “Stretch goals”- Optuna. Replace the random search with an Optuna study (
TPESampler(seed=42), 15 trials). Does it find a better MAE with the same budget? - Nested backtest. Put the tuning inside each forward fold, so the blend’s CV score is no longer optimistic (module 37).
- Band per price band. Compute the residual quantiles separately for each predicted price band. This is Mondrian conformal prediction: split conformal prediction run separately within each group. Does the 700k+ band get wider and the cheap band narrower, with coverage still near 90%?
- Monthly retraining. Simulate production: retrain on all sales up to the end of each test month and predict the next month. Does the MAE improve over a single model trained on 2024-06-30?
- Riverside follow-up. Refit the final model without one feature at a time and check whether the Riverside bias changes. Which features, if any, change it? Does the bias persist in the out-of-fold predictions on the training years, or is it specific to the test months?
- Monotonic constraints. Set
monotonic_cston the gradient-boosting member so that moresqftnever lowers the estimate. Compare the CV MAE.
Next steps
Section titled “Next steps”- Review 43. Interpretability for SHAP values, which explain a single listing’s estimate.
- Read 44. ML in production to save, version and monitor a model like this one.
- Continue with Capstone 4 — Customer churn classification, where the threshold choice replaces the error band.