TMWR-01 · ames-mini + lm: R vs Python, line-matched

Identical section banners and shared descriptions in both scripts; ochre DIFF comments (Python side only, R holds a blank #) explain what changes; red = mlfeatures gap. R: rmse 0.0764 / rsq 0.824 · Python ran: 0.0825 / 0.771. Same recipe, different split rows (seeds can't transfer).

R: tidymodels

# Setup --------------------------------------------------------------------
# Load the modeling stack.
#

library(tidymodels)
tidymodels_prefer()





# Data + target transform --------------------------------------------------
# Four features; log10 the target BEFORE the recipe.
#
#
#

data(ames, package = "modeldata")
ames <- ames %>% mutate(Sale_Price = log10(Sale_Price))

# (Gr_Liv_Area is logged INSIDE the recipe, below)

# Split --------------------------------------------------------------------
# Stratified 80/20 split on the target.
#
#

set.seed(502)
ames_split <- initial_split(ames, prop = 0.80, strata = Sale_Price)
ames_train <- training(ames_split)
ames_test  <- testing(ames_split)

# Recipe -------------------------------------------------------------------
# The book's first recipe: the formula's implicit preprocessing made explicit.
#
#

simple_ames <-
  recipe(Sale_Price ~ Neighborhood + Gr_Liv_Area +
           Year_Built + Bldg_Type, data = ames_train) %>%
  step_log(Gr_Liv_Area, base = 10) %>%
  step_dummy(all_nominal_predictors())

# Model + fit --------------------------------------------------------------
# Bind recipe + lm; fit on the training set.
#
#

lm_model <- linear_reg() %>% set_engine("lm")

lm_wflow <- workflow() %>%
  add_model(lm_model) %>%
  add_recipe(simple_ames)

lm_fit <- fit(lm_wflow, ames_train)


# Proof + holdout metrics --------------------------------------------------
# Transform the test set; score once.
#
#
#

extract_recipe(lm_fit, estimated = TRUE) %>%
  bake(new_data = ames_test) %>%
  head()

predict(lm_fit, ames_test) %>%
  bind_cols(ames_test %>% select(Sale_Price)) %>%
  reg_metrics(truth = Sale_Price, estimate = .pred)
# run result: rmse 0.0764, rsq 0.824 (log10 units)



Python: mlfeatures + sklearn

# Setup --------------------------------------------------------------------
# Load the modeling stack.
# DIFF: tidymodels bundles everything; Python assembles polars + sklearn + mlfeatures.

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 --------------------------------------------------
# Four features; log10 the target BEFORE the recipe.
# DIFF: ames ships in mlfeatures.data (exported from modeldata::ames).
# DIFF: only the target is logged here; Gr_Liv_Area is logged inside the
# recipe by StepLog, so the fitted recipe replays it on new data frames.

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 split on the target.
# DIFF: explicit quartile binning (qcut); seeds don't transfer across
# languages: same design, different rows.

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 book's first recipe: the formula's implicit preprocessing made explicit.
# DIFF: StepLog = step_log; the fitted recipe replays it on new data frames.
# DIFF: StepDummy = step_dummy (k-1 indicators, reference level dropped).

simple_ames = (
    Recipe(data=ames_train, target="Sale_Price")
    .add(StepLog(s.col("Gr_Liv_Area"), base=10))
    .add(StepDummy(s.nominal_features()))
)

# Model + fit --------------------------------------------------------------
# Bind recipe + lm; fit on the training set.
# DIFF: Pipeline + RecipeTransformer = workflow(); the X/y split is sklearn
# idiom: RecipeTransformer re-joins y as the target internally.

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

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

# Proof + holdout metrics --------------------------------------------------
# Transform the test set; score once.
# DIFF: metric_set(rmse, rsq) -> polars expressions. y stays a polars Series
# through all of sklearn (fit, CV, predict, metrics); the one thing to avoid
# is np.mean() on a polars Series (numpy passes axis=).

X_test = ames_test.drop("Sale_Price")
y_test = ames_test["Sale_Price"]
simple_ames.fit(ames_train).transform(ames_test).head()

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)


# ran: rmse 0.0825, rsq 0.771 (R: 0.0764/0.824, split-row luck)