TMWR-03 · ames realistic + 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: CV rmse 0.0791 · Python ran: CV 0.0780, test rmse 0.0792 / rsq 0.789. The full recipe runs; StepOther pools unseen fold-levels, so every CV fold scores.

R: tidymodels

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

library(tidymodels)
tidymodels_prefer()






# Data + target transform --------------------------------------------------
# Six features now (adds Latitude/Longitude); log10 the target pre-split.

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



# Split --------------------------------------------------------------------
# Stratified 80/20 split on the target (same as TMWR-01).

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 canonical recipe. Ordering is load-bearing twice: other pools rare
# levels BEFORE dummy; interact targets the GENERATED Bldg_Type_* columns.
#
#
#

ames_rec <-
  recipe(Sale_Price ~ Neighborhood + Gr_Liv_Area + Year_Built +
           Bldg_Type + Latitude + Longitude, data = ames_train) %>%
  step_log(Gr_Liv_Area, base = 10) %>%
  step_other(Neighborhood, threshold = 0.01) %>%
  step_dummy(all_nominal_predictors()) %>%
  step_interact( ~ Gr_Liv_Area:starts_with("Bldg_Type_") ) %>%
  step_ns(Latitude, Longitude, deg_free = 20)



# Model + workflow ---------------------------------------------------------
# Bind the recipe to a linear model.
#
#

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

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



# Resampled performance ----------------------------------------------------
# 5-fold CV estimate of the whole pipeline (recipe re-fit per fold).
#
#

set.seed(1001)
ames_folds <- vfold_cv(ames_train, v = 5)

lm_res <- fit_resamples(lm_wflow, resamples = ames_folds)
collect_metrics(lm_res)
# run result: CV rmse 0.0791, rsq 0.798


# Final fit + proof + metrics ----------------------------------------------
# Fit on all of training; transform the test set; score once.

lm_fit <- fit(lm_wflow, ames_train)

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)


Python: mlfeatures + sklearn

# Setup --------------------------------------------------------------------
# Load the modeling stack.
# DIFF: adds cross-validation imports; otherwise as TMWR-01.

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 --------------------------------------------------
# Six features now (adds Latitude/Longitude); log10 the target pre-split.

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 split on the target (same as TMWR-01).

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 canonical recipe. Ordering is load-bearing twice: other pools rare
# levels BEFORE dummy; interact targets the GENERATED Bldg_Type_* columns.
# DIFF: StepInteract multiplies every pair in its selection, so it also adds
# the dummy-by-dummy products R's formula omits; they are all zero.
# DIFF: keep_original_cols=True keeps the source columns, as R does.

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 ---------------------------------------------------------
# Bind the recipe to a linear model.
# DIFF: Pipeline + RecipeTransformer = workflow(); the X/y split is sklearn
# idiom: RecipeTransformer re-joins y as the target internally.

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

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

# Resampled performance ----------------------------------------------------
# 5-fold CV estimate of the whole pipeline (recipe re-fit per fold).
# DIFF: fit_resamples -> cross_val_score over the Pipeline; both re-estimate
# the recipe inside each fold, so there's no leakage in either language.

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(cv_rmse.mean())
# ran: 0.0780 (R: 0.0791); StepOther pools unseen fold-levels, so every
# fold scores

# Final fit + proof + metrics ----------------------------------------------
# Fit on all of training; transform the test set; score once.

lm_wflow.fit(X_train, y_train)

X_test = ames_test.drop("Sale_Price")
y_test = ames_test["Sale_Price"]
ames_rec.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)