import numpy as np
import polars as pl
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from mlfeatures import Recipe, RecipeTransformer, StepDummy, StepLog
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",
"Sale_Price"])
ames = ames.with_columns(pl.col("Sale_Price").log(base=10))
# ── Split (stratified 80/20 by target quartile, mirroring initial_split)
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 (simple_ames: log the living area, then dummy-encode)
simple_ames = (
Recipe(data=ames_train, target="Sale_Price")
.add(StepLog(s.col("Gr_Liv_Area"), base=10))
.add(StepDummy(s.nominal_features()))
)
# ── Model + workflow (sklearn Pipeline via RecipeTransformer)
lm_wflow = Pipeline([
("recipe", RecipeTransformer(simple_ames)),
("model", LinearRegression()),
])Ames mini: a first linear regression
The book’s first recipe: the R formula’s implicit preprocessing made explicit and sequential. Deliberately tiny: the end-to-end arc is the lesson. Ported from Tidy Modeling with R, ch. 8.
Compare with R: side-by-side R ↔︎ Python · R original: test rmse 0.0764, rsq 0.824 (log10 units).
PARITY NOTES:
- step_log(Gr_Liv_Area, base = 10) -> StepLog(s.col("Gr_Liv_Area"), base=10),
inside the recipe, so the fitted recipe replays it on new data frames. The
target is still logged outside the recipe, as in TMwR Ch. 5.
- StepDummy = step_dummy (k-1 indicators, first level as reference).
- Seeds don't transfer across languages; stratified 80/20 design matches.
Docs version loads the dataset from mlfeatures.data; the research originals export these datasets from R’s modeldata at first run.
Specify
Predict the log10 sale price of a house from its neighborhood, living area, year built, and building type. The recipe has two steps: log the living area so its skewed distribution is closer to linear in the target, then dummy-encode the nominal features, since a linear model cannot read strings. The recipe is wrapped in a scikit-learn Pipeline so the model and its preprocessing travel together.
Fit
Fitting the pipeline estimates the recipe on the training data and trains the model on the transformed result. Fitting the recipe alone gives a trained recipe we can inspect.
X_train = ames_train.drop("Sale_Price")
y_train = ames_train["Sale_Price"]
lm_wflow.fit(X_train, y_train) # the sklearn pipeline
fitted = simple_ames.fit(ames_train) # the recipe aloneReport
The transformed test data shows the log applied to Gr_Liv_Area and the dummy columns replacing the nominal ones. The holdout metrics are computed on log10 units, so an rmse of about 0.08 corresponds to a typical error of roughly 20% in dollars.
print("--- 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 result for comparison: rmse 0.0764, rsq 0.824 (log10 units)--- transformed test head ---
shape: (5, 34)
┌───────────┬───────────┬───────────┬───────────┬───┬───────────┬───────────┬───────────┬──────────┐
│ Gr_Liv_Ar ┆ Year_Buil ┆ Sale_Pric ┆ Neighborh ┆ … ┆ Bldg_Type ┆ Bldg_Type ┆ Bldg_Type ┆ Bldg_Typ │
│ ea ┆ t ┆ e ┆ ood_Blues ┆ ┆ _OneFam ┆ _Twnhs ┆ _TwnhsE ┆ e_TwoFmC │
│ --- ┆ --- ┆ --- ┆ te ┆ ┆ --- ┆ --- ┆ --- ┆ on │
│ f64 ┆ i64 ┆ f64 ┆ --- ┆ ┆ i8 ┆ i8 ┆ i8 ┆ --- │
│ ┆ ┆ ┆ i8 ┆ ┆ ┆ ┆ ┆ i8 │
╞═══════════╪═══════════╪═══════════╪═══════════╪═══╪═══════════╪═══════════╪═══════════╪══════════╡
│ 3.0 ┆ 1963 ┆ 5.214844 ┆ 0 ┆ … ┆ 1 ┆ 0 ┆ 0 ┆ 0 │
│ 3.410609 ┆ 2007 ┆ 5.440909 ┆ 0 ┆ … ┆ 1 ┆ 0 ┆ 0 ┆ 0 │
│ 3.05423 ┆ 1950 ┆ 5.108903 ┆ 0 ┆ … ┆ 1 ┆ 0 ┆ 0 ┆ 0 │
│ 3.142076 ┆ 1967 ┆ 5.161368 ┆ 0 ┆ … ┆ 1 ┆ 0 ┆ 0 ┆ 0 │
│ 3.133539 ┆ 1969 ┆ 5.146128 ┆ 0 ┆ … ┆ 1 ┆ 0 ┆ 0 ┆ 0 │
└───────────┴───────────┴───────────┴───────────┴───┴───────────┴───────────┴───────────┴──────────┘
rmse: 0.0825 rsq: 0.771