Skip to main content

Beans PCA: a recipe with no model

The recipe is the product: extraction estimated on training data, judged on the validation set. No estimator anywhere. Ported from Tidy Modeling with R, ch. 16.

Compare with R: side-by-side R ↔︎ Python · R original: PC1–PC4 variance 59.4 / 24.4 / … (with orderNorm).

The recipe IS the product: preprocessing estimated on training data, judged
visually on the validation set. No estimator anywhere.

PARITY NOTES:
 - step_orderNorm -> StepOrderNorm, step_pca -> StepPca(num_comp=4). Both are
   steps of the recipe, so the fitted recipe produces the PC scores itself.
   PC1-4 variance explained comes out as 59.44 / 24.42 / 6.95 / 5.44%, which
   matches R's 59.4 / 24.4 for the first two components.
 - R composes by piping MORE steps onto an already-prep()ed recipe and
   re-prepping; mlfeatures has no incremental fit. pca_rec is bean_rec plus
   StepPca, and is fit from the training data.
 - mlfeatures has no public accessor for a fitted step's loadings (R's
   tidy(id = "pca")), so the top-loadings table is not reproduced; variance
   explained is computed from the scores instead.

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

Specify

The bean measurements are strongly skewed and highly correlated. The base recipe drops constant columns, maps each numeric column to a normal shape with StepOrderNorm, and standardizes. The PCA recipe adds StepPca on top to extract four components. The data is split three ways so the validation set can be used to judge the extraction without touching the test set.

import polars as pl
from sklearn.model_selection import train_test_split

from mlfeatures import (Recipe, StepDropZeroVariance, StepNormalize, StepOrderNorm,
                        StepPca)
from mlfeatures import Selectors as s

# ── Data

from mlfeatures.data import beans  # 13,611 x 17

# ── 3-way split (75 / 12.5 / 12.5, stratified by class)

bean_train, rest = train_test_split(
    beans, train_size=0.75, stratify=beans["class"],
    random_state=1601
)
bean_validation, bean_test = train_test_split(
    rest, train_size=0.50, stratify=rest["class"],
    random_state=1601
)

# ── Base recipe: zv -> orderNorm -> normalize

bean_rec = (
    Recipe(data=bean_train, target="class")
    .add(StepDropZeroVariance(s.numeric_features()))
    .add(StepOrderNorm(s.numeric_features()))
    .add(StepNormalize(s.numeric_features()))
)

# ── PCA recipe: the base recipe plus the extraction step

pca_rec = bean_rec.add(StepPca(s.numeric_features(), num_comp=4))

Fit

Both recipes are fit on the training set only. The validation set is then transformed with what was learned there.

# fit() ~ prep(); transform() ~ bake(): the chapter doubles as the book's
# prep/bake tutorial, and this file doubles as mlfeatures's fit/transform one.
fitted = bean_rec.fit(bean_train)
bean_val_processed = fitted.transform(bean_validation)

pca_fitted = pca_rec.fit(bean_train)

Report

First the preprocessed validation data, then its principal component scores, ready to plot and color by class. The last table is the percent of variance each component explains; the first two carry most of it, which is why a two-dimensional plot of the beans separates the classes so well.

print("--- transformed validation head (zv -> orderNorm -> normalize) ---")
print(bean_val_processed.head())

scores = pca_fitted.transform(bean_validation)
print("\n--- validation-set PC scores (plot-ready) ---")
print(scores.head())

# ── Percent variance explained (R: tidy(id = "pca", type = "variance"))
# Each PC's variance on the training scores, over the total variance of the
# preprocessed training features.

total_var = (fitted.transform(bean_train).drop("class")
             .select(pl.sum_horizontal(pl.all().var())).item())
pct = (pca_fitted.transform(bean_train)
       .select((pl.col("^PC[0-9]+$").var() / total_var * 100).round(2)))
print("\n--- percent variance explained, PC1-PC4 ---")
print(pct)
--- transformed validation head (zv -> orderNorm -> normalize) ---
shape: (5, 17)
┌───────────┬───────────┬───────────┬───────────┬───┬───────────┬───────────┬───────────┬──────────┐
│ area      ┆ perimeter ┆ major_axi ┆ minor_axi ┆ … ┆ shape_fac ┆ shape_fac ┆ shape_fac ┆ class    │
│ ---       ┆ ---       ┆ s_length  ┆ s_length  ┆   ┆ tor_2     ┆ tor_3     ┆ tor_4     ┆ ---      │
│ f64       ┆ f64       ┆ ---       ┆ ---       ┆   ┆ ---       ┆ ---       ┆ ---       ┆ str      │
│           ┆           ┆ f64       ┆ f64       ┆   ┆ f64       ┆ f64       ┆ f64       ┆          │
╞═══════════╪═══════════╪═══════════╪═══════════╪═══╪═══════════╪═══════════╪═══════════╪══════════╡
│ -0.031437 ┆ 0.129653  ┆ 0.341091  ┆ -1.03952  ┆ … ┆ -0.77076  ┆ -1.529332 ┆ -0.858728 ┆ horoz    │
│ -1.877699 ┆ -1.856947 ┆ -1.379452 ┆ -2.139643 ┆ … ┆ 0.63488   ┆ -0.149557 ┆ -0.091435 ┆ dermason │
│ -1.32193  ┆ -1.221643 ┆ -1.103938 ┆ -1.281444 ┆ … ┆ 0.732047  ┆ 0.379788  ┆ 0.750482  ┆ dermason │
│ 0.152917  ┆ 0.047331  ┆ 0.011402  ┆ 0.365575  ┆ … ┆ 0.118406  ┆ 0.42973   ┆ 0.224248  ┆ sira     │
│ 0.067815  ┆ -0.021242 ┆ -0.049757 ┆ 0.267217  ┆ … ┆ 0.1663    ┆ 0.456165  ┆ 0.174279  ┆ sira     │
└───────────┴───────────┴───────────┴───────────┴───┴───────────┴───────────┴───────────┴──────────┘

--- validation-set PC scores (plot-ready) ---
shape: (5, 5)
┌──────────┬───────────┬───────────┬───────────┬───────────┐
│ class    ┆ PC1       ┆ PC2       ┆ PC3       ┆ PC4       │
│ ---      ┆ ---       ┆ ---       ┆ ---       ┆ ---       │
│ str      ┆ f64       ┆ f64       ┆ f64       ┆ f64       │
╞══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ horoz    ┆ -1.654807 ┆ 2.521806  ┆ -2.078126 ┆ 2.338054  │
│ dermason ┆ 3.80502   ┆ 3.257106  ┆ -0.99257  ┆ 0.740274  │
│ dermason ┆ 3.014013  ┆ 1.789769  ┆ 0.905458  ┆ -0.124073 │
│ sira     ┆ 0.352878  ┆ -0.94475  ┆ 0.37649   ┆ -1.017086 │
│ sira     ┆ 0.596694  ┆ -0.911851 ┆ 0.050461  ┆ -0.919107 │
└──────────┴───────────┴───────────┴───────────┴───────────┘

--- percent variance explained, PC1-PC4 ---
shape: (1, 4)
┌───────┬───────┬──────┬──────┐
│ PC1   ┆ PC2   ┆ PC3  ┆ PC4  │
│ ---   ┆ ---   ┆ ---  ┆ ---  │
│ f64   ┆ f64   ┆ f64  ┆ f64  │
╞═══════╪═══════╪══════╪══════╡
│ 59.44 ┆ 24.42 ┆ 6.95 ┆ 5.44 │
└───────┴───────┴──────┴──────┘