Skip to content

35. Regression — Mini-project

You work in the audit team of a mortgage lender. Before the lender accepts a sale price as the value of a house, the team wants a second opinion from a model. A sale whose recorded price is far from what comparable houses sell for is either a data-entry error or a deal that needs a closer look.

Write a script, valuation_check.py, that:

  1. estimates the price of every one of the 3,000 sales with a model that never saw that sale;
  2. compares a transparent model (linear regression on log price) with an accurate one (gradient boosting on log price);
  3. flags the sales whose price is unusually far from the estimate, and prints a short audit report.

The project uses every part of module 35: pipelines with a ColumnTransformer, a log target with TransformedTargetRegressor, gradient boosting, four of the five metrics, residual analysis and a plot. It adds one new tool: out-of-fold predictions.

data/houses.csv: 3,000 house sales from 2022 to 2024, described in the data dictionary. Use every column except house_id, sold_date and price as features, and add one more: years_since_2022, the time between 2022-01-01 and sold_date in years (exercise M35-X01 estimated a market trend of about +4.8% per year from it).

The data dictionary lists eight sales whose prices were deliberately corrupted: five inflated (×2.2–3.0) and three deflated (×0.35–0.5). Your script does not use this list to build the flags. It uses it only at the end, to measure how many of the eight the check catches:

H0537, H0542, H0751, H0914, H2277, H0887, H0957, H1990.

Your script must:

  1. Load the data, add years_since_2022, and convert neighborhood to the pandas category dtype so gradient boosting can read it directly.
  2. Build two models, both on log price with TransformedTargetRegressor: a linear regression after a ColumnTransformer (one-hot neighborhood with drop="first", median imputation, scaling), and a HistGradientBoostingRegressor(random_state=42).
  3. Produce out-of-fold predictions for all 3,000 sales with cross_val_predict and KFold(n_splits=5, shuffle=True, random_state=42). Each sale is predicted by the model trained on the other four folds, so no sale is valued by a model that saw its own price.
  4. Print MAE, RMSE, R² and MAPE of the out-of-fold predictions for both models, and choose the model with the lower RMSE for the audit.
  5. Compute the log residual of every sale for the chosen model. Measure the spread with a robust standard deviation: 1.4826×1.4826 \times the median absolute deviation from the median residual. A robust statistic is not inflated by the very outliers you are hunting.
  6. Flag the sales whose log residual is more than 3.5 robust standard deviations from the median residual. Print the number of flags and a table of the flagged sales, worst first, with the house id, neighborhood, size, recorded price, model estimate and residual.
  7. Print how many of the eight known corrupted sales were flagged.
  8. Draw a residuals-against-fitted plot with the flagged sales highlighted.
  9. End with assert checks: both models beat an R² of 0.85, the flags include at least 6 of the 8 known sales, and fewer than 2% of all sales are flagged.

The expected report:

Expected output
MAE RMSE R2 MAPE
model
log linear 61673 102525 0.897 0.128
log boosting 55802 97310 0.907 0.114
chosen model: log boosting
robust sd of log residuals: 0.137
flagged sales: 12 of 3000
house_id neighborhood sqft price estimate log_resid
H0542 Maple Grove 3770 2660000 856000 1.134
H0914 Cedar Park 1730 719500 258000 1.024
H0751 Oak Hill 1370 1431000 519000 1.014
H2277 Old Town 1080 905500 333000 1.000
H0537 Westfield 1040 500500 191000 0.962
H0957 Old Town 1160 117500 297000 -0.927
H1990 Oak Hill 1620 273500 592000 -0.773
H2594 Old Town 600 519000 278000 0.624
H2921 Lakeview 5710 3730500 2043000 0.602
H0887 Lakeview 1560 252500 459000 -0.597
H0180 Old Town 1860 219500 360000 -0.496
H1476 Lakeview 1070 217500 352000 -0.481
known corrupted sales caught: 8 of 8
  1. Load and prepare. Read the CSV. Add years_since_2022 with pd.to_datetime and .dt.days / 365.25. Build X and y. Cast neighborhood to category.

  2. Build the two models. Write a helper log_target(regressor) that wraps a regressor in TransformedTargetRegressor(func=np.log, inverse_func=np.exp). Wrap the linear pipeline and the gradient boosting model with it.

  3. Predict out of fold. Call cross_val_predict(model, X, y, cv=cv) for each model. The result has one prediction per sale, in the original row order.

  4. Score and choose. Compute the four metrics for each model in a DataFrame. Pick the model with the lower RMSE.

  5. Compute residuals and the robust spread. resid = np.log(y) - np.log(pred). The robust standard deviation is 1.4826 * np.median(np.abs(resid - np.median(resid))). For normal data, this estimates the same value as the ordinary standard deviation; outliers barely move it.

  6. Flag and report. Build a boolean mask for the 3.5-sigma rule. Select the flagged rows, add the estimate and the residual, and sort by the absolute residual.

  7. Measure the catch. Count how many flagged ids are in the list of eight known corrupted sales.

  8. Plot. Scatter the log residuals against the log of the estimates in gray, and the flagged sales on top in a strong color. Draw the two threshold lines.

  9. Add the asserts and run the script. Compare your report with the expected report.

