Skip to content

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:

  1. train_house_model.py trains and compares candidate pipelines on data/houses.csv with cross-validation, scores the chosen one on a hold-out set once, and saves it with joblib, next to a JSON metadata file.
  2. predict_house_price.py loads 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.

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.

Your solution must:

  1. Put the column lists and a custom AgeAtSale(TransformerMixin, BaseEstimator) in house_features.py. AgeAtSale turns year_built and sold_date into one column age_at_sale and implements get_feature_names_out().
  2. Build the preprocessing as one ColumnTransformer with three branches (numeric, categorical, age) inside a Pipeline with a final step named model.
  3. Hold out 20% of the rows with train_test_split(..., random_state=42) before any fitting.
  4. Compare three candidates with cross_validate on the training rows, all on one KFold(5, shuffle=True, random_state=42) object, with R² and RMSE: a DummyRegressor(strategy="median") baseline, a LinearRegression and a LinearRegression on the log of the price.
  5. 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.
  6. Save the fitted pipeline to output/house_price_model.joblib and a metadata JSON with at least the scikit-learn and NumPy versions, the feature list and the test scores.
  7. 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 missing lot_sqft.
  8. Pass ruff check, and guard both scripts with if __name__ == "__main__":.
  1. Write house_features.py. Define NUMERIC, CATEGORICAL, AGE_INPUTS and FEATURES. Write AgeAtSale: fit() checks that the two input columns exist, records n_features_in_ and feature_names_in_, and returns self; transform() computes the sale year minus year_built and returns a column of shape (n, 1).

  2. Test the transformer alone. In the REPL, fit it on houses[["year_built", "sold_date"]].head() and check the ages by hand. Check get_feature_names_out().

  3. Write build_preprocessing(). It returns a fresh ColumnTransformer on each call, with verbose_feature_names_out=False.

  4. Write candidates(). It returns a dict of three fresh pipelines. Wrap the log model in TransformedTargetRegressor.

  5. 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.

  6. Choose, refit and test. Pick the lowest mean RMSE. Fit it on all training rows. Compute the test R² and RMSE with r2_score and root_mean_squared_error from sklearn.metrics.

  7. Save. Create output/, joblib.dump the pipeline, and write the metadata JSON.

  8. Write the prediction script. Load the metadata, compare its versions with sklearn.__version__ and np.__version__ before you load anything, then load the model and predict for three listings. Select the columns with metadata["features"] so the order always matches training.

  9. Run both scripts from the project folder: python train_house_model.py, then python predict_house_price.py.

A skeleton for the training script:

train_house_model.py (starter)
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()
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
  1. Add a HistGradientBoostingRegressor(random_state=42) candidate with its own preprocessing (no scaling, OrdinalEncoder for the neighborhood). Does it beat the log-linear model on CV RMSE?
  2. Give AgeAtSale a hyperparameter reference_year: int | None = None. With a year, it computes the age at that year instead of the sale year. Check that get_params() shows it and that clone() keeps it.
  3. Add an argparse option --listings path.csv to the prediction script, so it prices a file of listings and writes the prices to output/prices.csv.
  4. 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.
  5. 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.

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.

house_features.py
"""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 np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from 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_house_model.py
"""Train, compare and save a house price pipeline.
Run from the project folder: python train_house_model.py
Writes output/house_price_model.joblib and output/house_price_model.json.
"""
import json
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import sklearn
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.dummy import DummyRegressor
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, root_mean_squared_error
from sklearn.model_selection import KFold, cross_validate, train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from 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()
Output
model CV R² CV RMSE (USD)
median baseline -0.100 ± 0.021 329,422 ± 30,057
linear 0.782 ± 0.038 145,481 ± 13,316
linear, log target 0.879 ± 0.045 106,225 ± 12,415
chosen: linear, log target
test R² 0.908, test RMSE 100,388
saved output/house_price_model.joblib and its metadata

predict_house_price.py: load and price new listings in a separate process.

predict_house_price.py
"""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 json
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import 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()
Output
model: linear, log target (test R² 0.908)
L1: 292,626 USD
L2: 546,534 USD
L3: 1,538,155 USD

Run them from the project folder:

Terminal
python train_house_model.py
python predict_house_price.py

How it works:

  1. The shared module. house_features.py holds everything that both scripts must agree on: the column lists and the AgeAtSale class. The training script imports it, so the joblib file refers to house_features.AgeAtSale, and the prediction script can load the model.
  2. The custom transformer. AgeAtSale has no hyperparameters, so it needs no __init__; BaseEstimator still gives it get_params() and a repr. It learns nothing, but its fit() still checks the input and records the input names, and get_feature_names_out() names its one output column.
  3. Fresh candidates. candidates() builds new pipelines on each call, so the final refit cannot reuse an object that cross_validate touched. (cross_validate clones anyway; a fresh build keeps the intent obvious.)
  4. 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.
  5. 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.
  6. 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.
  7. 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.