Skip to main content

Concrete + KNN: scale is the admission ticket

A distance model without a shared scale lets the widest column own the metric. One-step recipe; ports 1:1 and runs in mlfeatures today. Ported from Tidy Modeling with R, ch. 15.

Compare with R: side-by-side R ↔︎ Python · R original: test rmse 8.57 MPa.

THE MOST PORTABLE candidate: the recipe is one StepNormalize. First run
(pandas version) confirmed: ran clean, test rmse 7.94 vs R's 8.57.

PARITY NOTES:
 - The leakage beat (averaging replicate mixtures BEFORE splitting) is
   data-layer work in both languages: dplyr group_by/summarize -> polars
   group_by/agg. Deliberately outside the recipe in both.
 - Model mapping is approximate: kknn tunes neighbors/dist_power/weight_func
   (kernel weights); KNeighborsRegressor's analogs are n_neighbors/p/weights
   (only "uniform"/"distance"): same idea, coarser space.
 - The book's poly/interact variant: StepPolynomial and StepInteract (every
   pair of the selected columns) both exist, so it ports. It is left
   commented, as in R, because it is the glmnet story, not KNN's.

Docs version loads the dataset from mlfeatures.data; the research originals export these datasets from R’s modeldata at first run.

Specify

Concrete mixtures have ingredients measured in very different units (kilograms of cement versus days of age), and k-nearest neighbors judges similarity by distance. Without scaling, the widest column dominates every neighbor search, so the recipe is a single StepNormalize. Replicate mixtures are averaged before splitting so the same mixture cannot land in both the training and test sets.

import numpy as np
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 (pre-recipe, matching the book)

from mlfeatures.data import concrete
# Replicate mixtures averaged BEFORE splitting so one mixture can't appear in
# both train and test. 1,030 rows -> 992.
ingredients = [c for c in concrete.columns if c != "compressive_strength"]
concrete = (concrete.group_by(ingredients)
                    .agg(pl.col("compressive_strength").mean())
                    .sort(ingredients))  # group_by output is unordered:
                                         # sort makes the split deterministic

# ── Split (stratified by target quartile, mirroring initial_split)

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 (ports 1:1; the whole story for KNN is the shared scale)

normalized_rec = (
    Recipe(data=concrete_train, target="compressive_strength")
    .add(StepNormalize(s.features()))
)

# Variant (the book's response-surface recipe; the glmnet story, not KNN's):
# poly_rec = (
#     normalized_rec
#     .add(StepPolynomial(s.features(), degree=2))
#     .add(StepInteract(s.features(), keep_original_cols=True))
# )

# ── Model + workflow + tune

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

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

Fit

The grid search tunes the number of neighbors, the weighting, and the distance metric. The scaling is re-estimated inside each fold.

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)
fitted = normalized_rec.fit(concrete_train)   # the recipe alone

Report

The transformed test head shows every ingredient on a comparable z-score scale, followed by the best configuration and the holdout error in MPa.

print("--- best CV config ---")
print(search.best_params_, f"cv rmse: {-search.best_score_:.2f}")
print("\n--- transformed test head (z-scored ingredients) ---")
print(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(f"\ntest rmse: {rmse:.2f} MPa")
# R run result for comparison: test rmse 8.57 MPa
--- best CV config ---
{'model__n_neighbors': 8, 'model__p': 2, 'model__weights': 'distance'} cv rmse: 9.16

--- transformed test head (z-scored ingredients) ---
shape: (5, 9)
┌───────────┬───────────┬───────────┬───────────┬───┬───────────┬───────────┬───────────┬──────────┐
│ cement    ┆ blast_fur ┆ fly_ash   ┆ water     ┆ … ┆ coarse_ag ┆ fine_aggr ┆ age       ┆ compress │
│ ---       ┆ nace_slag ┆ ---       ┆ ---       ┆   ┆ gregate   ┆ egate     ┆ ---       ┆ ive_stre │
│ f64       ┆ ---       ┆ f64       ┆ f64       ┆   ┆ ---       ┆ ---       ┆ f64       ┆ ngth     │
│           ┆ f64       ┆           ┆           ┆   ┆ f64       ┆ f64       ┆           ┆ ---      │
│           ┆           ┆           ┆           ┆   ┆           ┆           ┆           ┆ f64      │
╞═══════════╪═══════════╪═══════════╪═══════════╪═══╪═══════════╪═══════════╪═══════════╪══════════╡
│ -1.133215 ┆ 1.886131  ┆ -0.857098 ┆ 0.431771  ┆ … ┆ -0.513857 ┆ 0.108344  ┆ 0.654047  ┆ 43.38    │
│ 1.066486  ┆ -0.600334 ┆ 0.600852  ┆ -1.204786 ┆ … ┆ -0.48042  ┆ 0.90472   ┆ -0.594908 ┆ 41.67    │
│ -0.602418 ┆ -0.830562 ┆ 0.700116  ┆ -1.097241 ┆ … ┆ 0.417241  ┆ 1.636189  ┆ 0.804523  ┆ 42.92    │
│ 1.56381   ┆ 1.206958  ┆ -0.857098 ┆ 0.151218  ┆ … ┆ -1.16331  ┆ -0.806616 ┆ 0.142427  ┆ 71.7     │
│ -0.814737 ┆ -0.830562 ┆ 1.084767  ┆ -0.975668 ┆ … ┆ 1.449936  ┆ 0.375467  ┆ 0.142427  ┆ 38.56    │
└───────────┴───────────┴───────────┴───────────┴───┴───────────┴───────────┴───────────┴──────────┘

test rmse: 7.94 MPa