A skeleton to start from:

valuation_check.py (starter)
# valuation_check.py: flag house sales whose price is far from a model estimate.
import numpy as np
import pandas as pd
KNOWN_BAD = [
"H0537", "H0542", "H0751", "H0914", "H2277", "H0887", "H0957", "H1990"
]
# --- Load and prepare ---------------------------------------------------
# TODO: read data/houses.csv, add years_since_2022, build X and y
# --- Models ---------------------------------------------------------------
# TODO: log_target(), the linear pipeline and gradient boosting
# --- Out-of-fold predictions and metrics ---------------------------------
# TODO: cross_val_predict for each model; a metrics table; choose a model
# --- Flags ----------------------------------------------------------------
# TODO: residuals, robust sd, 3.5-sigma mask, report table, catch count
# --- Plot and self-checks -------------------------------------------------
# TODO: residuals against fitted, flagged sales highlighted; asserts
Criterion Points Full points when
Runs as a script 2 python valuation_check.py runs with no error or warning and prints the report
Leak-free valuation 3 Every estimate is out of fold; all preprocessing sits inside the models
Log target 2 Both models use TransformedTargetRegressor; metrics are in USD
Model comparison 2 MAE, RMSE, R² and MAPE for both models in one table; the choice follows the stated rule
Robust flag rule 3 The spread is a robust statistic; the threshold is a named constant; the known list is not used to build the flags
Report 2 The flagged table is sorted by severity and readable; the catch count is correct
Plot 1 Residuals against fitted values, flags highlighted, threshold lines, labeled axes
Self-checks 1 The asserts of requirement 9 are present and pass
Total 16 13 or more: you are ready for module 36
  1. Robust training. The corrupted sales also train the models in the other folds. Fit HistGradientBoostingRegressor(loss="absolute_error") instead, and compare the robust spread and the flags.
  2. Precision of the check. Four flagged sales are not in the known list. Look at them (size, age, neighborhood). Are they genuine extremes, such as the 5,710 sqft Lakeview house, or plausible errors? Write one sentence for each.
  3. Threshold trade-off. Print the number of flags and the number of known sales caught for thresholds 2.5, 3, 3.5 and 4. Which threshold would you give an audit team with time for 20 reviews a month?
  4. Neighborhood view. Print the median absolute log residual per neighborhood. Where is the model least certain?
  5. Second opinion in USD. Add a column with the difference between price and estimate in USD, and sort the table by it. Does the order change? Which order fits a lender that cares about money at risk?

Try the project yourself first. Then compare your script with this one. Your names can differ; your numbers should not.

