34. The scikit-learn workflow — Mini-project
A real-estate team wants a price estimate for each new listing. A data scientist trains the model once a month. A small web tool then loads the saved model and prices listings all day, in another process and maybe on another machine.
Build the two halves of this workflow:
train_house_model.pytrains and compares candidate pipelines ondata/houses.csvwith cross-validation, scores the chosen one on a hold-out set once, and saves it with joblib, next to a JSON metadata file.predict_house_price.pyloads the saved pipeline, checks the scikit-learn version and prices three new listings.
The custom feature, the age of a house at sale, lives in a third file, house_features.py. This split is not decoration. A joblib file stores the import path of every class, so the prediction script can only load the model if it can import the custom transformer from a module. This project applies every part of module 34: the estimator API, a hold-out split, Pipeline, ColumnTransformer, a custom transformer, a meta-estimator, cross-validation with two metrics and persistence.
Dataset
Section titled “Dataset”data/houses.csv: 3,000 house sales from 2022 to 2024, one row per sale (see the data dictionary).
| Group | Columns | Preprocessing |
|---|---|---|
| numeric | sqft, bedrooms, bathrooms, lot_sqft, garage_spaces, has_pool, condition, distance_to_center_km, school_rating |
median imputation (lot_sqft and school_rating have 90 blanks each), then scaling |
| categorical | neighborhood (8 values) |
one-hot encoding, unknown values ignored |
| age inputs | year_built, sold_date |
custom AgeAtSale transformer, then scaling |
| target | price (USD) |
none, or a log transform inside the model |
| not used | house_id |
an identifier, not a feature |
Prices are right-skewed: most houses sell for 250,000 to 500,000 USD, and a few for more than 2 million. A model that predicts log(price) and converts back with exp often fits such targets better. sklearn.compose.TransformedTargetRegressor(regressor=..., func=np.log, inverse_func=np.exp) is a meta-estimator that does exactly this: it fits its regressor on log(y) and returns exp(prediction), so predict() and score() still work in USD.
Requirements
Section titled “Requirements”Your solution must:
- Put the column lists and a custom
AgeAtSale(TransformerMixin, BaseEstimator)inhouse_features.py.AgeAtSaleturnsyear_builtandsold_dateinto one columnage_at_saleand implementsget_feature_names_out(). - Build the preprocessing as one
ColumnTransformerwith three branches (numeric, categorical, age) inside aPipelinewith a final step namedmodel. - Hold out 20% of the rows with
train_test_split(..., random_state=42)before any fitting. - Compare three candidates with
cross_validateon the training rows, all on oneKFold(5, shuffle=True, random_state=42)object, with R² and RMSE: aDummyRegressor(strategy="median")baseline, aLinearRegressionand aLinearRegressionon the log of the price. - Print mean ± standard deviation for both metrics, choose the candidate with the lowest CV RMSE, refit it on all training rows and score it on the test rows once.
- Save the fitted pipeline to
output/house_price_model.jobliband a metadata JSON with at least the scikit-learn and NumPy versions, the feature list and the test scores. - In
predict_house_price.py, refuse to load the model when the scikit-learn or NumPy version differs, then price three listings given as a DataFrame, including one with a missinglot_sqft. - Pass
ruff check, and guard both scripts withif __name__ == "__main__":.
Step plan
Section titled “Step plan”-
Write
house_features.py. DefineNUMERIC,CATEGORICAL,AGE_INPUTSandFEATURES. WriteAgeAtSale:fit()checks that the two input columns exist, recordsn_features_in_andfeature_names_in_, and returnsself;transform()computes the sale year minusyear_builtand returns a column of shape(n, 1). -
Test the transformer alone. In the REPL, fit it on
houses[["year_built", "sold_date"]].head()and check the ages by hand. Checkget_feature_names_out(). -
Write
build_preprocessing(). It returns a freshColumnTransformeron each call, withverbose_feature_names_out=False. -
Write
candidates(). It returns a dict of three fresh pipelines. Wrap the log model inTransformedTargetRegressor. -
Cross-validate. Loop over the candidates with
cross_validate(..., scoring={"r2": "r2", "rmse": "neg_root_mean_squared_error"}). Flip the sign of the RMSE scores before you print them. -
Choose, refit and test. Pick the lowest mean RMSE. Fit it on all training rows. Compute the test R² and RMSE with
r2_scoreandroot_mean_squared_errorfromsklearn.metrics. -
Save. Create
output/,joblib.dumpthe pipeline, and write the metadata JSON. -
Write the prediction script. Load the metadata, compare its versions with
sklearn.__version__andnp.__version__before you load anything, then load the model and predict for three listings. Select the columns withmetadata["features"]so the order always matches training. -
Run both scripts from the project folder:
python train_house_model.py, thenpython predict_house_price.py.
A skeleton for the training script:
from house_features import AGE_INPUTS, CATEGORICAL, FEATURES, NUMERIC, AgeAtSale
def build_preprocessing(): ... # TODO: ColumnTransformer with "num", "cat" and "age" branches
def candidates(): ... # TODO: dict of three Pipelines: median baseline, linear, linear on log price
def main(): ... # TODO: load, split, cross-validate, choose, refit, test, save
if __name__ == "__main__": main()Rubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Custom transformer | 3 | AgeAtSale follows the estimator rules: no __init__ logic, fit() returns self, check_is_fitted in transform(), correct get_feature_names_out() |
| Pipeline design | 3 | one ColumnTransformer with three branches inside a Pipeline; nothing is fitted outside it |
| No leakage | 2 | the test rows are split off first and used only once, after the choice |
| Fair comparison | 3 | all candidates use the same KFold object, report mean ± std for R² and RMSE, and include a baseline |
| Log-target model | 2 | TransformedTargetRegressor used so predictions stay in USD |
| Persistence | 3 | the pipeline and a metadata JSON are saved; the predictor checks the version and loads the model |
| Prediction script | 2 | prices three listings, including one with a missing value, with the saved feature order |
| Code quality | 2 | ruff-clean, __main__ guards, clear names, docstrings |
| Total | 20 | 16 or more: you are ready for module 35 |
Stretch goals
Section titled “Stretch goals”- Add a
HistGradientBoostingRegressor(random_state=42)candidate with its own preprocessing (no scaling,OrdinalEncoderfor the neighborhood). Does it beat the log-linear model on CV RMSE? - Give
AgeAtSalea hyperparameterreference_year: int | None = None. With a year, it computes the age at that year instead of the sale year. Check thatget_params()shows it and thatclone()keeps it. - Add an
argparseoption--listings path.csvto the prediction script, so it prices a file of listings and writes the prices tooutput/prices.csv. - Save the five CV fold scores of the chosen model in the metadata, and make the training script refuse to overwrite the saved model when the new CV RMSE is worse than the old one.
- Replace the random split with a time-based one: train on sales before 2024-07-01 and test on the later ones. Compare the test RMSE with the random split and explain the difference.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your files with these three. Each block below is the full file. Run the scripts from the folder that holds data/ and the three files.
Reference solution
house_features.py: the shared module. Running it on its own does nothing, because it only defines names.
"""Custom features for the house price pipeline.
The trained pipeline stores a reference to ``house_features.AgeAtSale``.Any script that loads the model must be able to import this module."""
import numpy as npimport pandas as pdfrom sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.utils.validation import check_is_fitted
NUMERIC = ["sqft", "bedrooms", "bathrooms", "lot_sqft", "garage_spaces", "has_pool", "condition", "distance_to_center_km", "school_rating"]CATEGORICAL = ["neighborhood"]AGE_INPUTS = ["year_built", "sold_date"]FEATURES = NUMERIC + CATEGORICAL + AGE_INPUTS
class AgeAtSale(TransformerMixin, BaseEstimator): """Turn year_built and sold_date into one column: the age of the house at sale."""
def fit(self, X: pd.DataFrame, y=None) -> "AgeAtSale": missing = set(AGE_INPUTS) - set(X.columns) if missing: raise ValueError(f"AgeAtSale needs the columns {sorted(missing)}") self.n_features_in_ = X.shape[1] self.feature_names_in_ = np.asarray(X.columns, dtype=object) return self
def transform(self, X: pd.DataFrame) -> np.ndarray: check_is_fitted(self) sold_year = pd.to_datetime(X["sold_date"]).dt.year age = (sold_year - X["year_built"]).clip(lower=0) return age.to_numpy(dtype=np.float64).reshape(-1, 1)
def get_feature_names_out(self, input_features=None) -> np.ndarray: return np.array(["age_at_sale"], dtype=object)train_house_model.py: compare, choose, test, save.
"""Train, compare and save a house price pipeline.
Run from the project folder: python train_house_model.pyWrites output/house_price_model.joblib and output/house_price_model.json."""
import jsonfrom pathlib import Path
import joblibimport numpy as npimport pandas as pdimport sklearnfrom sklearn.compose import ColumnTransformer, TransformedTargetRegressorfrom sklearn.dummy import DummyRegressorfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_score, root_mean_squared_errorfrom sklearn.model_selection import KFold, cross_validate, train_test_splitfrom sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler
from house_features import AGE_INPUTS, CATEGORICAL, FEATURES, NUMERIC, AgeAtSale
OUTPUT = Path("output")SCORING = {"r2": "r2", "rmse": "neg_root_mean_squared_error"}
def build_preprocessing() -> ColumnTransformer: return ColumnTransformer( [ ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC), ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CATEGORICAL), ("age", make_pipeline(AgeAtSale(), StandardScaler()), AGE_INPUTS), ], verbose_feature_names_out=False, )
def candidates() -> dict[str, Pipeline]: log_linear = TransformedTargetRegressor( regressor=LinearRegression(), func=np.log, inverse_func=np.exp ) return { "median baseline": Pipeline([("prep", build_preprocessing()), ("model", DummyRegressor(strategy="median"))]), "linear": Pipeline([("prep", build_preprocessing()), ("model", LinearRegression())]), "linear, log target": Pipeline([("prep", build_preprocessing()), ("model", log_linear)]), }
def main() -> None: houses = pd.read_csv("data/houses.csv") X, y = houses[FEATURES], houses["price"] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) cv = KFold(n_splits=5, shuffle=True, random_state=42)
print(f"{'model':<20} {'CV R²':^15} {'CV RMSE (USD)':^22}") cv_rmse = {} for name, pipe in candidates().items(): res = cross_validate(pipe, X_train, y_train, cv=cv, scoring=SCORING) r2, rmse = res["test_r2"], -res["test_rmse"] cv_rmse[name] = rmse.mean() print(f"{name:<20} {r2.mean():>7.3f} ± {r2.std():.3f} " f"{rmse.mean():>11,.0f} ± {rmse.std():,.0f}")
best_name = min(cv_rmse, key=cv_rmse.get) best = candidates()[best_name].fit(X_train, y_train) pred = best.predict(X_test) test_r2 = r2_score(y_test, pred) test_rmse = root_mean_squared_error(y_test, pred) print(f"chosen: {best_name}") print(f"test R² {test_r2:.3f}, test RMSE {test_rmse:,.0f}")
OUTPUT.mkdir(exist_ok=True) joblib.dump(best, OUTPUT / "house_price_model.joblib") metadata = { "model": best_name, "sklearn_version": sklearn.__version__, "numpy_version": np.__version__, "features": FEATURES, "cv_rmse": round(float(cv_rmse[best_name]), 1), "test_r2": round(float(test_r2), 4), "test_rmse": round(float(test_rmse), 1), "n_train": len(X_train), } (OUTPUT / "house_price_model.json").write_text(json.dumps(metadata, indent=2)) print(f"saved {OUTPUT / 'house_price_model.joblib'} and its metadata")
if __name__ == "__main__": main()model CV R² CV RMSE (USD)median baseline -0.100 ± 0.021 329,422 ± 30,057linear 0.782 ± 0.038 145,481 ± 13,316linear, log target 0.879 ± 0.045 106,225 ± 12,415chosen: linear, log targettest R² 0.908, test RMSE 100,388saved output/house_price_model.joblib and its metadatapredict_house_price.py: load and price new listings in a separate process.
"""Load the saved house price pipeline and price new listings.
Run from the project folder after train_house_model.py: python predict_house_price.py"""
import jsonfrom pathlib import Path
import joblibimport numpy as npimport pandas as pdimport sklearn
MODEL = Path("output/house_price_model.joblib")METADATA = MODEL.with_suffix(".json")
def load_model(): metadata = json.loads(METADATA.read_text()) running = {"sklearn_version": sklearn.__version__, "numpy_version": np.__version__} for key, version in running.items(): if metadata[key] != version: # check before unpickling anything raise RuntimeError( f"model saved with {key} {metadata[key]}, running {version}: " "retrain or pin the environment" ) return joblib.load(MODEL), metadata # only load files you trust
def main() -> None: model, metadata = load_model() listings = pd.DataFrame( { "sqft": [1200, 2400, 3100], "bedrooms": [2, 4, 5], "bathrooms": [1.0, 2.5, 3.5], "lot_sqft": [4000, 8000, None], # unknown lot size: the imputer fills it "garage_spaces": [0, 2, 3], "has_pool": [0, 0, 1], "condition": [3, 4, 5], "distance_to_center_km": [1.5, 8.0, 12.0], "school_rating": [6, 8, 9], "neighborhood": ["Downtown", "Maple Grove", "Lakeview"], "year_built": [1965, 2004, 2021], "sold_date": ["2025-03-01", "2025-03-01", "2025-03-01"], }, index=["L1", "L2", "L3"], ) prices = model.predict(listings[metadata["features"]]) print(f"model: {metadata['model']} (test R² {metadata['test_r2']:.3f})") for listing_id, price in zip(listings.index, prices, strict=True): print(f"{listing_id}: {price:>12,.0f} USD")
if __name__ == "__main__": main()model: linear, log target (test R² 0.908)L1: 292,626 USDL2: 546,534 USDL3: 1,538,155 USDRun them from the project folder:
python train_house_model.pypython predict_house_price.pyHow it works:
- The shared module.
house_features.pyholds everything that both scripts must agree on: the column lists and theAgeAtSaleclass. The training script imports it, so the joblib file refers tohouse_features.AgeAtSale, and the prediction script can load the model. - The custom transformer.
AgeAtSalehas no hyperparameters, so it needs no__init__;BaseEstimatorstill gives itget_params()and a repr. It learns nothing, but itsfit()still checks the input and records the input names, andget_feature_names_out()names its one output column. - Fresh candidates.
candidates()builds new pipelines on each call, so the final refit cannot reuse an object thatcross_validatetouched. (cross_validateclones anyway; a fresh build keeps the intent obvious.) - The comparison. The median baseline has a negative R²: predicting one price for every house is worse than predicting the mean. The plain linear model explains about 78% of the variance. Fitting on the log of the price lifts the CV R² to about 0.88 and cuts the CV RMSE by about 40,000 USD, much more than one standard deviation. The data dictionary notes that log price is close to normal. A log target suits prices whose differences are proportional: a feature adds a percentage to the price, not a fixed amount.
- The test set. The chosen model is scored on the 600 test rows once. Its test R² of 0.908 is inside the CV range, so the CV estimate was honest.
- Persistence. The joblib file holds the whole fitted pipeline. The JSON file records the scikit-learn and NumPy versions, the features and the scores. The prediction script checks the versions before it unpickles anything, refuses a mismatch instead of risking silent changes, and it selects the columns in the saved order.
- New listings. L3 has a missing
lot_sqft, which the imputer fills with the training median. The model needs no special code for it.
Alternative: instead of TransformedTargetRegressor, train on np.log(y) directly and call np.exp(model.predict(X)) yourself. It works, but every caller must remember the exp, and score() and cross_validate then report errors in log units. The meta-estimator keeps the transform inside the saved model.