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.
What runs in CodeSplash
- Linear / logistic regression Verified in Python and R
- Histogram gradient boosting Verified in Python and R
- k-nearest neighbors Verified in Python and R
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
Different learners, different needs
ReadEach model card lists what it does by itself. In the gallery you'll see standardizes inputs or handles missing values.
| Learner | Scale | Missing numbers |
|---|---|---|
| Linear, elastic net, Bayesian GLM | Standardize | Median |
| k-nearest neighbors, SVM, neural networks | Standardize | Median |
| Tree, forest, extra trees | None needed | Median |
| XGBoost, LightGBM, histogram boosting | None needed | Handled natively |
Categories become 0/1 columns, and a missing category becomes a row of zeros.
Will scaling matter?
PredictPredict first
You stop standardizing, and income (in dollars) now dwarfs age (in years). Which model's predictions change the most?
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.
Learned values live inside folds
ReadA 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.
See the size of the problem
ExploreScaling 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?
The pipeline
Commit your prediction above to see the result
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.
Missing can be informative
ReadMedian 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.
Check your understanding
CheckpointCheck 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 in the millions to in the tens. That's why k-nearest neighbors works on standardized design columns.
Override with a reason
In the appIn 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.
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 folddf <- 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)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