Reference solution
valuation_check.py (part 1: models and metrics)
# valuation_check.py: flag house sales whose price is far from a model estimate.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import (
mean_absolute_error,
mean_absolute_percentage_error,
r2_score,
root_mean_squared_error,
)
from sklearn.model_selection import KFold, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
KNOWN_BAD = [
"H0537", "H0542", "H0751", "H0914", "H2277", "H0887", "H0957", "H1990"
]
THRESHOLD = 3.5 # flag beyond this many robust standard deviations
# --- Load and prepare ---------------------------------------------------
houses = pd.read_csv("data/houses.csv")
houses["years_since_2022"] = (
pd.to_datetime(houses["sold_date"]) - pd.Timestamp("2022-01-01")
).dt.days / 365.25
X = houses.drop(columns=["house_id", "sold_date", "price"])
X["neighborhood"] = X["neighborhood"].astype("category")
y = houses["price"]
cat_cols = ["neighborhood"]
num_cols = [c for c in X.columns if c not in cat_cols]
# --- Models ---------------------------------------------------------------
def log_target(regressor) -> TransformedTargetRegressor:
"""Fit on log price, predict in USD."""
return TransformedTargetRegressor(
regressor=regressor, func=np.log, inverse_func=np.exp
)
preprocess = ColumnTransformer(
[
("cat", OneHotEncoder(drop="first"), cat_cols),
(
"num",
make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
num_cols,
),
]
)
models = {
"log linear": log_target(make_pipeline(preprocess, LinearRegression())),
"log boosting": log_target(HistGradientBoostingRegressor(random_state=42)),
}
# --- Out-of-fold predictions and metrics ---------------------------------
cv = KFold(n_splits=5, shuffle=True, random_state=42)
oof = {name: cross_val_predict(model, X, y, cv=cv) for name, model in models.items()}
metrics = pd.DataFrame(
{
name: {
"MAE": mean_absolute_error(y, pred),
"RMSE": root_mean_squared_error(y, pred),
"R2": r2_score(y, pred),
"MAPE": mean_absolute_percentage_error(y, pred),
}
for name, pred in oof.items()
}
).T
metrics.index.name = "model"
print(metrics.round({"MAE": 0, "RMSE": 0, "R2": 3, "MAPE": 3}).astype(
{"MAE": int, "RMSE": int}
))
chosen = metrics["RMSE"].idxmin()
print("chosen model:", chosen)
Output
MAE RMSE R2 MAPE
model
log linear 61673 102525 0.897 0.128
log boosting 55802 97310 0.907 0.114
chosen model: log boosting
valuation_check.py (part 2: flags and report)
# --- Flags ----------------------------------------------------------------
estimate = oof[chosen]
resid = np.log(y) - np.log(estimate)
center = np.median(resid)
robust_sd = 1.4826 * np.median(np.abs(resid - center))
flagged = np.abs(resid - center) > THRESHOLD * robust_sd
print(f"robust sd of log residuals: {robust_sd:.3f}")
print(f"flagged sales: {flagged.sum()} of {len(houses)}")
report = houses.loc[flagged, ["house_id", "neighborhood", "sqft", "price"]].assign(
estimate=estimate[flagged].round(-3).astype(int),
log_resid=resid[flagged].round(3),
)
report = report.sort_values("log_resid", key=np.abs, ascending=False)
print(report.to_string(index=False))
caught = report["house_id"].isin(KNOWN_BAD).sum()
print(f"known corrupted sales caught: {caught} of {len(KNOWN_BAD)}")
Output
robust sd of log residuals: 0.137
flagged sales: 12 of 3000
house_id neighborhood sqft price estimate log_resid
H0542 Maple Grove 3770 2660000 856000 1.134
H0914 Cedar Park 1730 719500 258000 1.024
H0751 Oak Hill 1370 1431000 519000 1.014
H2277 Old Town 1080 905500 333000 1.000
H0537 Westfield 1040 500500 191000 0.962
H0957 Old Town 1160 117500 297000 -0.927
H1990 Oak Hill 1620 273500 592000 -0.773
H2594 Old Town 600 519000 278000 0.624
H2921 Lakeview 5710 3730500 2043000 0.602
H0887 Lakeview 1560 252500 459000 -0.597
H0180 Old Town 1860 219500 360000 -0.496
H1476 Lakeview 1070 217500 352000 -0.481
known corrupted sales caught: 8 of 8
valuation_check.py (part 3: plot and self-checks)
# --- Plot and self-checks -------------------------------------------------
fitted = np.log(estimate)
fig, ax = plt.subplots(figsize=(9, 5))
ax.scatter(
fitted[~flagged], resid[~flagged], s=6, color="tab:gray", alpha=0.4, label="others"
)
ax.scatter(fitted[flagged], resid[flagged], s=30, color="tab:red", label="flagged")
for sign in (-1, 1):
limit = center + sign * THRESHOLD * robust_sd
ax.axhline(limit, color="tab:red", linestyle="--", linewidth=1)
ax.axhline(center, color="black", linewidth=1)
ax.set(
xlabel="Out-of-fold estimate (log price)",
ylabel="Log residual",
title="Valuation check: price against out-of-fold estimate",
)
ax.legend()
plt.show()
assert (metrics["R2"] > 0.85).all()
assert caught >= 6
assert flagged.mean() < 0.02
Gray points form a band of log residuals around zero across all estimate levels. Twelve red points lie outside two dashed threshold lines at about plus and minus 0.48: seven above the band, up to 1.1, and five below it, down to about minus 0.93.
Out-of-fold log residuals of the gradient boosting model, with the 3.5 robust-sigma thresholds and the 12 flagged sales.

Run it from the project folder:

Terminal
python valuation_check.py

How it works:

  1. Preparation. years_since_2022 turns the date into a number, so the models can use the price drift over time that exercise M35-X01 measured. The category dtype lets gradient boosting split on the neighborhood directly; the linear pipeline one-hot encodes the same column.
  2. Out-of-fold predictions. cross_val_predict fits each model five times, each time on four folds, and predicts the fifth. Every sale gets exactly one estimate from a model that never saw its price. All preprocessing sits inside the models, so it is refitted inside each fold too.
  3. Metrics. Gradient boosting wins on all four metrics, so it does the audit. Both models are scored in USD, because TransformedTargetRegressor back-transforms the predictions.
  4. Robust spread. The ordinary standard deviation of the residuals includes the corrupted sales and grows with them. The median absolute deviation times 1.4826 estimates the spread of the normal part only, so the threshold is not pushed out by the outliers it should catch.
  5. Flags. At 3.5 robust standard deviations, 12 sales (0.4%) are flagged, and all 8 corrupted sales are among them. The 4 other flags are H2594 (a 600 sqft Old Town house that sold far above its estimate), H2921 (5,710 sqft in Lakeview, the largest and most expensive house in the data), and H0180 (Old Town) and H1476 (Lakeview), both sold well below their estimates. H0180 also topped the residual list in Example 4 of the lesson. These are the sales an auditor would review by hand; stretch goal 2 asks you to do that.
  6. Plot. The band of gray points is even across all price levels, which confirms that the log target was right. The red points sit well outside the dashed thresholds.

Alternative: use IsolationForest or LocalOutlierFactor on the features and the price together (module 39). The residual approach used here is easier to explain to an auditor: “the price is 3 times what comparable houses sold for”.