Skip to content

What each model needs, inside the folds

Scaling, imputation and encoding are learned values. Learn which learners need what, and let the plan fit each step on each fold's training rows.

Applied ~11 min8 steps

What runs in CodeSplash

You will be able to

  • Say which learners need scaling and which handle missing values natively
  • Explain why preprocessing is fitted on each fold's training rows only
  • Override preprocessing for every model when you have a reason to

Read first

01

Different learners, different needs

Read

Each model card lists what it does by itself. In the gallery you'll see standardizes inputs or handles missing values.

LearnerScaleMissing numbers
Linear, elastic net, Bayesian GLMStandardizeMedian
k-nearest neighbors, SVM, neural networksStandardizeMedian
Tree, forest, extra treesNone neededMedian
XGBoost, LightGBM, histogram boostingNone neededHandled natively

Categories become 0/1 columns, and a missing category becomes a row of zeros.

02

Will scaling matter?

Predict

Predict first

You stop standardizing, and income (in dollars) now dwarfs age (in years). Which model's predictions change the most?

k-nearest neighborsA decision treeBoth about equally
Reveal

k-nearest neighbors. Distances are dominated by the column with the largest numbers. A tree splits on one column at a time, by order alone, so changing the units leaves its splits in the same places.

03

Learned values live inside folds

Read

A mean for imputing, an SD for scaling and the list of levels for encoding are all learned from data. If they see validation rows, those rows have influenced the model that's scoring them.

So each step is fitted on a fold's training rows and applied to its validation rows. For test rows, the final model uses values learned on all training rows.

04

See the size of the problem

Explore

Scaling leaks a little. Selection leaks a lot. Switch The pipeline between Pick features on all rows and Pick features inside each fold, and read the Gap.

DExplorable · Leakage detective

Why does a model that scores brilliantly in testing fail on real data?

Read the pipeline on the left. Will its cross-validation score overstate real-world accuracy by more than 6 points?

How sure?

The pipeline

200
60
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

A pipeline that re-fits everything per fold gives you this protection for free, whatever steps you add.

05

Missing can be informative

Read

Median imputation hides the fact that a value was missing. Sometimes that fact is the signal: a test nobody ordered, a field filled in only for some customers.

Missing-value indicators adds a 0/1 column per feature with gaps, so a linear model can use it. For example, predicting penguin sex on data with gaps, with indicators and mean imputation, logistic regression scores an AUC of 0.953.

Boosters such as histogram gradient boosting send missing values down their own branch: on penguins with gaps, accuracy is 0.978, with no imputation at all.

06

Check your understanding

Checkpoint

Check yourself

Which is correct for a median imputer in 5-fold cross-validation?

Show the answer

Answer: b

Validation rows must be treated as if they haven't arrived. The same goes for new rows after deployment: they get the training median.

Check yourself

Why doesn't a decision tree need standardized inputs?

Show the answer

Answer: a

Multiplying a column by 100 moves its split threshold and leaves the rows on each side unchanged.

Check yourself

Bill length in mm runs up to about 60, and body mass in grams up to about 6,000. With no scaling, which column decides a penguin's neighbors?

Show the answer

Answer: b

Squared distance adds (Δmass)2(\Delta\text{mass})^2 in the millions to (Δbill)2(\Delta\text{bill})^2 in the tens. That's why k-nearest neighbors works on standardized design columns.

07

Override with a reason

In the app

In Validation, Preprocessing for every model offers Impute missing numbers, Scale numbers and Missing-value indicators. Leave Model default unless you have a reason: each model's own choice is usually right, and the app fits them on each fold's training rows.

Python
import pandas as pd
from sklearn.compose import make_column_selector as cols, make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv("penguins.csv").drop(columns="year")
X, y = df.drop(columns="species"), df["species"]
prep = make_column_transformer(
    (make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), cols(dtype_include="number")),
    (OneHotEncoder(handle_unknown="ignore"), cols(dtype_exclude="number")),
)
model = make_pipeline(prep, KNeighborsClassifier(5))
print(cross_val_score(model, X, y, cv=5).mean())  # the prep is refitted inside each fold
R
df <- read.csv("penguins.csv")
num <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
acc <- sapply(1:5, function(k) {
  tr <- df[fold != k, num]; te <- df[fold == k, num]
  med <- sapply(tr, median, na.rm = TRUE)      # learned on training rows only
  for (j in num) { tr[is.na(tr[[j]]), j] <- med[j]; te[is.na(te[[j]]), j] <- med[j] }
  m <- colMeans(tr); s <- apply(tr, 2, sd)
  p <- class::knn(scale(tr, m, s), scale(te, m, s), df$species[fold != k], k = 5)
  mean(p == df$species[fold == k])
})
mean(acc)
08

Recap

Recap
  • Distance and penalty methods need comparable scales. Trees don't.
  • Imputation, scaling and encoding are learned values, so fit them on each fold's training rows.
  • Keep the model default unless you know why not, and flag missingness when it may carry signal.

Concepts in this lesson