35. Regression — Exercises
These exercises practice every idea of the Regression lesson. Most of them use the 3,000 house sales in data/houses.csv; a few use scikit-learn’s bundled diabetes data.
How to work:
- Copy the setup block below into the top of your script. It loads the houses, splits them once and defines
make_preprocessor(), exactly as in the lesson. - Copy the starter code under it and replace each to-do comment with your code.
- Run the script and compare your output with the expected output.
- Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. They pass silently when the result is right.
import numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformer, TransformedTargetRegressorfrom 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_score, train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
houses = pd.read_csv("data/houses.csv")X = houses.drop(columns=["house_id", "sold_date", "price"])y = houses["price"]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42)cat_cols = ["neighborhood"]num_cols = [c for c in X.columns if c not in cat_cols]cv = KFold(n_splits=5, shuffle=True, random_state=42)
def make_preprocessor(scale: bool = True) -> ColumnTransformer: """One-hot encode the neighborhood, impute (and scale) the numbers.""" num_steps = [SimpleImputer(strategy="median")] if scale: num_steps.append(StandardScaler()) return ColumnTransformer( [ ("cat", OneHotEncoder(drop="first"), cat_cols), ("num", make_pipeline(*num_steps), num_cols), ], verbose_feature_names_out=False, )Warm-up
Section titled “Warm-up”M35-W01 · Beat the baseline
Section titled “M35-W01 · Beat the baseline”Before any real model, measure two baselines on the test set: DummyRegressor(strategy="mean") and DummyRegressor(strategy="median"). Fit each on the training set and print the constant it predicts and its test MAE.
mean: predicts 474,008, test MAE 215,799median: predicts 373,500, test MAE 202,090from sklearn.dummy import DummyRegressor
for strategy in ["mean", "median"]: # TODO: fit a DummyRegressor with this strategy on the training set # TODO: print the constant prediction and the test MAE passHint 1
DummyRegressor(strategy=strategy).fit(X_train, y_train) ignores the features. predict(X_test) returns the same number for every row.
Hint 2
Use mean_absolute_error(y_test, pred). Format with :>6 for the name and :,.0f for the numbers.
Solution
from sklearn.dummy import DummyRegressor
maes = {}for strategy in ["mean", "median"]: dummy = DummyRegressor(strategy=strategy).fit(X_train, y_train) pred = dummy.predict(X_test) maes[strategy] = mean_absolute_error(y_test, pred) print(f"{strategy:>6}: predicts {pred[0]:,.0f}, test MAE {maes[strategy]:,.0f}")assert maes["median"] < maes["mean"]assert maes["mean"] == mean_absolute_error(y_test, np.full(len(y_test), y_train.mean())) mean: predicts 474,008, test MAE 215,799median: predicts 373,500, test MAE 202,090How it works:
- Each dummy model learns one number from
y_train: the mean or the median. - It predicts that number for every test house, whatever the features say.
- The median baseline has the lower MAE. The median is the constant that minimizes the absolute error, while the mean minimizes the squared error. With right-skewed prices, the two differ by about 100,000 USD.
Alternative: compute the baselines without scikit-learn: np.mean(np.abs(y_test - y_train.median())). The dummy models are still useful, because they fit into the same pipelines and comparison tables as real models.
M35-W02 · Compute the metrics by hand
Section titled “M35-W02 · Compute the metrics by hand”Six test houses have these true prices and predictions (USD). Compute MAE, RMSE, R² and MAPE with NumPy only, print them on one line, and assert that each one equals scikit-learn’s result.
- true: 245,000, 310,000, 388,000, 452,000, 615,000, 980,000
- predicted: 262,000, 298,000, 401,000, 430,000, 660,000, 905,000
MAE 30,667 RMSE 38,158 R² 0.976 MAPE 5.7%y_true = np.array([245_000, 310_000, 388_000, 452_000, 615_000, 980_000])y_pred = np.array([262_000, 298_000, 401_000, 430_000, 660_000, 905_000])# TODO: compute mae, rmse, r2 and mape with NumPy# TODO: print them and check them against scikit-learnHint 1
Start with err = y_true - y_pred. Every metric is built from err.
Hint 2
R² is 1 - SS_res / SS_tot, with SS_res = np.sum(err**2) and SS_tot = np.sum((y_true - y_true.mean()) ** 2). MAPE is np.mean(np.abs(err / y_true)).
Solution
y_true = np.array([245_000, 310_000, 388_000, 452_000, 615_000, 980_000])y_pred = np.array([262_000, 298_000, 401_000, 430_000, 660_000, 905_000])err = y_true - y_predmae = np.mean(np.abs(err))rmse = np.sqrt(np.mean(err**2))r2 = 1 - np.sum(err**2) / np.sum((y_true - y_true.mean()) ** 2)mape = np.mean(np.abs(err / y_true))print(f"MAE {mae:,.0f} RMSE {rmse:,.0f} R² {r2:.3f} MAPE {mape:.1%}")assert np.isclose(mae, mean_absolute_error(y_true, y_pred))assert np.isclose(rmse, root_mean_squared_error(y_true, y_pred))assert np.isclose(r2, r2_score(y_true, y_pred))assert np.isclose(mape, mean_absolute_percentage_error(y_true, y_pred))MAE 30,667 RMSE 38,158 R² 0.976 MAPE 5.7%How it works:
errholds the six residuals.np.absand**2turn them into sizes.- RMSE is the square root of the mean squared residual, so it is in USD like MAE.
- R² compares the squared residuals with the squared distances from the mean of the true prices.
- The format spec
:.1%multiplies the MAPE fraction by 100 and adds a percent sign.
Alternative: np.linalg.norm(err) / np.sqrt(len(err)) also gives the RMSE, because the norm of a vector is the square root of its sum of squares (module 32).
M35-W03 · Predict the output: one big miss
Section titled “M35-W03 · Predict the output: one big miss”Predict the output: two models predict the same four houses. Model A misses each one by 10,000 USD. Model B is exact on three houses and misses the fourth by 40,000 USD. Write down the MAE and RMSE of each model before you run the code.
Acceptance criteria:
- Write your prediction for both lines before you run the code.
- Run the code. Your prediction matches the Output in the solution.
- Explain in one sentence why the two RMSE values differ although the MAE values are equal.
y_true = np.array([300_000, 400_000, 500_000, 600_000])pred_a = y_true + 10_000pred_b = y_true + np.array([0, 0, 0, 40_000])for name, pred in [("A", pred_a), ("B", pred_b)]: mae = mean_absolute_error(y_true, pred) rmse = root_mean_squared_error(y_true, pred) print(f"model {name}: MAE {mae:,.0f} RMSE {rmse:,.0f}")# TODO: write your prediction for both lines before you run itHint 1
MAE adds the sizes of the errors: 4 × 10,000 and 1 × 40,000 have the same sum.
Hint 2
RMSE squares first. 40,000² is 16 times 10,000², not 4 times.
Solution
y_true = np.array([300_000, 400_000, 500_000, 600_000])pred_a = y_true + 10_000pred_b = y_true + np.array([0, 0, 0, 40_000])for name, pred in [("A", pred_a), ("B", pred_b)]: mae = mean_absolute_error(y_true, pred) rmse = root_mean_squared_error(y_true, pred) print(f"model {name}: MAE {mae:,.0f} RMSE {rmse:,.0f}")assert mean_absolute_error(y_true, pred_a) == mean_absolute_error(y_true, pred_b)assert root_mean_squared_error(y_true, pred_b) == 2 * root_mean_squared_error( y_true, pred_a)model A: MAE 10,000 RMSE 10,000model B: MAE 10,000 RMSE 20,000How it works:
- Both models have a total absolute error of 40,000 USD over 4 houses, so both MAE values are 10,000.
- Model A’s squared errors are four times 10,000², with a mean of 10,000², so its RMSE is 10,000.
- Model B’s squared errors are 0, 0, 0 and 40,000² = 1.6 billion. The mean is 400 million, and its square root is 20,000.
- RMSE grows when the same total error is concentrated in fewer houses. That is why it punishes one big miss.
M35-W04 · Fix the bug: the R² is wrong
Section titled “M35-W04 · Fix the bug: the R² is wrong”Fix the bug: a teammate fits a linear model on house size alone and reports its R². The number is far too low. Find the bug, fix it, and print the correct R².
wrong order: 0.025R² from size alone: 0.529model = LinearRegression().fit(X_train[["sqft"]], y_train)pred = model.predict(X_test[["sqft"]])print(f"R² from size alone: {r2_score(pred, y_test):.3f}") # bug# TODO: fix the call so the R² is correctHint 1
Look at the order of the arguments. Read the signature: r2_score(y_true, y_pred).
Hint 2
R² divides by the variance of the first argument. The predictions vary less than the true prices.
Solution
model = LinearRegression().fit(X_train[["sqft"]], y_train)pred = model.predict(X_test[["sqft"]])wrong = r2_score(pred, y_test)right = r2_score(y_test, pred)print(f"wrong order: {wrong:.3f}")print(f"R² from size alone: {right:.3f}")assert right > wrongassert np.isclose(right, model.score(X_test[["sqft"]], y_test))wrong order: 0.025R² from size alone: 0.529How it works:
- Every scikit-learn metric takes the true values first and the predictions second.
- MAE and RMSE are symmetric, so a swapped order goes unnoticed there. R² is not symmetric: it divides by the spread of the first argument around its mean.
- The predictions of a regression vary less than the true values, so the swapped call divides by a smaller number and gives a lower R².
model.score(X, y)computes R² with the right order, so the last assert checks the fix.
Alternative: pass the arguments by name: r2_score(y_true=y_test, y_pred=pred). A swap is then visible at a glance.
M35-W05 · Interpret: price per square foot
Section titled “M35-W05 · Interpret: price per square foot”Interpret a result: fit LinearRegression on sqft alone. Print the slope as “USD per 100 sqft”, the intercept, and the predicted price of a 1,500 sqft house. Then answer: why is the intercept negative, and can you trust it?
slope: 32,309 USD per 100 sqftintercept: -127,730 USD1,500 sqft house: 356,902 USDmodel = LinearRegression().fit(X_train[["sqft"]], y_train)# TODO: print the slope per 100 sqft, the intercept and the prediction for 1,500 sqftHint 1
The slope is model.coef_[0] (USD per square foot) and the intercept is model.intercept_.
Hint 2
model.predict needs a 2-D input with the same column name: pd.DataFrame({"sqft": [1_500]}).
Solution
model = LinearRegression().fit(X_train[["sqft"]], y_train)slope = model.coef_[0]house = pd.DataFrame({"sqft": [1_500]})pred = model.predict(house)[0]print(f"slope: {slope * 100:,.0f} USD per 100 sqft")print(f"intercept: {model.intercept_:,.0f} USD")print(f"1,500 sqft house: {pred:,.0f} USD")assert np.isclose(pred, model.intercept_ + 1_500 * slope)assert model.intercept_ < 0slope: 32,309 USD per 100 sqftintercept: -127,730 USD1,500 sqft house: 356,902 USDHow it works:
- The slope is the change in the predicted price per square foot. Multiplying by 100 gives a unit people can picture.
- The intercept is the prediction at 0 sqft. The data has no house below 550 sqft, so this is an extrapolation far outside the data. It only anchors the line and has no meaning as a price.
- A negative intercept appears because the line is steep: it must drop below 0 to pass through the cloud of small and large houses.
- A DataFrame with the column name
sqftavoids scikit-learn’s warning about missing feature names.
Answer: the intercept is negative because the straight line through the data is steep and 0 sqft lies far outside the data. Do not trust it as a price; trust the predictions only within the range of sizes the model has seen.
M35-W06 · Predict the output: a tree stump
Section titled “M35-W06 · Predict the output: a tree stump”Predict the output: a depth-1 tree is trained on six houses. Predict the three printed prices before you run the code. The third house is far larger than any training house.
Acceptance criteria:
- Write your three predicted prices before you run the code.
- Run the code. Your prediction matches the Output in the solution.
- Explain why the 5,000 sqft house gets the price it gets.
from sklearn.tree import DecisionTreeRegressor
sizes = pd.DataFrame({"sqft": [800, 900, 1_000, 2_000, 2_100, 2_200]})prices = np.array([200_000, 220_000, 210_000, 500_000, 520_000, 540_000])stump = DecisionTreeRegressor(max_depth=1, random_state=42).fit(sizes, prices)new = pd.DataFrame({"sqft": [950, 2_050, 5_000]})print(stump.predict(new))# TODO: write your prediction before you run itHint 1
The best single split separates the three small houses from the three large ones.
Hint 2
Each leaf predicts the mean price of its training houses. A tree never predicts outside the range of its leaf values.
Solution
from sklearn.tree import DecisionTreeRegressor
sizes = pd.DataFrame({"sqft": [800, 900, 1_000, 2_000, 2_100, 2_200]})prices = np.array([200_000, 220_000, 210_000, 500_000, 520_000, 540_000])stump = DecisionTreeRegressor(max_depth=1, random_state=42).fit(sizes, prices)new = pd.DataFrame({"sqft": [950, 2_050, 5_000]})print(stump.predict(new))print("threshold:", stump.tree_.threshold[0])assert list(stump.predict(new)) == [210_000, 520_000, 520_000][210000. 520000. 520000.]threshold: 1500.0How it works:
- The split with the lowest squared error puts 800–1,000 sqft in one leaf and 2,000–2,200 sqft in the other. The threshold is the midpoint, 1,500.
- The left leaf predicts the mean of 200k, 220k and 210k: 210,000. The right leaf predicts 520,000.
- The 5,000 sqft house falls in the right leaf, so it gets 520,000, the same as a 2,050 sqft house. Trees cannot extrapolate: they only return averages of training prices.
M35-W07 · Fix the bug: MAPE as a percentage
Section titled “M35-W07 · Fix the bug: MAPE as a percentage”Fix the bug: the report below says that the linear price model is off by 0.2% on a typical house. That is far too good to be true. Fix the report line.
MAPE: 23.7%model = make_pipeline(make_preprocessor(), LinearRegression()).fit(X_train, y_train)mape = mean_absolute_percentage_error(y_test, model.predict(X_test))print(f"MAPE: {mape:.1f}%") # bug# TODO: fix the report lineHint 1
Print mape without formatting. Is it 23.7 or 0.237?
Hint 2
mean_absolute_percentage_error returns a fraction. The format spec :.1% multiplies by 100 for you.
Solution
model = make_pipeline(make_preprocessor(), LinearRegression()).fit(X_train, y_train)mape = mean_absolute_percentage_error(y_test, model.predict(X_test))print(f"MAPE: {mape:.1%}")assert 0 < mape < 1MAPE: 23.7%How it works:
- Despite its name,
mean_absolute_percentage_errorreturns the mean of|error / true|, a fraction such as 0.237. :.1fprinted that fraction with a percent sign glued on, which made the error look 100 times smaller.:.1%multiplies by 100 and adds the sign: 0.237 becomes23.7%.
Alternative: print(f"MAPE: {mape * 100:.1f}%") gives the same line.
M35-W08 · KNN regression by hand
Section titled “M35-W08 · KNN regression by hand”Write the code: take the first 8 training houses (sqft and price). Predict the price of a 1,750 sqft house as the mean price of its 3 nearest neighbors by size, using NumPy only. Then check the result with KNeighborsRegressor(n_neighbors=3).
training sizes: [2830 1800 1160 790 1520 3430 1560 1190]nearest sizes: [1800 1560 1520]by hand: 310,833sklearn: 310,833from sklearn.neighbors import KNeighborsRegressor
sizes = X_train["sqft"].to_numpy()[:8]prices = y_train.to_numpy()[:8]# TODO: distances from 1,750 to each size# TODO: indices of the 3 smallest distances, then the mean of their prices# TODO: check with KNeighborsRegressorHint 1
The distance in one dimension is np.abs(sizes - 1_750).
Hint 2
np.argsort(distances)[:3] gives the positions of the 3 nearest houses.
Solution
from sklearn.neighbors import KNeighborsRegressor
sizes = X_train["sqft"].to_numpy()[:8]prices = y_train.to_numpy()[:8]distances = np.abs(sizes - 1_750)nearest = np.argsort(distances)[:3]by_hand = prices[nearest].mean()print("training sizes:", sizes)print("nearest sizes: ", sizes[nearest])print(f"by hand: {by_hand:,.0f}")
knn = KNeighborsRegressor(n_neighbors=3).fit(sizes.reshape(-1, 1), prices)by_sklearn = knn.predict(np.array([[1_750]]))[0]print(f"sklearn: {by_sklearn:,.0f}")assert np.isclose(by_hand, by_sklearn)training sizes: [2830 1800 1160 790 1520 3430 1560 1190]nearest sizes: [1800 1560 1520]by hand: 310,833sklearn: 310,833How it works:
- With one feature, the Euclidean distance is the absolute difference in size.
np.argsortsorts the positions by distance. The first three are the neighbors.- The prediction is the plain mean of their prices.
KNeighborsRegressorneeds a 2-D input, soreshape(-1, 1)turns the sizes into one column.
Alternative: KNeighborsRegressor(n_neighbors=3, weights="distance") gives closer neighbors more weight. It is often better when the neighbors are at very different distances.
M35-C01 · Linear regression from scratch on the diabetes data
Section titled “M35-C01 · Linear regression from scratch on the diabetes data”Write the code: load load_diabetes(as_frame=True) (its features are already centered and scaled), split it with test_size=0.25, random_state=42, and fit a linear regression with np.linalg.lstsq on a design matrix with a column of ones. Check that LinearRegression gives the same intercept and coefficients, and print the test R² of your weights.
intercept: 151.67 (sklearn 151.67)bmi and s5 weights: [532. 695.8]test R²: 0.485from sklearn.datasets import load_diabetes
data = load_diabetes(as_frame=True)Xd_train, Xd_test, yd_train, yd_test = train_test_split( data.data, data.target, test_size=0.25, random_state=42)# TODO: design matrix with a column of ones, then lstsq# TODO: compare with LinearRegression# TODO: predict the test set with your weights and print R²Hint 1
A = np.column_stack([np.ones(len(Xd_train)), Xd_train]). Then w, *_ = np.linalg.lstsq(A, yd_train).
Hint 2
w[0] is the intercept and w[1:] the ten coefficients. A test prediction is w[0] + Xd_test.to_numpy() @ w[1:].
Solution
from sklearn.datasets import load_diabetes
data = load_diabetes(as_frame=True)Xd_train, Xd_test, yd_train, yd_test = train_test_split( data.data, data.target, test_size=0.25, random_state=42)A = np.column_stack([np.ones(len(Xd_train)), Xd_train])w, *_ = np.linalg.lstsq(A, yd_train.to_numpy())ols = LinearRegression().fit(Xd_train, yd_train)pred = w[0] + Xd_test.to_numpy() @ w[1:]print(f"intercept: {w[0]:.2f} (sklearn {ols.intercept_:.2f})")print("bmi and s5 weights:", w[1:][[2, 8]].round(1))print(f"test R²: {r2_score(yd_test, pred):.3f}")assert np.allclose(w[1:], ols.coef_)assert np.isclose(w[0], ols.intercept_)intercept: 151.67 (sklearn 151.67)bmi and s5 weights: [532. 695.8]test R²: 0.485How it works:
- The column of ones gives the intercept its own weight, so
lstsqsolves for all eleven numbers at once. lstsqminimizes the sum of squared residuals, which is exactly whatLinearRegressiondoes, so the weights agree.- The diabetes features are pre-scaled to small values, so the weights are large: they are per unit of a scaled feature, not per year or per BMI point.
- An R² near 0.49 is typical for this data: one year of disease progression is hard to predict from ten baseline numbers.
Alternative: solve the normal equations with np.linalg.solve(A.T @ A, A.T @ yd_train). It gives the same weights here, but lstsq is more stable when columns are nearly dependent.
M35-C02 · Errors by price band
Section titled “M35-C02 · Errors by price band”Interpret a result: fit the log-target linear model (TransformedTargetRegressor around the full pipeline). Split the test houses into four price bands with pd.qcut(y_test, 4) and print the MAE and MAPE per band. What happens to the error in USD and to the error in percent as prices rise?
MAE MAPEpriceQ1 35326.0 0.151Q2 44561.0 0.134Q3 64019.0 0.138Q4 117024.0 0.119model = TransformedTargetRegressor( regressor=make_pipeline(make_preprocessor(), LinearRegression()), func=np.log, inverse_func=np.exp,)# TODO: fit, predict the test set# TODO: build a DataFrame with the true price, the absolute error and the relative error# TODO: group by pd.qcut(y_test, 4, labels=["Q1", "Q2", "Q3", "Q4"]) and averageHint 1
The absolute error is (y_test - pred).abs(); the relative error divides it by y_test.
Hint 2
df.groupby(bands, observed=True)[["abs_err", "rel_err"]].mean() gives MAE and MAPE per band.
Solution
model = TransformedTargetRegressor( regressor=make_pipeline(make_preprocessor(), LinearRegression()), func=np.log, inverse_func=np.exp,)pred = model.fit(X_train, y_train).predict(X_test)errors = pd.DataFrame( {"abs_err": (y_test - pred).abs(), "rel_err": ((y_test - pred) / y_test).abs()})bands = pd.qcut(y_test, 4, labels=["Q1", "Q2", "Q3", "Q4"])by_band = errors.groupby(bands, observed=True).mean()by_band.columns = ["MAE", "MAPE"]print(by_band.round({"MAE": 0, "MAPE": 3}))assert by_band["MAE"].is_monotonic_increasingassert by_band["MAPE"].max() < 2 * by_band["MAPE"].min() MAE MAPEpriceQ1 35326.0 0.151Q2 44561.0 0.134Q3 64019.0 0.138Q4 117024.0 0.119How it works:
pd.qcutcuts the test prices at their quartiles, so each band holds about 187 houses.- The MAE grows steadily with the price: an expensive house has more USD to miss.
- The MAPE stays within a narrow range across the bands. A log model makes errors that are roughly proportional to the price, which is what the flat residual band in the lesson showed.
Answer: the error in USD grows several times from the cheapest to the most expensive band, while the error in percent stays in a narrow range. Report a percentage, or the MAE per band, when one MAE for all houses would mislead.
M35-C03 · Interpret: school rating and garage spaces
Section titled “M35-C03 · Interpret: school rating and garage spaces”Interpret a result: an agent asks what three more points of school rating and one more garage space are worth. Fit the log-price model with unscaled features, and print the percent effect of +3 school rating points and +1 garage space. Then print the value of each effect in USD for a house predicted at 400,000 USD.
+3 school_rating: +11.5%, about 45,843 USD at 400k+1 garage_spaces: +3.3%, about 13,232 USD at 400kmodel = make_pipeline(make_preprocessor(scale=False), LinearRegression())model.fit(X_train, np.log(y_train))# TODO: put the coefficients in a Series indexed by the feature names# TODO: percent effect = exp(coef * step) - 1# TODO: USD effect for a 400,000 USD houseHint 1
pd.Series(model[-1].coef_, index=model[0].get_feature_names_out()).
Hint 2
For +3 points, multiply the coefficient by 3 before np.exp. The USD effect is 400_000 * pct.
Solution
model = make_pipeline(make_preprocessor(scale=False), LinearRegression())model.fit(X_train, np.log(y_train))coefs = pd.Series(model[-1].coef_, index=model[0].get_feature_names_out())results = {}for feature, step in [("school_rating", 3), ("garage_spaces", 1)]: pct = np.exp(coefs[feature] * step) - 1 results[feature] = pct print(f"+{step} {feature}: {pct:+.1%}, about {400_000 * pct:,.0f} USD at 400k")assert 0.10 < results["school_rating"] < 0.12assert results["garage_spaces"] > 0+3 school_rating: +11.5%, about 45,843 USD at 400k+1 garage_spaces: +3.3%, about 13,232 USD at 400kHow it works:
- On a log target, a coefficient times a step is the change in log price.
np.exp(...) - 1turns it into a relative change. - Three points of school rating multiply the predicted price by about 1.11.
- The USD value depends on the price of the house: the same percent is more money on a more expensive house. That is how a multiplicative model works.
- Both numbers hold the other features fixed and describe association, not cause: better schools may also go with other features the data lacks.
Alternative: fit the model on the raw price with unscaled features. Each coefficient is then a fixed USD amount per unit, the same for a cheap and an expensive house, which fits these data less well (R² 0.79 instead of 0.90).
M35-C04 · Fix the bug: an unfair comparison
Section titled “M35-C04 · Fix the bug: an unfair comparison”Fix the bug: the code below “shows” that the log model has R² 0.892 and the price model 0.792. The comparison is not fair. Fix it so that both R² values are measured on the price scale, and print them.
price model R²: 0.792log model R²: 0.898 (on the log scale it was 0.892)price_model = make_pipeline(make_preprocessor(), LinearRegression()).fit(X_train, y_train)log_fit = make_pipeline(make_preprocessor(), LinearRegression())log_fit.fit(X_train, np.log(y_train))print(f"price model R²: {price_model.score(X_test, y_test):.3f}")print(f"log model R²: {log_fit.score(X_test, np.log(y_test)):.3f}") # bug# TODO: score the log model on the price scaleHint 1
The second R² compares log predictions with log prices. It answers a different question.
Hint 2
Wrap the log model in TransformedTargetRegressor(..., func=np.log, inverse_func=np.exp), fit it on y_train, and call .score(X_test, y_test).
Solution
price_model = make_pipeline(make_preprocessor(), LinearRegression())price_model.fit(X_train, y_train)log_model = TransformedTargetRegressor( regressor=make_pipeline(make_preprocessor(), LinearRegression()), func=np.log, inverse_func=np.exp,).fit(X_train, y_train)r2_price = price_model.score(X_test, y_test)r2_log = log_model.score(X_test, y_test)r2_log_scale = r2_score(np.log(y_test), np.log(log_model.predict(X_test)))print(f"price model R²: {r2_price:.3f}")print(f"log model R²: {r2_log:.3f} (on the log scale it was {r2_log_scale:.3f})")assert r2_log > r2_priceassert not np.isclose(r2_log, r2_log_scale)price model R²: 0.792log model R²: 0.898 (on the log scale it was 0.892)How it works:
- R² depends on the scale of the target. On the log scale, the variance of the target is very different, so the old number was not comparable.
TransformedTargetRegressor.scoreback-transforms the predictions and computes R² against the prices in USD.- The log model still wins on the price scale, so the conclusion survives, but now the evidence is sound. These two test scores only show the scale problem; to choose between the models, compare them with cross-validation on the training rows.
M35-C05 · Feature selection with LassoCV
Section titled “M35-C05 · Feature selection with LassoCV”Write the code: on the diabetes data (load_diabetes(as_frame=True), split with random_state=42), fit LassoCV(cv=5, random_state=42) after a StandardScaler. Print the chosen alpha, the test R², and the kept features sorted by the size of their coefficient (largest first). Which feature did Lasso drop?
alpha 0.106, test R² 0.487s1 -31.6s5 28.7bmi 25.3bp 18.1s2 14.8sex -11.3s4 11.0age 2.2s6 1.3dropped: ['s3']from sklearn.datasets import load_diabetesfrom sklearn.linear_model import LassoCV
data = load_diabetes(as_frame=True)Xd_train, Xd_test, yd_train, yd_test = train_test_split( data.data, data.target, test_size=0.25, random_state=42)# TODO: pipeline StandardScaler -> LassoCV, fit# TODO: alpha_, test R², kept features sorted by |coef|Hint 1
After fitting, the Lasso step is pipe[-1]. Its coef_ lines up with data.data.columns.
Hint 2
Make a Series, keep the non-zero entries, and sort with key=abs: coefs[coefs != 0].sort_values(key=abs, ascending=False).
Solution
from sklearn.datasets import load_diabetesfrom sklearn.linear_model import LassoCV
data = load_diabetes(as_frame=True)Xd_train, Xd_test, yd_train, yd_test = train_test_split( data.data, data.target, test_size=0.25, random_state=42)pipe = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=42))pipe.fit(Xd_train, yd_train)coefs = pd.Series(pipe[-1].coef_, index=data.data.columns)kept = coefs[coefs != 0].sort_values(key=abs, ascending=False)print(f"alpha {pipe[-1].alpha_:.3f}, test R² {pipe.score(Xd_test, yd_test):.3f}")print(kept.round(1).to_string())print("dropped:", coefs.index[coefs == 0].tolist())assert len(kept) == 9assert kept.index[0] == "s1"alpha 0.106, test R² 0.487s1 -31.6s5 28.7bmi 25.3bp 18.1s2 14.8sex -11.3s4 11.0age 2.2s6 1.3dropped: ['s3']How it works:
LassoCVtries 100 alphas with 5-fold cross-validation on the training set and refits with the best one.- The chosen
alphais small, so the penalty is weak and only one coefficient becomes exactly 0. sort_values(key=abs, ...)sorts by size and ignores the sign. Because the features are standardized, the sizes are comparable.- Lasso dropped
s3here, althoughs3survives at larger alphas in the lesson. With correlated blood measurements, which one Lasso drops can change with small changes in alpha. Do not read one zero as proof that a feature is useless.
M35-C06 · Fix the bug: Lasso on raw units
Section titled “M35-C06 · Fix the bug: Lasso on raw units”Fix the bug: a teammate runs Lasso(alpha=5) on the diabetes data in raw units (load_diabetes(as_frame=True, scaled=False)) and concludes that s5 (a strong predictor in every other analysis) is useless. Show the features kept without and with standardization, and fix the pipeline.
raw kept: ['age', 'bmi', 'bp', 's1', 's2', 's3', 's6']std kept: ['sex', 'bmi', 'bp', 's3', 's5']test R² raw 0.445, std 0.496from sklearn.datasets import load_diabetesfrom sklearn.linear_model import Lasso
raw = load_diabetes(as_frame=True, scaled=False)Xr_train, Xr_test, yr_train, yr_test = train_test_split( raw.data, raw.target, test_size=0.25, random_state=42)buggy = Lasso(alpha=5).fit(Xr_train, yr_train)print("raw kept:", raw.data.columns[buggy.coef_ != 0].tolist())# TODO: fix the model and print the kept features and both test R² valuesHint 1
Look at the spread of each feature with raw.data.std(). s5 spans about half a unit; s1 spans about 35.
Hint 2
make_pipeline(StandardScaler(), Lasso(alpha=5)) gives every feature the same scale before the penalty.
Solution
from sklearn.datasets import load_diabetesfrom sklearn.linear_model import Lasso
raw = load_diabetes(as_frame=True, scaled=False)Xr_train, Xr_test, yr_train, yr_test = train_test_split( raw.data, raw.target, test_size=0.25, random_state=42)buggy = Lasso(alpha=5).fit(Xr_train, yr_train)fixed = make_pipeline(StandardScaler(), Lasso(alpha=5)).fit(Xr_train, yr_train)kept_raw = raw.data.columns[buggy.coef_ != 0].tolist()kept_std = raw.data.columns[fixed[-1].coef_ != 0].tolist()print("raw kept:", kept_raw)print("std kept:", kept_std)r2_raw, r2_std = buggy.score(Xr_test, yr_test), fixed.score(Xr_test, yr_test)print(f"test R² raw {r2_raw:.3f}, std {r2_std:.3f}")assert "s5" not in kept_raw and "s5" in kept_stdraw kept: ['age', 'bmi', 'bp', 's1', 's2', 's3', 's6']std kept: ['sex', 'bmi', 'bp', 's3', 's5']test R² raw 0.445, std 0.496How it works:
s5has a standard deviation of about 0.5 in raw units. To have an effect, it needs a large coefficient, and the L1 penalty charges for every unit of coefficient.- Features with a large spread, such as
s1, get the same effect with a tiny coefficient that costs almost nothing. The penalty is unfair. - After
StandardScaler, every feature has standard deviation 1, so the penalty compares features by their predictive value, ands5survives. The test R² rises too.
M35-C07 · Tune Ridge on the houses
Section titled “M35-C07 · Tune Ridge on the houses”Write the code: build a log-target model with RidgeCV(alphas=np.logspace(-3, 3, 13)) after the scaled preprocessor. Print the chosen alpha, the test R² on the price scale and the test R² of the plain log-linear model. Interpret: does regularization help here?
chosen alpha: 0.0316RidgeCV R²: 0.8985OLS R²: 0.8985from sklearn.linear_model import RidgeCV
# TODO: TransformedTargetRegressor around make_pipeline(make_preprocessor(), RidgeCV(...))# TODO: the chosen alpha lives in model.regressor_[-1].alpha_# TODO: compare with the same model using LinearRegressionHint 1
Write a small function log_model(estimator) that returns the TransformedTargetRegressor, and call it twice.
Hint 2
After fit, TransformedTargetRegressor stores the fitted inner pipeline in regressor_ (with an underscore).
Solution
from sklearn.linear_model import RidgeCV
def log_model(estimator) -> TransformedTargetRegressor: return TransformedTargetRegressor( regressor=make_pipeline(make_preprocessor(), estimator), func=np.log, inverse_func=np.exp, )
ridge = log_model(RidgeCV(alphas=np.logspace(-3, 3, 13))).fit(X_train, y_train)plain = log_model(LinearRegression()).fit(X_train, y_train)alpha = ridge.regressor_[-1].alpha_print(f"chosen alpha: {alpha:.3g}")print(f"RidgeCV R²: {ridge.score(X_test, y_test):.4f}")print(f"OLS R²: {plain.score(X_test, y_test):.4f}")assert abs(ridge.score(X_test, y_test) - plain.score(X_test, y_test)) < 0.005chosen alpha: 0.0316RidgeCV R²: 0.8985OLS R²: 0.8985How it works:
RidgeCVtries the 13 alphas from 0.001 to 1,000 with efficient leave-one-out cross-validation on the training set.- The chosen alpha is small, and the two test R² values agree to four decimals. The test scores only report the result; a decision between Ridge and OLS must rest on cross-validated scores of the training rows, not on these test scores.
- With 2,250 rows and only 17 features, OLS is already stable, so the penalty has little to fix. Ridge pays off with few rows, many features or strongly correlated features, as on the diabetes data.
Answer: no, not here. The penalty barely changes the predictions. Keep Ridge in your toolbox for wide or small data sets, and for one-hot encodings with many categories.
M35-C08 · Choose and justify: a curved age effect
Section titled “M35-C08 · Choose and justify: a curved age effect”Choose a method and justify it: three of the five worst residuals in the lesson’s Example 4 were Old Town houses from the 1950s. Test whether a curved year_built effect helps. Add polynomial terms of year_built (only that column) to the log-linear model, for degrees 1 to 4. Compare the 5-fold CV RMSE on the log scale (use cv from the setup) and choose a degree. Justify the choice.
degree 1: CV RMSE 0.1725degree 2: CV RMSE 0.1634degree 3: CV RMSE 0.1633degree 4: CV RMSE 0.1628lowest: 4 chosen: 2from sklearn.preprocessing import PolynomialFeatures
others = [c for c in num_cols if c != "year_built"]for degree in [1, 2, 3, 4]: # TODO: a ColumnTransformer with three parts: # neighborhood -> OneHotEncoder(drop="first") # year_built -> StandardScaler, then PolynomialFeatures(degree, include_bias=False) # others -> SimpleImputer(median), then StandardScaler # TODO: cross_val_score on np.log(y_train) with neg_root_mean_squared_error passHint 1
year_built has no blanks, so it needs no imputer. Scale it before the powers to keep the numbers small.
Hint 2
Flip the sign of the scores: -scores.mean() is the CV RMSE. Prefer the simplest degree whose RMSE is within about 0.001 of the best.
Solution
from sklearn.preprocessing import PolynomialFeatures
others = [c for c in num_cols if c != "year_built"]cv_rmse = {}for degree in [1, 2, 3, 4]: pre = ColumnTransformer( [ ("cat", OneHotEncoder(drop="first"), cat_cols), ( "age", make_pipeline( StandardScaler(), PolynomialFeatures(degree, include_bias=False) ), ["year_built"], ), ( "num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), others, ), ] ) scores = cross_val_score( make_pipeline(pre, LinearRegression()), X_train, np.log(y_train), cv=cv, scoring="neg_root_mean_squared_error", ) cv_rmse[degree] = -scores.mean() print(f"degree {degree}: CV RMSE {cv_rmse[degree]:.4f}")best = min(cv_rmse, key=cv_rmse.get)chosen = min(d for d in cv_rmse if cv_rmse[d] - cv_rmse[best] < 0.001)print("lowest:", best, "chosen:", chosen)assert cv_rmse[2] < cv_rmse[1]assert chosen == 2degree 1: CV RMSE 0.1725degree 2: CV RMSE 0.1634degree 3: CV RMSE 0.1633degree 4: CV RMSE 0.1628lowest: 4 chosen: 2How it works:
- The
ColumnTransformersendsyear_builtthrough its own branch, so only that column gets powers. - Degree 2 lowers the CV RMSE clearly. A straight line in
year_builtwas missing a real curve in the age effect, as the residuals had suggested. - Degrees 3 and 4 improve the score only in the fourth decimal, which is within the noise of 5 folds.
- The rule “choose the simplest model within a small margin of the best” protects against overfitting the CV score itself.
Answer: degree 2. It gives almost all of the gain, and the higher degrees add columns without a meaningful improvement.
Alternative: SplineTransformer builds smooth piecewise curves that behave better at the edges than high-degree polynomials. A tree model learns the curve without any manual feature.
M35-C09 · Tune a tree with min_samples_leaf
Section titled “M35-C09 · Tune a tree with min_samples_leaf”Write the code: instead of limiting the depth, limit the leaf size. For min_samples_leaf in 1, 5, 10, 20 and 50, compute the 5-fold CV RMSE of a DecisionTreeRegressor(random_state=42) on price (unscaled preprocessor, cv from the setup). Print each score and the best value.
min_samples_leaf= 1: CV RMSE 154,209min_samples_leaf= 5: CV RMSE 145,065min_samples_leaf=10: CV RMSE 145,504min_samples_leaf=20: CV RMSE 158,019min_samples_leaf=50: CV RMSE 167,078best: 5from sklearn.tree import DecisionTreeRegressor
for leaf in [1, 5, 10, 20, 50]: # TODO: pipeline with make_preprocessor(scale=False) and the tree # TODO: CV RMSE with cross_val_score pass# TODO: print the best min_samples_leafHint 1
DecisionTreeRegressor(min_samples_leaf=leaf, random_state=42).
Hint 2
Store the scores in a dict and use min(scores, key=scores.get).
Solution
from sklearn.tree import DecisionTreeRegressor
scores = {}for leaf in [1, 5, 10, 20, 50]: tree = make_pipeline( make_preprocessor(scale=False), DecisionTreeRegressor(min_samples_leaf=leaf, random_state=42), ) res = cross_val_score( tree, X_train, y_train, cv=cv, scoring="neg_root_mean_squared_error" ) scores[leaf] = -res.mean() print(f"min_samples_leaf={leaf:>2}: CV RMSE {scores[leaf]:,.0f}")best_leaf = min(scores, key=scores.get)print("best:", best_leaf)assert scores[best_leaf] < scores[1]min_samples_leaf= 1: CV RMSE 154,209min_samples_leaf= 5: CV RMSE 145,065min_samples_leaf=10: CV RMSE 145,504min_samples_leaf=20: CV RMSE 158,019min_samples_leaf=50: CV RMSE 167,078best: 5How it works:
- With
min_samples_leaf=1, the tree grows until each leaf holds one house: it memorizes the training data and overfits. - Larger leaves average more houses, so each prediction is less noisy.
- Very large leaves are too coarse and underfit. The best value sits in between.
min_samples_leafadapts to the data: dense regions can split further than sparse ones, which a single depth limit cannot do.
Alternative: tune max_depth and min_samples_leaf together with GridSearchCV (module 37).
M35-C10 · Refactor: one loop for many models
Section titled “M35-C10 · Refactor: one loop for many models”Refactor: the code below repeats the same five lines for each model. Rewrite it as a dict of models and one loop that builds a DataFrame with the test MAE and R² of each model, sorted by MAE. The numbers must not change.
MAE R2modelknn 73125.0 0.878tree 84905.0 0.800linear 98861.0 0.792from sklearn.neighbors import KNeighborsRegressorfrom sklearn.tree import DecisionTreeRegressor
m1 = make_pipeline(make_preprocessor(), LinearRegression())m1.fit(X_train, y_train)p1 = m1.predict(X_test)print("linear", round(mean_absolute_error(y_test, p1)), round(r2_score(y_test, p1), 3))m2 = make_pipeline(make_preprocessor(), KNeighborsRegressor(n_neighbors=5))m2.fit(X_train, y_train)p2 = m2.predict(X_test)print("knn", round(mean_absolute_error(y_test, p2)), round(r2_score(y_test, p2), 3))m3 = make_pipeline(make_preprocessor(scale=False), DecisionTreeRegressor(max_depth=9, random_state=42))m3.fit(X_train, y_train)p3 = m3.predict(X_test)print("tree", round(mean_absolute_error(y_test, p3)), round(r2_score(y_test, p3), 3))# TODO: refactor into a dict of models and one loop that fills a DataFrameHint 1
Keys are the model names; values are the unfitted pipelines.
Hint 2
Collect one dict per model in a list, then pd.DataFrame(rows).set_index("model").sort_values("MAE").
Solution
from sklearn.neighbors import KNeighborsRegressorfrom sklearn.tree import DecisionTreeRegressor
models = { "linear": make_pipeline(make_preprocessor(), LinearRegression()), "knn": make_pipeline(make_preprocessor(), KNeighborsRegressor(n_neighbors=5)), "tree": make_pipeline( make_preprocessor(scale=False), DecisionTreeRegressor(max_depth=9, random_state=42), ),}rows = []for name, model in models.items(): pred = model.fit(X_train, y_train).predict(X_test) mae, r2 = mean_absolute_error(y_test, pred), r2_score(y_test, pred) rows.append({"model": name, "MAE": mae, "R2": r2})table = pd.DataFrame(rows).set_index("model").sort_values("MAE")print(table.round({"MAE": 0, "R2": 3}))assert list(table.index) == ["knn", "tree", "linear"] MAE R2modelknn 73125.0 0.878tree 84905.0 0.800linear 98861.0 0.792How it works:
- The dict separates what to compare (the models) from how to compare them (the loop). Adding a model is now one line.
- The loop body runs the same fit–predict–score steps for every model, so no model can get a different treatment by accident.
- A DataFrame sorts, rounds and exports (
to_markdown,to_csv) for free, which makes the result a report, not a printout. - The table holds test scores, so it can only report. Do not pick the model from it: rank cross-validated scores of the training rows instead (exercise M35-X02).
Alternative: a function evaluate(model) -> dict and a dict comprehension: pd.DataFrame({n: evaluate(m) for n, m in models.items()}).T.
M35-C11 · Interpret: residuals by neighborhood
Section titled “M35-C11 · Interpret: residuals by neighborhood”Interpret a result: compute the log residuals of the log-target linear model on the test set (np.log(y_test) - np.log(pred)) and print their mean and count per neighborhood, sorted by the mean. Which neighborhoods does the model underprice and overprice on average, and is the bias large?
mean countneighborhoodOld Town -0.037 81Riverside -0.025 103Oak Hill -0.017 89Downtown 0.008 86Maple Grove 0.020 98Cedar Park 0.024 102Westfield 0.030 103Lakeview 0.032 88model = TransformedTargetRegressor( regressor=make_pipeline(make_preprocessor(), LinearRegression()), func=np.log, inverse_func=np.exp,)# TODO: fit, predict, log residuals# TODO: group the residuals by X_test["neighborhood"]: mean and count, sorted by meanHint 1
A positive log residual means the true price is above the prediction: the model underprices.
Hint 2
resid.groupby(X_test["neighborhood"]).agg(["mean", "count"]).sort_values("mean").
Solution
model = TransformedTargetRegressor( regressor=make_pipeline(make_preprocessor(), LinearRegression()), func=np.log, inverse_func=np.exp,)pred = model.fit(X_train, y_train).predict(X_test)resid = pd.Series(np.log(y_test) - np.log(pred), index=X_test.index)by_hood = resid.groupby(X_test["neighborhood"]).agg(["mean", "count"])print(by_hood.sort_values("mean").round(3))assert by_hood["mean"].abs().max() < 0.06assert by_hood["count"].sum() == len(X_test) mean countneighborhoodOld Town -0.037 81Riverside -0.025 103Oak Hill -0.017 89Downtown 0.008 86Maple Grove 0.020 98Cedar Park 0.024 102Westfield 0.030 103Lakeview 0.032 88How it works:
- The model has a dummy for each neighborhood, so on the training set the mean residual per neighborhood is exactly 0. On the test set it is close to 0, but not exactly.
- Each mean residual is a few percent at most (0.03 on the log scale is about 3%). Compared with the residual standard deviation of about 0.17, that bias is small.
- Old Town has the most negative mean: the model overprices it by about 4% on average. That fits the overpriced Old Town houses from the 1950s that the lesson’s Example 4 found.
Answer: the model underprices Lakeview, Westfield and Cedar Park slightly and overprices Old Town and Riverside slightly, but no neighborhood is badly biased on average. The large errors sit inside neighborhoods, with single houses. To reduce them, try a curved age effect (exercise M35-C08), an interaction between neighborhood and size, or a tree model.
M35-C12 · Choose and justify: which metric?
Section titled “M35-C12 · Choose and justify: which metric?”Choose a method and justify it: two candidate models priced the same six houses. Print MAE, RMSE and MAPE for both. Then decide which model each client should use: a bank that lends against the valuation and fears any large miss, and a listing site whose users compare relative errors across cheap and expensive homes.
model A: MAE 64,167 RMSE 105,218 MAPE 9.0%model B: MAE 47,500 RMSE 48,520 MAPE 11.8%y_true = np.array([180_000, 240_000, 310_000, 450_000, 900_000, 1_600_000])model_a = np.array([200_000, 220_000, 335_000, 420_000, 860_000, 1_350_000])model_b = np.array([215_000, 280_000, 270_000, 500_000, 960_000, 1_540_000])# TODO: print MAE, RMSE and MAPE for both models# TODO: decide which model fits the bank and which fits the listing siteHint 1
Loop over [("A", model_a), ("B", model_b)] and print the three metrics per model.
Hint 2
Look at the most expensive house: which model misses it by more?
Solution
y_true = np.array([180_000, 240_000, 310_000, 450_000, 900_000, 1_600_000])model_a = np.array([200_000, 220_000, 335_000, 420_000, 860_000, 1_350_000])model_b = np.array([215_000, 280_000, 270_000, 500_000, 960_000, 1_540_000])metrics = {}for name, pred in [("A", model_a), ("B", model_b)]: metrics[name] = ( mean_absolute_error(y_true, pred), root_mean_squared_error(y_true, pred), mean_absolute_percentage_error(y_true, pred), ) mae, rmse, mape = metrics[name] print(f"model {name}: MAE {mae:,.0f} RMSE {rmse:,.0f} MAPE {mape:.1%}")assert metrics["A"][2] < metrics["B"][2] # A wins on MAPEassert metrics["B"][1] < metrics["A"][1] # B wins on RMSEmodel A: MAE 64,167 RMSE 105,218 MAPE 9.0%model B: MAE 47,500 RMSE 48,520 MAPE 11.8%How it works:
- Model A is close on the five cheaper houses but misses the 1.6M house by 250,000 USD.
- Model B makes medium errors everywhere, including 60,000 on the 1.6M house.
- RMSE squares the errors, so A’s one big miss dominates and B wins. MAPE divides by the price, so A’s big miss counts as only about 16%, and A’s small relative errors elsewhere win.
- MAE also favors B here. It treats every USD of error the same, and A’s single miss of 250,000 USD outweighs its small errors elsewhere.
Answer: the bank should use model B, judged by RMSE: one large miss on an expensive house is the costly event. The listing site should use model A, judged by MAPE: users compare percentages, and A is closer in relative terms on most homes.
M35-C13 · Forest size and the out-of-bag score
Section titled “M35-C13 · Forest size and the out-of-bag score”Write the code: fit RandomForestRegressor(oob_score=True, random_state=42, n_jobs=-1) with 25, 50 and 100 trees (unscaled preprocessor). Print the out-of-bag R² and the test R² for each size. Each tree’s bootstrap sample leaves out about a third of the rows; the out-of-bag (OOB) score predicts each training row only with the trees that did not see it, which gives a free validation score.
25 trees: OOB R² 0.855, test R² 0.894 50 trees: OOB R² 0.866, test R² 0.894100 trees: OOB R² 0.871, test R² 0.896from sklearn.ensemble import RandomForestRegressor
for n in [25, 50, 100]: # TODO: pipeline with the forest; fit on the training set # TODO: print the forest's oob_score_ and the test R² passHint 1
The forest is the last step of the pipeline: pipe[-1].oob_score_.
Hint 2
oob_score=True makes the forest compute R² on the out-of-bag predictions during fit.
Solution
from sklearn.ensemble import RandomForestRegressor
oob = {}for n in [25, 50, 100]: forest = make_pipeline( make_preprocessor(scale=False), RandomForestRegressor( n_estimators=n, oob_score=True, random_state=42, n_jobs=-1 ), ).fit(X_train, y_train) oob[n] = forest[-1].oob_score_ test_r2 = forest.score(X_test, y_test) print(f"{n:>3} trees: OOB R² {oob[n]:.3f}, test R² {test_r2:.3f}")assert oob[100] > oob[25] 25 trees: OOB R² 0.855, test R² 0.894 50 trees: OOB R² 0.866, test R² 0.894100 trees: OOB R² 0.871, test R² 0.896How it works:
- Each tree trains on a bootstrap sample. On average, about 37% of the rows are not in it: they are “out of the bag” for that tree.
- For each training row, the forest averages only the trees that never saw it. The R² of these predictions estimates the test score without a separate validation set.
- More trees raise both scores, with diminishing returns. A forest does not overfit as trees are added; it only gets slower.
- The OOB R² is lower than the test R², for at least two reasons. Each training row is predicted by only the roughly 37% of trees that did not see it, so the OOB predictions come from a much smaller forest; that part of the gap shrinks as trees are added. And the OOB score is computed on the training rows, which hold all eight corrupted sales of the data dictionary (the lesson’s Example 4 shows that none is in the test set); their huge errors pull the OOB R² down.
Alternative: cross_val_score gives a similar estimate but fits the forest 5 times. OOB needs only one fit.
Challenge
Section titled “Challenge”M35-X01 · Does the market move over time?
Section titled “M35-X01 · Does the market move over time?”Do prices drift over the three years of sales, holding the houses fixed? The lesson dropped sold_date. Add a feature years_since_2022 (days since 2022-01-01 divided by 365.25), split again with test_size=0.25, random_state=42, and fit the log-linear model with unscaled features. Print the estimated yearly trend in percent, and compare the 5-fold CV R² on the training set (log scale) with and without the new feature. Report the test R² on the price scale for both, once.
without date: CV R² (log) 0.891, test R² (price) 0.898 with date: CV R² (log) 0.897, test R² (price) 0.903market trend: +4.8% per yeardated = houses.assign( years_since_2022=lambda d: 0.0 # TODO: compute from sold_date)# TODO: X2 = all columns except house_id, sold_date and price# TODO: split X2 with the same settings# TODO: preprocessor: one-hot neighborhood, median-impute the numbers (incl. the new one)# TODO: CV R² on log price (cv from the setup), with and without the feature# TODO: fit on the training set, test R² on the price scale, the yearly trendHint 1
(pd.to_datetime(d["sold_date"]) - pd.Timestamp("2022-01-01")).dt.days / 365.25.
Hint 2
The same random_state and the same number of rows give the same split, so the scores are comparable with the lesson.
Hint 3
Write a function log_linear(columns) that builds the pipeline for a list of numeric columns. Call it with and without the new column, and use cross_val_score(..., scoring="r2") on np.log(y2_train) before you fit and test.
Solution
dated = houses.assign( years_since_2022=lambda d: ( pd.to_datetime(d["sold_date"]) - pd.Timestamp("2022-01-01") ).dt.days / 365.25)X2 = dated.drop(columns=["house_id", "sold_date", "price"])X2_train, X2_test, y2_train, y2_test = train_test_split( X2, dated["price"], test_size=0.25, random_state=42)
def log_linear(numeric: list[str]): pre = ColumnTransformer( [ ("cat", OneHotEncoder(drop="first"), cat_cols), ("num", SimpleImputer(strategy="median"), numeric), ], verbose_feature_names_out=False, ) return make_pipeline(pre, LinearRegression())
z2_train = np.log(y2_train)results = {}feature_sets = {"without date": num_cols, "with date": num_cols + ["years_since_2022"]}for label, numeric in feature_sets.items(): model = log_linear(numeric) cv_r2 = cross_val_score(model, X2_train, z2_train, cv=cv, scoring="r2").mean() model.fit(X2_train, z2_train) test_r2 = r2_score(y2_test, np.exp(model.predict(X2_test))) results[label] = (model, cv_r2, test_r2) print(f"{label:>12}: CV R² (log) {cv_r2:.3f}, test R² (price) {test_r2:.3f}")
with_date = results["with date"][0]coefs = pd.Series(with_date[-1].coef_, index=with_date[0].get_feature_names_out())trend = np.exp(coefs["years_since_2022"]) - 1print(f"market trend: {trend:+.1%} per year")assert X2_test.index.equals(X_test.index)assert trend > 0assert results["with date"][1] > results["without date"][1]without date: CV R² (log) 0.891, test R² (price) 0.898 with date: CV R² (log) 0.897, test R² (price) 0.903market trend: +4.8% per yearHow it works:
pd.to_datetimeparses the ISO dates; subtracting a timestamp gives atimedeltaSeries, and.dt.daysturns it into a number.- The split has the same rows as the lesson, which the first assert proves, so the test R² values are directly comparable with the lesson.
- The decision to keep the date rests on the CV R², computed on the training set only. The test R² is reported once, after the decision.
- On log price, the coefficient of a time variable is a growth rate: per year. The output says prices rose by about 4.8% per year, holding the other features fixed.
- The date explains part of the price that the other features cannot, so both R² values rise.
Alternative: use the sale year as a category (one-hot 2022, 2023, 2024). It allows a different jump each year, at the cost of two extra columns and no single growth rate.
M35-X02 · Select a model with cross-validation, test it once
Section titled “M35-X02 · Select a model with cross-validation, test it once”Run a proper model selection. Compare five candidates by 5-fold CV RMSE on the training set (use cv from the setup): the log-linear model, Ridge on log price (alpha=1), KNN with k=5, a random forest with 100 trees, and HistGradientBoostingRegressor on log price. Print the CV table sorted by RMSE, then score only the winner on the test set.
log boosting 101247.0log linear 107252.0log ridge 107951.0forest 114812.0knn k=5 127042.0winner: log boostingtest RMSE 94,269, R² 0.915from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressorfrom sklearn.linear_model import Ridgefrom sklearn.neighbors import KNeighborsRegressor
hood_type = pd.CategoricalDtype(sorted(X_train["neighborhood"].unique()))X_train_cat = X_train.astype({"neighborhood": hood_type})X_test_cat = X_test.astype({"neighborhood": hood_type})# TODO: a dict name -> (model, X for training, X for testing)# TODO: CV RMSE of each on its training X; a sorted table# TODO: fit the winner on all training rows and print its test RMSE and R²Hint 1
Write log_target(regressor) that wraps any regressor in TransformedTargetRegressor(func=np.log, inverse_func=np.exp). Cross-validation then scores every model on the price scale.
Hint 2
Gradient boosting needs X_train_cat (with the category dtype); the other models use X_train with the preprocessor.
Hint 3
table.index[0] is the winner after sorting. Look it up in the dict, fit it, and score it once.
Solution
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressorfrom sklearn.linear_model import Ridgefrom sklearn.neighbors import KNeighborsRegressor
hood_type = pd.CategoricalDtype(sorted(X_train["neighborhood"].unique()))X_train_cat = X_train.astype({"neighborhood": hood_type})X_test_cat = X_test.astype({"neighborhood": hood_type})
def log_target(regressor) -> TransformedTargetRegressor: return TransformedTargetRegressor( regressor=regressor, func=np.log, inverse_func=np.exp )
linear_pipe = make_pipeline(make_preprocessor(), LinearRegression())ridge_pipe = make_pipeline(make_preprocessor(), Ridge(alpha=1))knn_pipe = make_pipeline(make_preprocessor(), KNeighborsRegressor(n_neighbors=5))candidates = { "log linear": (log_target(linear_pipe), X_train, X_test), "log ridge": (log_target(ridge_pipe), X_train, X_test), "knn k=5": (knn_pipe, X_train, X_test), "forest": ( make_pipeline( make_preprocessor(scale=False), RandomForestRegressor(n_estimators=100, n_jobs=-1, random_state=42), ), X_train, X_test, ), "log boosting": ( log_target(HistGradientBoostingRegressor(random_state=42)), X_train_cat, X_test_cat, ),}cv_rmse = { name: -cross_val_score( model, Xtr, y_train, cv=cv, scoring="neg_root_mean_squared_error" ).mean() for name, (model, Xtr, _) in candidates.items()}table = pd.Series(cv_rmse, name="CV RMSE").sort_values()print(table.round(0).to_string())
winner = table.index[0]model, Xtr, Xte = candidates[winner]pred = model.fit(Xtr, y_train).predict(Xte)print(f"winner: {winner}")rmse, r2 = root_mean_squared_error(y_test, pred), r2_score(y_test, pred)print(f"test RMSE {rmse:,.0f}, R² {r2:.3f}")assert winner == "log boosting"log boosting 101247.0log linear 107252.0log ridge 107951.0forest 114812.0knn k=5 127042.0winner: log boostingtest RMSE 94,269, R² 0.915How it works:
- Each candidate carries its own training and test frames, so gradient boosting gets the
categorycolumn and the others get the raw frame for their preprocessor. cross_val_scorerefits every model on 4 folds and scores the fifth, five times, using only training rows. The preprocessors are refitted inside each fold, so nothing leaks.- The log-target models are scored on the price scale, because
TransformedTargetRegressorback-transforms before the scorer sees the predictions. - Only the winner touches the test set, once. Its test score is an honest estimate for new houses, because the test set played no part in the choice.
Alternative: cross_validate with scoring={"rmse": "neg_root_mean_squared_error", "r2": "r2"} returns several metrics in one run.
M35-X03 · Gradient boosting from scratch
Section titled “M35-X03 · Gradient boosting from scratch”Write gradient boosting yourself. Use the unscaled preprocessor to build the training and test matrices, and the log price as the target. Start from the mean log price, then repeat 100 times: fit a DecisionTreeRegressor(max_depth=3, random_state=42) to the current residuals and add 0.1 times its prediction. Print the training RMSE (log scale) after 1, 10 and 100 trees, and the test R² on the price scale. Compare with GradientBoostingRegressor(n_estimators=100, max_depth=3, learning_rate=0.1, random_state=42) fitted on the same data.
after 1 trees: training RMSE 0.490after 10 trees: training RMSE 0.301after 100 trees: training RMSE 0.135test R² from scratch 0.907, scikit-learn 0.907from sklearn.ensemble import GradientBoostingRegressorfrom sklearn.tree import DecisionTreeRegressor
pre = make_preprocessor(scale=False)A_train = pre.fit_transform(X_train)A_test = pre.transform(X_test)z_train = np.log(y_train.to_numpy())learning_rate = 0.1# TODO: start both predictions (train and test) at the mean of z_train# TODO: loop 100 times: fit a tree on the residuals, add learning_rate * its predictions# TODO: print the training RMSE after 1, 10 and 100 trees# TODO: test R² on the price scale; compare with GradientBoostingRegressorHint 1
F_train = np.full(len(z_train), z_train.mean()). The residuals are z_train - F_train.
Hint 2
Update the test predictions with the same tree in the same loop: F_test += learning_rate * tree.predict(A_test).
Hint 3
Back-transform before scoring: r2_score(y_test, np.exp(F_test)).
Solution
from sklearn.ensemble import GradientBoostingRegressorfrom sklearn.tree import DecisionTreeRegressor
pre = make_preprocessor(scale=False)A_train = pre.fit_transform(X_train)A_test = pre.transform(X_test)z_train = np.log(y_train.to_numpy())learning_rate = 0.1
F_train = np.full(len(z_train), z_train.mean())F_test = np.full(len(A_test), z_train.mean())for m in range(1, 101): tree = DecisionTreeRegressor(max_depth=3, random_state=42) tree.fit(A_train, z_train - F_train) F_train += learning_rate * tree.predict(A_train) F_test += learning_rate * tree.predict(A_test) if m in (1, 10, 100): rmse_m = root_mean_squared_error(z_train, F_train) print(f"after {m:>3} trees: training RMSE {rmse_m:.3f}")
r2_scratch = r2_score(y_test, np.exp(F_test))gbr = GradientBoostingRegressor( n_estimators=100, max_depth=3, learning_rate=0.1, random_state=42).fit(A_train, z_train)r2_sklearn = r2_score(y_test, np.exp(gbr.predict(A_test)))print(f"test R² from scratch {r2_scratch:.3f}, scikit-learn {r2_sklearn:.3f}")assert abs(r2_scratch - r2_sklearn) < 0.01after 1 trees: training RMSE 0.490after 10 trees: training RMSE 0.301after 100 trees: training RMSE 0.135test R² from scratch 0.907, scikit-learn 0.907How it works:
- The model starts as a constant: the mean log price. Its residuals are everything that is left to explain.
- Each tree is a weak learner with at most 8 leaves. It fits the current residuals, so it learns what the model still gets wrong.
- Adding only 0.1 of each tree’s prediction makes small, careful steps. The training RMSE falls quickly at first and then slowly.
- For squared error, the residual is the negative gradient of the loss, which gives the method its name: each tree is a step of gradient descent in the space of functions.
- scikit-learn’s
GradientBoostingRegressorruns the same algorithm. The scores match closely but not exactly: small implementation details (for example how the trees break ties between equally good splits) make the predictions differ slightly.
Alternative: HistGradientBoostingRegressor is the fast version for real work. It bins the features first and reads missing values and categories directly.
M35-X04 · Refactor: a KNN regressor class
Section titled “M35-X04 · Refactor: a KNN regressor class”Refactor procedural code into a class: write NumpyKNNRegressor(n_neighbors=5) that inherits from scikit-learn’s BaseEstimator and RegressorMixin (module 34 rebuilt minilearn this way). fit stores the training arrays; predict averages the targets of the k nearest rows by Euclidean distance, computed with NumPy broadcasting. Put it in a pipeline after the scaled preprocessor, and check that its test predictions equal those of KNeighborsRegressor(n_neighbors=5).
mine R² 0.878, sklearn R² 0.878same predictions: TrueNumpyKNNRegressor()from sklearn.base import BaseEstimator, RegressorMixinfrom sklearn.neighbors import KNeighborsRegressor
class NumpyKNNRegressor(RegressorMixin, BaseEstimator): def __init__(self, n_neighbors: int = 5): self.n_neighbors = n_neighbors
def fit(self, X, y): # TODO: store X and y as NumPy arrays (learned attributes end with _) return self
def predict(self, X): # TODO: distances of shape (n_test, n_train) with broadcasting # TODO: indices of the k smallest per row, then the mean of their targets ...
# TODO: compare a pipeline with NumpyKNNRegressor and one with KNeighborsRegressorHint 1
diff = X[:, None, :] - self.X_[None, :, :] has shape (n_test, n_train, n_features). Square, sum over the last axis and take the square root.
Hint 2
np.argsort(dist, axis=1)[:, : self.n_neighbors] gives the neighbor indices per test row. self.y_[idx].mean(axis=1) averages their targets.
Hint 3
RegressorMixin gives your class a score method that returns R², so pipe.score(X_test, y_test) works.
Solution
from sklearn.base import BaseEstimator, RegressorMixinfrom sklearn.neighbors import KNeighborsRegressor
class NumpyKNNRegressor(RegressorMixin, BaseEstimator): """Predict the mean target of the k nearest training rows."""
def __init__(self, n_neighbors: int = 5): self.n_neighbors = n_neighbors
def fit(self, X, y): self.X_ = np.asarray(X, dtype=float) self.y_ = np.asarray(y, dtype=float) return self
def predict(self, X): X = np.asarray(X, dtype=float) dist = np.sqrt(((X[:, None, :] - self.X_[None, :, :]) ** 2).sum(axis=2)) idx = np.argsort(dist, axis=1, kind="stable")[:, : self.n_neighbors] return self.y_[idx].mean(axis=1)
mine = make_pipeline(make_preprocessor(), NumpyKNNRegressor(n_neighbors=5))ref = make_pipeline(make_preprocessor(), KNeighborsRegressor(n_neighbors=5))mine_pred = mine.fit(X_train, y_train).predict(X_test)ref_pred = ref.fit(X_train, y_train).predict(X_test)r2_mine, r2_ref = mine.score(X_test, y_test), ref.score(X_test, y_test)print(f"mine R² {r2_mine:.3f}, sklearn R² {r2_ref:.3f}")print("same predictions:", np.allclose(mine_pred, ref_pred))print(mine[-1])assert np.allclose(mine_pred, ref_pred)assert mine[-1].get_params() == {"n_neighbors": 5}mine R² 0.878, sklearn R² 0.878same predictions: TrueNumpyKNNRegressor()How it works:
BaseEstimatorgivesget_params,set_paramsand the readablereprfrom the__init__arguments, so the class works withclone, pipelines and grid search.RegressorMixinaddsscore, which computes R². It must come first in the base list, so its methods take priority.- Broadcasting builds all test–train differences at once: 750 × 2,250 × 17 numbers, about 230 MB of temporary memory at most for this data, with no Python loop.
argsort(..., kind="stable")keeps ties in a fixed order. The predictions equal scikit-learn’s, which proves the class is correct.
Alternative: scipy.spatial.distance.cdist(X, self.X_) computes the distance matrix without the large 3-D temporary array, which matters for bigger data.
M35-X05 · Fix the bugs: a leaky price script
Section titled “M35-X05 · Fix the bugs: a leaky price script”Fix the bugs: this script has three separate bugs. (1) The scaler and imputer see the test rows. (2) The MAE is computed on log prices but reported in USD. (3) Ridge’s alpha is chosen by test score. Rewrite it as one leak-free pipeline: TransformedTargetRegressor around the preprocessor and RidgeCV(alphas=[0.1, 1, 10, 100]), fitted on the training set only. Print the chosen alpha, the test MAE in USD and the test R².
chosen alpha: 0.1test MAE: 65,216 USDtest R²: 0.898from sklearn.linear_model import Ridge, RidgeCV
pre = make_preprocessor()X_all = pre.fit_transform(X) # bug 1: fitted on all rowsA_train, A_test = X_all[X_train.index], X_all[X_test.index]best = Nonefor alpha in [0.1, 1, 10, 100]: model = Ridge(alpha=alpha).fit(A_train, np.log(y_train)) score = model.score(A_test, np.log(y_test)) # bug 3: tuned on the test set if best is None or score > best[0]: best = (score, alpha, model)pred = best[2].predict(A_test)print(f"MAE: {mean_absolute_error(np.log(y_test), pred):,.0f} USD") # bug 2# TODO: rewrite as one pipeline fitted on X_train onlyHint 1
Bug 1 and bug 3 have the same cure: everything that learns from data (the preprocessor and the choice of alpha) must live inside the model that is fitted on X_train.
Hint 2
RidgeCV picks alpha with cross-validation on the training rows. TransformedTargetRegressor handles the log and its inverse, which fixes bug 2.
Solution
from sklearn.linear_model import RidgeCV
model = TransformedTargetRegressor( regressor=make_pipeline(make_preprocessor(), RidgeCV(alphas=[0.1, 1, 10, 100])), func=np.log, inverse_func=np.exp,)model.fit(X_train, y_train)pred = model.predict(X_test)alpha = model.regressor_[-1].alpha_mae = mean_absolute_error(y_test, pred)print(f"chosen alpha: {alpha}")print(f"test MAE: {mae:,.0f} USD")print(f"test R²: {r2_score(y_test, pred):.3f}")assert alpha in (0.1, 1, 10, 100)assert 50_000 < mae < 80_000chosen alpha: 0.1test MAE: 65,216 USDtest R²: 0.898How it works:
- Bug 1.
pre.fit_transform(X)learned the medians, means and standard deviations from all 3,000 houses, test rows included. In the pipeline, the preprocessor is fitted onX_trainonly.RidgeCVthen picks alpha with efficient leave-one-out cross-validation on the transformed training rows; no fold refits the preprocessor. For a refit per fold, useGridSearchCV(see the alternative). - Bug 2. The old MAE compared log prices, so it was about 0.13, printed as “0 USD”.
TransformedTargetRegressorback-transforms, so the MAE is a real amount in USD. - Bug 3. Picking the alpha with the best test score uses the test set for a decision, so the reported score is optimistic.
RidgeCVchooses with cross-validation on the training rows. - Also note the subtle indexing trap in the old code:
X_all[X_train.index]used DataFrame labels as row positions in a NumPy array. It only worked becausehouseshas the default 0..2999 index.
Alternative: use GridSearchCV over regressor__ridge__alpha on a TransformedTargetRegressor with a plain Ridge (module 37). It also allows scoring on the price scale with any metric.