TMWR-14 · concrete + KNN: 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 8.57 · Python ran: 7.94. Ports 1:1 and runs clean.

R: tidymodels

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

library(tidymodels)
tidymodels_prefer()





# Data + the leakage beat --------------------------------------------------
# Average replicate mixtures BEFORE splitting, so one mixture can't appear
# in both train and test. Data-layer work, pre-recipe, in both languages.
#
#
#

data(concrete, package = "modeldata")

concrete <- concrete %>%
  group_by(across(-compressive_strength)) %>%
  summarize(compressive_strength = mean(compressive_strength),
            .groups = "drop")   # 1,030 rows -> 992

# Split --------------------------------------------------------------------
# Stratified 75/25 split on the target.

set.seed(1501)
concrete_split <- initial_split(concrete, strata = compressive_strength)
concrete_train <- training(concrete_split)
concrete_test  <- testing(concrete_split)


# Recipe -------------------------------------------------------------------
# One step. "KNN ... require predictors that have been centered and scaled."
#
#
#

normalized_rec <-
  recipe(compressive_strength ~ ., data = concrete_train) %>%
  step_normalize(all_predictors())

# poly_recipe <- normalized_rec %>%
#    step_poly(all_predictors()) %>%
#    step_interact(~ all_predictors():all_predictors())



# Model + tune -------------------------------------------------------------
# Tune the neighborhood over 5-fold CV.
#
#
#

knn_spec <-
  nearest_neighbor(neighbors = tune(), dist_power = tune(),
                   weight_func = tune()) %>%
  set_engine("kknn") %>%
  set_mode("regression")

knn_wflow <- workflow() %>%
  add_recipe(normalized_rec) %>%
  add_model(knn_spec)

set.seed(1502)
concrete_folds <- vfold_cv(concrete_train, v = 5)

set.seed(1503)
knn_tune <- tune_grid(knn_wflow, resamples = concrete_folds,
                      grid = 6)
show_best(knn_tune, metric = "rmse", n = 3)

# Finalize + proof + metrics -----------------------------------------------
# Refit the best config; transform the test set; score once.

best_knn  <- select_best(knn_tune, metric = "rmse")
final_res <- knn_wflow %>%
  finalize_workflow(best_knn) %>%
  last_fit(concrete_split)

final_res %>% extract_recipe(estimated = TRUE) %>%
  bake(new_data = concrete_test) %>% head()
collect_metrics(final_res)   # run: test rmse 8.57 MPa

Python: mlfeatures + sklearn

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

import polars as pl
from sklearn.model_selection import GridSearchCV, KFold, train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import Pipeline
from mlfeatures import Recipe, RecipeTransformer, StepNormalize
from mlfeatures import Selectors as s

# Data + the leakage beat --------------------------------------------------
# Average replicate mixtures BEFORE splitting, so one mixture can't appear
# in both train and test. Data-layer work, pre-recipe, in both languages.
# DIFF: concrete ships in mlfeatures.data (exported from modeldata::concrete).
# DIFF: dplyr group_by/summarize -> polars group_by/agg. group_by's output is
# unordered, so the sort restores determinism.

from mlfeatures.data import concrete
ingredients = [c for c in concrete.columns
               if c != "compressive_strength"]
concrete = (concrete.group_by(ingredients)
            .agg(pl.col("compressive_strength").mean())
            .sort(ingredients))   # 1,030 -> 992

# Split --------------------------------------------------------------------
# Stratified 75/25 split on the target.

strata = (concrete["compressive_strength"]
          .qcut(4, labels=["q1","q2","q3","q4"]))
concrete_train, concrete_test = train_test_split(
    concrete, train_size=0.75, stratify=strata, random_state=1501
)

# Recipe -------------------------------------------------------------------
# One step. "KNN ... require predictors that have been centered and scaled."
# DIFF: none; StepNormalize ports step_normalize exactly.
# DIFF (variant only): the poly/interact response surface is
# StepPolynomial + StepInteract (every pair of the selected columns).

normalized_rec = (
    Recipe(data=concrete_train, target="compressive_strength")
    .add(StepNormalize(s.features()))
)
# poly_rec = (
#     normalized_rec
#     .add(StepPolynomial(s.features(), degree=2))
#     .add(StepInteract(s.features(), keep_original_cols=True))
# )

# Model + tune -------------------------------------------------------------
# Tune the neighborhood over 5-fold CV.
# DIFF: kknn tunes neighbors / dist_power / weight_func (kernel weights);
# sklearn's analogs are n_neighbors / p / weights (only uniform-vs-distance);
# same idea, coarser space, so best configs won't match exactly.

pipe = Pipeline([
    ("recipe", RecipeTransformer(normalized_rec)),
    ("model", KNeighborsRegressor()),
])

param_grid = {
    "model__n_neighbors": [4, 8, 12, 16],
    "model__weights": ["uniform", "distance"],
    "model__p": [1, 2],
}
cv = KFold(n_splits=5, shuffle=True, random_state=1502)

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

# Finalize + proof + metrics -----------------------------------------------
# Refit the best config; transform the test set; score once.

# refit already happened (refit=True)
fitted = normalized_rec.fit(concrete_train)
fitted.transform(concrete_test).head()

X_test = concrete_test.drop("compressive_strength")
y_test = concrete_test["compressive_strength"]
pred = search.predict(X_test)
rmse = float(((y_test - pred) ** 2).mean() ** 0.5)
print(rmse)                  # ran: 7.94 (R test: 8.57; distance weights won)