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:
- estimates the price of every one of the 3,000 sales with a model that never saw that sale;
- compares a transparent model (linear regression on log price) with an accurate one (gradient boosting on log price);
- 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.
Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”Your script must:
- Load the data, add
years_since_2022, and convertneighborhoodto the pandascategorydtype so gradient boosting can read it directly. - Build two models, both on log price with
TransformedTargetRegressor: a linear regression after aColumnTransformer(one-hot neighborhood withdrop="first", median imputation, scaling), and aHistGradientBoostingRegressor(random_state=42). - Produce out-of-fold predictions for all 3,000 sales with
cross_val_predictandKFold(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. - 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.
- Compute the log residual of every sale for the chosen model. Measure the spread with a robust standard deviation: the median absolute deviation from the median residual. A robust statistic is not inflated by the very outliers you are hunting.
- 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.
- Print how many of the eight known corrupted sales were flagged.
- Draw a residuals-against-fitted plot with the flagged sales highlighted.
- End with
assertchecks: 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:
MAE RMSE R2 MAPEmodellog linear 61673 102525 0.897 0.128log boosting 55802 97310 0.907 0.114chosen model: log boostingrobust sd of log residuals: 0.137flagged sales: 12 of 3000house_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.481known corrupted sales caught: 8 of 8Step plan
Section titled “Step plan”-
Load and prepare. Read the CSV. Add
years_since_2022withpd.to_datetimeand.dt.days / 365.25. BuildXandy. Castneighborhoodtocategory. -
Build the two models. Write a helper
log_target(regressor)that wraps a regressor inTransformedTargetRegressor(func=np.log, inverse_func=np.exp). Wrap the linear pipeline and the gradient boosting model with it. -
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. -
Score and choose. Compute the four metrics for each model in a DataFrame. Pick the model with the lower RMSE.
-
Compute residuals and the robust spread.
resid = np.log(y) - np.log(pred). The robust standard deviation is1.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. -
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.
-
Measure the catch. Count how many flagged ids are in the list of eight known corrupted sales.
-
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.
-
Add the asserts and run the script. Compare your report with the expected report.
A skeleton to start from:
# valuation_check.py: flag house sales whose price is far from a model estimate.import numpy as npimport 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; assertsRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- 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. - 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.
- 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?
- Neighborhood view. Print the median absolute log residual per neighborhood. Where is the model least certain?
- 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?
Reference solution
Section titled “Reference solution”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: flag house sales whose price is far from a model estimate.import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformer, TransformedTargetRegressorfrom sklearn.ensemble import HistGradientBoostingRegressorfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import ( mean_absolute_error, mean_absolute_percentage_error, r2_score, root_mean_squared_error,)from sklearn.model_selection import KFold, cross_val_predictfrom sklearn.pipeline import make_pipelinefrom 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.25X = 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() }).Tmetrics.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) MAE RMSE R2 MAPEmodellog linear 61673 102525 0.897 0.128log boosting 55802 97310 0.907 0.114chosen model: log boosting# --- 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_sdprint(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)}")robust sd of log residuals: 0.137flagged sales: 12 of 3000house_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.481known corrupted sales caught: 8 of 8# --- 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 >= 6assert flagged.mean() < 0.02
Run it from the project folder:
python valuation_check.pyHow it works:
- Preparation.
years_since_2022turns the date into a number, so the models can use the price drift over time that exercise M35-X01 measured. Thecategorydtype lets gradient boosting split on the neighborhood directly; the linear pipeline one-hot encodes the same column. - Out-of-fold predictions.
cross_val_predictfits 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. - Metrics. Gradient boosting wins on all four metrics, so it does the audit. Both models are scored in USD, because
TransformedTargetRegressorback-transforms the predictions. - 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.
- 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.
- 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”.