Skip to main content

Ames realistic: the canonical linear-model recipe

The workhorse recipe TMwR grows step by motivated step: log, pool rare neighborhoods, dummy-encode, interact, spline. Ported from Tidy Modeling with R, ch. 8.

Compare with R: side-by-side R ↔︎ Python · R original (full recipe): CV rmse 0.0791, test rsq 0.798.

THE FULL TMWR RECIPE: log, pool rare levels, dummy, interact, spline. Every
step runs inside the recipe, so the fitted recipe replays all of it, including
in each cross-validation fold.

PARITY NOTES:
 - step_log -> StepLog(s.col("Gr_Liv_Area"), base=10). The target is still
   logged outside the recipe, as in TMwR Ch. 5.
 - step_other(Neighborhood, 0.01) -> StepOther(..., threshold=0.01). Rare
   levels, and levels unseen at fit time, pool into "other", so a level that
   only appears in a CV fold (e.g. 'Landmark') no longer nulls predictions
   (a run without this step scored cross_val_score = nan).
 - step_interact(~ Gr_Liv_Area:starts_with("Bldg_Type_")) -> StepInteract over
   Gr_Liv_Area and the Bldg_Type_ dummies, with keep_original_cols=True. It
   multiplies every pair in its selection, so it also adds the dummy-by-dummy
   products R's formula omits; they are all zero (one building type excludes
   the others), so they add nothing to the fit.
 - step_ns(Latitude, Longitude, deg_free = 20) -> StepSplineNatural.

Docs version loads the dataset from mlfeatures.data; the research originals export these datasets from R’s modeldata at first run.

Specify

This recipe adds three steps to the mini version, each answering a problem the data has. StepOther pools rare neighborhoods (and any level unseen at fit time) into “other” so dummy columns stay stable. StepInteract lets the effect of living area differ by building type. StepSplineNatural lets latitude and longitude act non-linearly, which is how a linear model captures neighborhood-scale geography.

import numpy as np
import polars as pl
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.pipeline import Pipeline

from mlfeatures import (Recipe, RecipeTransformer, StepDummy, StepInteract,
                        StepLog, StepOther, StepSplineNatural)
from mlfeatures import Selectors as s

# ── Data + target transform (outside the recipe, per TMwR Ch. 5)

from mlfeatures.data import ames
ames = ames.select(["Neighborhood", "Gr_Liv_Area", "Year_Built", "Bldg_Type",
                    "Latitude", "Longitude", "Sale_Price"])
ames = ames.with_columns(pl.col("Sale_Price").log(base=10))

# ── Split (stratified 80/20 by target quartile)

strata = ames["Sale_Price"].qcut(4, labels=["q1", "q2", "q3", "q4"])
ames_train, ames_test = train_test_split(
    ames, train_size=0.80, stratify=strata, random_state=502
)

# ── Recipe (the full ames_rec)

ames_rec = (
    Recipe(data=ames_train, target="Sale_Price")
    .add(StepLog(s.col("Gr_Liv_Area"), base=10))
    .add(StepOther(s.col("Neighborhood"), threshold=0.01))
    .add(StepDummy(s.nominal_features()))
    .add(StepInteract(s.col("Gr_Liv_Area") | s.starts_with("Bldg_Type_"),
                      keep_original_cols=True))
    .add(StepSplineNatural(s.col("Latitude", "Longitude"), deg_free=20))
)

# ── Model + workflow

lm_wflow = Pipeline([
    ("recipe", RecipeTransformer(ames_rec)),
    ("model", LinearRegression()),
])

Fit

Because every step lives inside the recipe, cross-validation re-estimates the whole chain on each fold, so nothing leaks from the held-out fold into the preprocessing.

X_train = ames_train.drop("Sale_Price")
y_train = ames_train["Sale_Price"]

# Resampled performance (5-fold, mirroring fit_resamples):
cv = KFold(n_splits=5, shuffle=True, random_state=1001)
cv_rmse = -cross_val_score(lm_wflow, X_train, y_train, cv=cv,
                           scoring="neg_root_mean_squared_error")
print(f"--- 5-fold CV rmse: {cv_rmse.mean():.4f} (+/- {cv_rmse.std():.4f}) ---")
# StepOther pools rare and unseen levels at fit time, so every fold scores.

# Final fit on the full training set:
lm_wflow.fit(X_train, y_train)
fitted = ames_rec.fit(ames_train)
--- 5-fold CV rmse: 0.0780 (+/- 0.0040) ---

Report

The transformed head is much wider than the mini example’s: dummy columns, interaction terms, and the spline basis for each coordinate. Compare the holdout rmse with the mini recipe to see what the extra steps bought.

print("\n--- transformed test head ---")
print(fitted.transform(ames_test).head())

# ── Holdout metrics

X_test = ames_test.drop("Sale_Price")
y_test = ames_test["Sale_Price"]
pred = lm_wflow.predict(X_test)
rmse = float(((y_test - pred) ** 2).mean() ** 0.5)
rsq = float(pl.DataFrame({"y": y_test, "pred": pred})
            .select(pl.corr("y", "pred")).item() ** 2)
print(f"\nrmse: {rmse:.4f}   rsq: {rsq:.3f}")
# R run (full recipe): CV rmse 0.0791, test rsq 0.798

--- transformed test head ---
shape: (5, 77)
┌───────────┬───────────┬───────────┬───────────┬───┬───────────┬───────────┬───────────┬──────────┐
│ Gr_Liv_Ar ┆ Year_Buil ┆ Latitude_ ┆ Latitude_ ┆ … ┆ Bldg_Type ┆ Bldg_Type ┆ Bldg_Type ┆ Bldg_Typ │
│ ea        ┆ t         ┆ 1         ┆ 2         ┆   ┆ _OneFam_x ┆ _Twnhs_x_ ┆ _Twnhs_x_ ┆ e_TwnhsE │
│ ---       ┆ ---       ┆ ---       ┆ ---       ┆   ┆ _Bldg_Typ ┆ Bldg_Type ┆ Bldg_Type ┆ _x_Bldg_ │
│ f64       ┆ i64       ┆ f64       ┆ f64       ┆   ┆ e_T…      ┆ _Tw…      ┆ _Tw…      ┆ Type_T…  │
│           ┆           ┆           ┆           ┆   ┆ ---       ┆ ---       ┆ ---       ┆ ---      │
│           ┆           ┆           ┆           ┆   ┆ i8        ┆ i8        ┆ i8        ┆ i8       │
╞═══════════╪═══════════╪═══════════╪═══════════╪═══╪═══════════╪═══════════╪═══════════╪══════════╡
│ 3.0       ┆ 1963      ┆ 0.0       ┆ 0.0       ┆ … ┆ 0         ┆ 0         ┆ 0         ┆ 0        │
│ 3.410609  ┆ 2007      ┆ 0.0       ┆ 0.0       ┆ … ┆ 0         ┆ 0         ┆ 0         ┆ 0        │
│ 3.05423   ┆ 1950      ┆ 0.0       ┆ 0.0       ┆ … ┆ 0         ┆ 0         ┆ 0         ┆ 0        │
│ 3.142076  ┆ 1967      ┆ 0.0       ┆ 0.0       ┆ … ┆ 0         ┆ 0         ┆ 0         ┆ 0        │
│ 3.133539  ┆ 1969      ┆ 0.320184  ┆ 0.019286  ┆ … ┆ 0         ┆ 0         ┆ 0         ┆ 0        │
└───────────┴───────────┴───────────┴───────────┴───┴───────────┴───────────┴───────────┴──────────┘

rmse: 0.0792   rsq: 0.789