TMWR-11 · ames + xgboost: 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: test rmse 0.0730 (best CV 0.0773) · Python ran: test 0.0771 / rsq 0.800.

R: tidymodels

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

library(tidymodels)
tidymodels_prefer()





# Data + target transform --------------------------------------------------
# Ames housing; log10 the target BEFORE the recipe (target transforms
# don't belong inside it: they fail at predict time).
#
#
#

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

# (predictors declared in the recipe formula, 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 usemodels "minimal preprocessing for xgboost": guard unseen levels,
# one-hot encode, drop zero-variance columns.
#
#
#
#
#

xgboost_recipe <-
  recipe(Sale_Price ~ Neighborhood + Gr_Liv_Area + Year_Built +
           Bldg_Type + Latitude + Longitude, data = ames_train) %>%
  step_novel(all_nominal_predictors()) %>%
  step_dummy(all_nominal_predictors(), one_hot = TRUE) %>%
  step_zv(all_predictors())

# Model spec + workflow ----------------------------------------------------
# Bind recipe + model; trees and learn_rate will be tuned.
#
#

xgboost_spec <-
  boost_tree(trees = tune(), learn_rate = tune()) %>%
  set_mode("regression") %>%
  set_engine("xgboost")

xgboost_workflow <-
  workflow() %>%
  add_recipe(xgboost_recipe) %>%
  add_model(xgboost_spec)

# Resamples + grid + tune --------------------------------------------------
# 5-fold CV over the same 2 x 3 grid (trees x learn_rate).
#
#
#
#

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

xgb_grid <- crossing(
  trees      = c(500, 1000),
  learn_rate = c(0.01, 0.05, 0.1)
)

set.seed(69305)
xgboost_tune <- tune_grid(xgboost_workflow,
                          resamples = ames_folds,
                          grid = xgb_grid)
show_best(xgboost_tune, metric = "rmse", n = 3)

# Finalize + test metrics --------------------------------------------------
# Refit the best config on all training data; evaluate once on the test set.
#
#

best_xgb  <- select_best(xgboost_tune, metric = "rmse")
final_res <- xgboost_workflow %>%
  finalize_workflow(best_xgb) %>%
  last_fit(ames_split)
collect_metrics(final_res)  # run result: test rmse 0.0730 (log10)

# Proof the recipe stands alone --------------------------------------------
# Transform new data with no model attached.
#
#

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

Python: mlfeatures + sklearn

# Setup --------------------------------------------------------------------
# Load the modeling stack.
# DIFF: tidymodels is one meta-package; Python assembles polars + sklearn
# + xgboost + mlfeatures (xgboost's polars path needs pyarrow).

import polars as pl
from sklearn.model_selection import GridSearchCV, KFold, train_test_split
from sklearn.pipeline import Pipeline
from xgboost import XGBRegressor
from mlfeatures import Recipe, RecipeTransformer, StepDropZeroVariance, StepOneHot
from mlfeatures import Selectors as s

# Data + target transform --------------------------------------------------
# Ames housing; log10 the target BEFORE the recipe (target transforms
# don't belong inside it: they fail at predict time).
# DIFF: ames ships in mlfeatures.data (exported from modeldata::ames).
# DIFF: the bundled copy holds plain strings, not factors; fine, because
# nominal_features() matches them (categorical_features() would not).

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.
# DIFF: explicit quartile binning (qcut) does what initial_split(strata=)
# does internally.
# DIFF: 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 usemodels "minimal preprocessing for xgboost": guard unseen levels,
# one-hot encode, drop zero-variance columns.
# DIFF (GAP): step_novel() has no mlfeatures analog yet; StepNovel is unbuilt and
# StepUnknown fills only nulls. Omitted here; StepOneHot warns and emits
# nulls for unseen levels at transform instead.
# DIFF: Recipe(target=...) roles replace the R formula; selectors pick
# columns by kind.

xgboost_recipe = (
    Recipe(data=ames_train, target="Sale_Price")
    .add(StepOneHot(s.nominal_features()))
    .add(StepDropZeroVariance(s.features()))
)


# Model spec + workflow ----------------------------------------------------
# Bind recipe + model; trees and learn_rate will be tuned.
# DIFF: Pipeline + RecipeTransformer = workflow(); the tune() markers move
# into param_grid (next section): sklearn declares tunables at search time.

pipe = Pipeline([
    ("recipe", RecipeTransformer(xgboost_recipe)),
    ("model", XGBRegressor(objective="reg:squarederror",
                           random_state=69305)),
])





# Resamples + grid + tune --------------------------------------------------
# 5-fold CV over the same 2 x 3 grid (trees x learn_rate).
# DIFF: GridSearchCV is three tidymodels verbs in one object:
# tune_grid (search) + select_best (pick) + refit on full train (refit=True).
# DIFF: sklearn separates X from y; RecipeTransformer re-joins y as the
# target internally, so the recipe still sees one data frame.

cv = KFold(n_splits=5, shuffle=True, random_state=1001)

param_grid = {
    "model__n_estimators": [500, 1000],
    "model__learning_rate": [0.01, 0.05, 0.1],
}

X_train = ames_train.drop("Sale_Price")
y_train = ames_train["Sale_Price"]
search = GridSearchCV(pipe, param_grid, cv=cv,
                      scoring="neg_root_mean_squared_error",
                      refit=True)
search.fit(X_train, y_train)

# Finalize + test metrics --------------------------------------------------
# Refit the best config on all training data; evaluate once on the test set.
# DIFF: last_fit() is one verb for refit-and-evaluate; the refit already
# happened (refit=True), so only the scoring remains.

X_test = ames_test.drop("Sale_Price")
y_test = ames_test["Sale_Price"]
pred  = search.predict(X_test)
rmse  = float(((y_test - pred) ** 2).mean() ** 0.5)
print(rmse)                 # ran: 0.0771 (R test: 0.0730)

# Proof the recipe stands alone --------------------------------------------
# Transform new data with no model attached.
# DIFF (mlfeatures-only): the lineage query (which columns did the one-hot step
# produce?) has no recipes equivalent (name-prefix matching is the R workaround).

fitted = xgboost_recipe.fit(ames_train)
fitted.transform(ames_train).head()

fitted.lineage.columns_from_source("one_hot")[:8]