38. Ensembles — Mini-project
An estate agency wants an automated valuation model: a number for every house that comes on the market. The lead analyst has heard that “ensembles always win” and asks you to check that claim on their data before they commit to a complex model.
Write a script, valuation_model.py, that compares five candidate models on data/houses.csv with a fair protocol, chooses one with a stated decision rule and reports one honest test score. End with a short recommendation that a manager can read in one minute.
The project uses the core of module 38: random forests, gradient boosting, HistGradientBoosting with early stopping, stacking with out-of-fold meta-features, and a fair comparison with the same folds, mean ± standard deviation and paired differences.
Dataset
Section titled “Dataset”data/houses.csv has 3,000 house sales from 2022 to 2024 and 14 columns. The target is price in USD (117,500 to 3,730,500, right-skewed). The data dictionary describes every column.
| Use | Columns |
|---|---|
| Target | price |
| Features | neighborhood (8 values), sqft, bedrooms, bathrooms, year_built, lot_sqft (90 blank), garage_spaces, has_pool, condition, distance_to_center_km, school_rating (90 blank) |
| Leave out | house_id (an identifier), sold_date |
The data contain 8 injected price outliers. RMSE squares the errors, so these few houses weigh heavily in it. Keep them: a valuation model meets odd sales in practice too.
Requirements
Section titled “Requirements”Your script must:
- One-hot encode
neighborhoodwithpd.get_dummies, add alog_sqftcolumn, and split 75% / 25% withrandom_state=42. Do not touch the test set until the last step. - Put every learned preprocessing step (imputation, scaling) inside a pipeline, so that cross-validation refits it in each fold.
- Build five candidates:
- linear (log): median imputation,
StandardScalerandRidgeCV, trained on log price withTransformedTargetRegressor; - forest:
RandomForestRegressorwith 150 trees andmax_features=0.33; - boosting:
GradientBoostingRegressorwith 300 trees, learning rate 0.05, depth 3 andsubsample=0.8; - hist boosting (log):
HistGradientBoostingRegressorwith learning rate 0.05,max_iter=1000and early stopping, on log price; - stack: a
StackingRegressorof the linear, forest and hist-boosting models with aRidgeCVmeta-learner.
- linear (log): median imputation,
- Cross-validate all five on the training set with one
KFold(5, shuffle=True, random_state=42)object. Print RMSE mean ± standard deviation per model, sorted from best to worst. - Print the per-fold RMSE differences of every model against the best single model (not the stack).
- Apply this decision rule and print the choice: choose the stack only if it beats the best single model on at least 4 of the 5 folds; otherwise choose the best single model.
- Fit the chosen model on the whole training set. Print its test RMSE, its test MAE and the median absolute percentage error. Print the linear baseline’s test RMSE for comparison.
- Print the meta-learner weights if you chose the stack, and explain them.
- End with
assertchecks, for example that every model saw the same folds and that the chosen model beats the baseline on the test set. - Write 4–6 sentences of recommendation.
Step plan
Section titled “Step plan”-
Load and split. Read the CSV, build
Xwithpd.get_dummies(..., dtype=int)andlog_sqft, and split. Print the shapes. -
Build the candidates. Use
make_pipeline(SimpleImputer(strategy="median"), ...)for the scikit-learn models that cannot handle blanks.HistGradientBoostingRegressorhandles blanks itself. Wrap the log-price models inTransformedTargetRegressor(regressor=..., func=np.log, inverse_func=np.exp). -
Build the stack. Pass the three base models as
(name, model)pairs toStackingRegressor, withfinal_estimator=RidgeCV()andcv=cv. Thecvcreates the out-of-fold meta-features. -
Cross-validate. Loop over the models with
cross_validate(model, X_train, y_train, cv=cv, scoring="neg_root_mean_squared_error"). Flip the sign. Keep the fold scores in a dict. -
Compare fairly. Build a table of mean and standard deviation. Build a DataFrame of fold scores and subtract the best single model’s column.
-
Decide. Count the folds where the stack is better. Apply the rule.
-
Test once. Fit the chosen model on the full training set, then score it on the test set.
-
Explain. Read the meta-learner weights. Write the recommendation.
A skeleton to start from:
import numpy as npimport pandas as pdfrom sklearn.compose import TransformedTargetRegressorfrom sklearn.ensemble import ( GradientBoostingRegressor, HistGradientBoostingRegressor, RandomForestRegressor, StackingRegressor,)from sklearn.impute import SimpleImputerfrom sklearn.linear_model import RidgeCVfrom sklearn.model_selection import KFold, cross_validate, train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerfrom threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # whole script: 1 thread for OpenMP and BLAS
houses = pd.read_csv("data/houses.csv")# TODO: X with one-hot neighborhood and log_sqft; y = price; 75/25 splitcv = KFold(5, shuffle=True, random_state=42)# TODO: the five candidates# TODO: cross-validate, compare, decide, test once, explainRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| No leakage | 3 | imputation and scaling inside pipelines; the test set is used once, at the end |
| Candidates | 3 | all five models with the stated settings; log target where required |
| Fair comparison | 3 | one KFold object for every model; mean ± standard deviation printed |
| Paired differences | 2 | per-fold differences against the best single model |
| Decision rule | 2 | the rule is applied in code and the choice is printed |
| Honest test score | 2 | RMSE, MAE and median percentage error of the chosen model; the baseline for comparison |
| Self-checks | 1 | at least three meaningful asserts |
| Recommendation | 2 | 4–6 sentences; mentions the gain, the cost and the risk |
| Total | 18 | 15 or more: you are ready for module 39 |
Stretch goals
Section titled “Stretch goals”- Add the
GradientBoostingRegressorpipeline to the stack. Does a fourth member help, or is it too correlated with the hist-boosting model? Check the correlation of their out-of-fold predictions withcross_val_predict. - Compare the stack with a
VotingRegressorof the same three models. How much of the stack’s gain comes from learning the weights? - Train the boosting model with
loss="huber"orloss="absolute_error", which give outliers less weight, and compare the test MAE. - Estimate the uncertainty of the final test RMSE with a bootstrap of the 750 test errors (module 29).
- Use nested cross-validation (module 37) to tune the learning rate of the hist-boosting model inside the comparison.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your formatting can differ; your numbers must not.
Reference solution
import numpy as npimport pandas as pdfrom sklearn.compose import TransformedTargetRegressorfrom sklearn.ensemble import ( GradientBoostingRegressor, HistGradientBoostingRegressor, RandomForestRegressor, StackingRegressor,)from sklearn.impute import SimpleImputerfrom sklearn.linear_model import RidgeCVfrom sklearn.metrics import mean_absolute_error, root_mean_squared_errorfrom sklearn.model_selection import KFold, cross_validate, train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerfrom threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # whole script: 1 thread for OpenMP and BLASpd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)
houses = pd.read_csv("data/houses.csv")X = pd.get_dummies( houses.drop(columns=["house_id", "sold_date", "price"]), columns=["neighborhood"], dtype=int,)X["log_sqft"] = np.log(X["sqft"])y = houses["price"]X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42)cv = KFold(5, shuffle=True, random_state=42)print(X_train.shape, X_test.shape)
def on_log_price(model): """Train on log(price), predict in USD.""" return TransformedTargetRegressor(regressor=model, func=np.log, inverse_func=np.exp)
linear = on_log_price(make_pipeline( SimpleImputer(strategy="median"), StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 11)),))forest = make_pipeline( SimpleImputer(strategy="median"), RandomForestRegressor(n_estimators=150, max_features=0.33, random_state=42),)boosting = make_pipeline( SimpleImputer(strategy="median"), GradientBoostingRegressor( n_estimators=300, learning_rate=0.05, max_depth=3, subsample=0.8, random_state=42, ),)hist_log = on_log_price(HistGradientBoostingRegressor( learning_rate=0.05, max_iter=1000, early_stopping=True, n_iter_no_change=20, random_state=42,))stack = StackingRegressor( [("linear", linear), ("forest", forest), ("hist", hist_log)], final_estimator=RidgeCV(), cv=cv,)candidates = { "linear (log)": linear, "forest": forest, "boosting": boosting, "hist boosting (log)": hist_log, "stack": stack,}(2250, 19) (750, 19)fold_rmse, rows = {}, []for name, model in candidates.items(): res = cross_validate( model, X_train, y_train, cv=cv, scoring="neg_root_mean_squared_error" ) fold_rmse[name] = -res["test_score"] rows.append({"model": name, "rmse_mean": fold_rmse[name].mean(), "rmse_std": fold_rmse[name].std()})board = pd.DataFrame(rows).set_index("model").sort_values("rmse_mean")print(board.round(0).astype(int))
folds = pd.DataFrame(fold_rmse)best_single = board.drop("stack")["rmse_mean"].idxmin()diff = folds.sub(folds[best_single], axis=0).drop(columns=best_single)print(f"\nRMSE minus {best_single}, per fold (negative = better):")print(diff.round(0).astype(int)) rmse_mean rmse_stdmodelstack 99036 13518boosting 103494 17020linear (log) 107884 8599hist boosting (log) 112052 17714forest 112819 14783
RMSE minus boosting, per fold (negative = better): linear (log) forest hist boosting (log) stack0 4315 10513 8420 -22701 463 8596 12023 -30712 -14372 5045 7202 -145763 15196 9515 1789 -18164 16350 12959 13357 -558stack_wins = int((diff["stack"] < 0).sum())choice = "stack" if stack_wins >= 4 else best_singleprint(f"stack beats {best_single} on {stack_wins} of 5 folds -> choose: {choice}")
final = candidates[choice].fit(X_train, y_train)pred = final.predict(X_test)baseline = candidates["linear (log)"].fit(X_train, y_train).predict(X_test)test_rmse = root_mean_squared_error(y_test, pred)base_rmse = root_mean_squared_error(y_test, baseline)mdape = np.median(np.abs(pred - y_test) / y_test)test_mae = mean_absolute_error(y_test, pred)print(f"{choice}: test RMSE {test_rmse:,.0f} | MAE {test_mae:,.0f}" f" | median abs. % error {mdape:.1%}")print(f"linear (log) baseline: test RMSE {base_rmse:,.0f}")if choice == "stack": coefs = final.final_estimator_.coef_.round(2).tolist() print("meta-learner weights:", dict(zip(["linear", "forest", "hist"], coefs)))
assert set(fold_rmse) == set(candidates)assert all(len(scores) == 5 for scores in fold_rmse.values())assert test_rmse < base_rmseassert 0 < mdape < 0.2stack beats boosting on 5 of 5 folds -> choose: stackstack: test RMSE 90,602 | MAE 59,601 | median abs. % error 10.7%linear (log) baseline: test RMSE 104,506meta-learner weights: {'linear': 0.64, 'forest': 0.07, 'hist': 0.38}How the solution works:
- Leak-free candidates. The imputer and the scaler sit inside the pipelines, so
cross_validaterefits them on each training fold.pd.get_dummiesandlog_sqftlearn nothing from the data, so they are safe before the split.TransformedTargetRegressortrains on log price and returns USD, so all RMSEs are on the same scale. - The stack.
StackingRegressorbuilds its meta-features with the samecvsplitter: 5 out-of-fold predictions per base model. Inside the outer cross-validation, it splits each training fold again into 5, so the outer validation fold never reaches the meta-learner. - The comparison. One
KFoldobject gives every model the same folds. The standard deviations are large, between about 8,600 and 17,700 USD, because a few outlier houses land in different folds. By the “within one standard deviation” rule, most models would tie. - The paired differences. Subtracting the best single model fold by fold removes that shared noise. The stack is better on every fold, so the rule chooses it.
- The weights. The meta-learner gives most weight to the linear model and the hist-boosting model, and little to the forest. The linear log-price model and the trees make different kinds of errors: the linear model extrapolates smoothly, the trees capture thresholds and interactions. That diversity is what the stack exploits. The forest adds little that the boosting model does not already provide.
- The test score. It is read once, for the chosen model and the baseline. The stack beats the linear baseline on the test set too.
Example recommendation: Use the stacking ensemble. In cross-validation it beat the best single model on all 5 folds, by about 4,500 USD of RMSE on average, and on the held-out test set it values a typical house within about 11% of its sale price. The gain comes from combining a log-price linear model with gradient boosting, two models that err differently; a forest adds little. The cost is a model of three parts, and training it fits each part 6 times (5 out-of-fold fits and 1 final fit), which is acceptable for nightly retraining. If the agency needs a model that it can explain line by line, the linear log-price model is the fallback: about 15% higher test RMSE, but every coefficient can be read.