Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Features, scaling and data leakage

P3.A1140 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A model only sees the numbers you give it, so how you build, scale and encode them decides what it can learn, and one careless step can leak the answer into training and make a useless model look excellent.

  • k-nearest neighbors predicts from distances, so a feature measured in big numbers (dollars) drowns one measured in small numbers (years) unless the features are rescaled. (P3.B1: k-Nearest Neighbors)
  • The penalty of ridge and lasso treats every weight alike, so it only means the same thing for every feature when the features are on a common scale. (P3.A6: Regularization: L1 and L2)
  • Cross-validation and the final test only estimate real performance if every fitted step, scaling and encoding included, is learned inside each training fold. (P3.A4: Train, validation and test sets)
  • A neural network trains faster with standardized inputs, and normalization layers repeat the same operation between layers. (P4.19: Normalization layers)

Before this: The supervised learning setup, Linear regression, Data wrangling with Pandas, Descriptive statistics and visualization

After this lesson you can

  • Build simple features (ratios, logs of skewed values, interactions, parts of a date) and say which of them a model can and cannot find by itself
  • Standardize, min–max scale and robust scale a column by hand, choose between them, and say when scaling matters (distance methods, gradient descent, penalties) and when it does not (trees)
  • Encode categories with one-hot and ordinal codes, avoid the dummy trap, handle new categories and many categories, and say how target encoding leaks and how out-of-fold encoding fixes it
  • Define data leakage, tell target leakage, contamination and time leakage apart, spot them, and prevent them by splitting first and fitting every learned step inside a pipeline

A classmate shows a model that predicts who survived the Titanic with 97% accuracy on held-out passengers. A second model, built from the same passenger table, reaches 82%. Nothing is wrong with the arithmetic in either. One of them has been given something it should not have, and the other has not. By the end of this lesson you will know which kind of thing that is, and how to catch it before anyone is fooled.

This lesson is about the step between a table of raw data and a model: turning columns into features, putting them on sensible scales, turning categories into numbers, and doing all of it without letting information leak from the data you will be judged on into the data you learn from. P3.A1 put “features” in the pipeline and said the split comes first. Here we see what goes on inside that Features box, and why the order matters.

What a feature is, and a few you can build

A feature is one number about an example that the model is allowed to use. The feature vector x\mathbf{x} of P3.A1 is a list of them, and the data matrix X\mathbf{X} has one column per feature. Two rules decide whether a column is a good feature.

  1. It must be a number. A model does arithmetic. Text, colours and categories are turned into numbers first (the encodings below).
  2. It must be known when you predict. If the value would only exist after the outcome, it is not a feature but a leak (later in this lesson).

Choosing and building features is feature engineering. Deep networks learn many features for themselves (Part 4), but with a table of columns, a few hand-made features often help more than a fancier model. Four standard moves:

  • A ratio. A house’s area and its number of rooms say little together; the area per room says how spacious the rooms are. A model that adds features, like linear regression (P3.A2), cannot divide them for you.
  • A log for a right-skewed value. Incomes in thousands, 20, 25, 30, 35, 40, 45, 5020,\ 25,\ 30,\ 35,\ 40,\ 45,\ 50 and one at 10001000, have mean 155.6155.6 and median 37.537.5. On a log⁡10\log_{10} scale the seven ordinary values run from 1.301.30 to 1.701.70 and the large one becomes 3.003.00. The jump from 5050 to 10001000 is 31.731.7 times the jump from 2020 to 5050 in raw units (950950 against 3030), and 3.33.3 times on the log scale (1.301.30 against 0.400.40). Equal steps now mean equal factors, which is how many quantities behave (P1.D12). The log needs positive values, so log⁡(1+x)\log(1+x) is common when zeros occur.
  • An interaction. The product x1x2x_1x_2 lets a linear model say “the effect of x1x_1 depends on x2x_2”, for example that an extra room is worth more in a large house. A weighted sum alone cannot say that.
  • Parts of a date. A timestamp such as 2026-12-02 14:30 is not a useful number by itself. Its parts are: month 1212, weekday Wednesday, hour 1414, weekend or not. Which parts help depends on the problem: sales depend on the weekday, electricity use on the hour.
Go deeper Cyclic features: the hour that wraps around

Hour 2323 and hour 00 are one hour apart, but as plain numbers they are 2323 apart. A common fix is to place the hour on a circle with two features, sin⁡(2πh/24)\sin(2\pi h/24) and cos⁡(2πh/24)\cos(2\pi h/24). Then hours 2323 and 00 are 0.260.26 apart (straight-line distance), and hours 00 and 1212 are 2.02.0 apart, the full diameter. The same trick suits weekdays, months and wind direction. Tree models (P3.B3) can often manage with the plain number, because they cut it into ranges.

Engineered features follow the same rules as any other: compute them from information available at prediction time, and if building one needs a number learned from data (an average, a vocabulary), learn it from the training rows only. The titles hidden in the Titanic names (“Mr”, “Miss”, “Master”) are a feature of this kind, extracted in an exercise of P2.5.

Scaling

Why scale: three reasons

Features come in different units. Age is in tens, income in tens of thousands. Many methods quietly assume the numbers are comparable, and three of them break in a way you can compute.

Distances. In P1.B4 Alice is 25 and earns 50 000, Bob is 60 and earns 50 500, and Carol is 26 and earns 60 000. The Euclidean distances from Alice are 501.2501.2 to Bob and 10 000.010\,000.0 to Carol. A 35-year age gap hardly registers beside a 500-dollar income gap, only because dollars are bigger numbers than years. After rescaling both features to similar ranges the distances become 0.7000.700 and 0.1020.102, and Carol, a year older than Alice, is the near neighbour (these use the ranges assumed in P1.B4; the widget below learns its ranges from five training people, so its numbers differ, but Carol is still nearest). Any method built on distance (k-NN in P3.B1, k-means in P3.C1) has this problem, and so does PCA (P3.C3), which looks for the directions of most variance and finds them in whichever feature has the biggest numbers.

Gradient descent. A feature with big values makes the loss change fast when its weight moves, so the loss bowl is steep in that direction and flat in the others (P1.C5, P1.F3). The step size must be small enough for the steep direction, so the flat directions crawl. In the second cell of Try it two features, a house area (50 to 150) and a room count (1 to 5), give a loss bowl whose curvatures along its three main directions (the Hessian eigenvalues of P1.C8, for the three weights: the two features and the bias) are 0.0940.094, 4.384.38 and 23 45223\,452. The largest stable step is η<8.5×10−5\eta<8.5\times10^{-5}, and at η=0.00008\eta=0.00008 it takes 95069506 steps to get within 1% of the best loss. After standardizing both features the three curvatures are 1.901.90, 2.002.00 and 2.102.10, a nearly round bowl, the limit is η<0.95\eta<0.95, and η=0.5\eta=0.5 takes 22 steps. (P3.A2 saw the same effect from only centring xx.) Standardizing does two things at once: it centres the features and it puts them on one scale, and both make the bowl rounder. It cannot remove correlation between features, which still tilts the bowl. Features built as powers of xx (P3.A3) differ a lot in size and are strongly correlated, so centre and scale xx before building the powers.

Penalties. A weight is “per unit of its feature”: the same relation gives a weight 10001000 times larger for a length in metres than in millimetres. A penalty such as ridge’s λ∑w2\lambda\sum w^2 (P3.A6) cannot tell the two apart, so it punishes the metre feature far more. In the same cell, with λ=1\lambda=1 on made-up data, the ridge slope per metre is 1.4771.477 when the feature is in metres and 3.0143.014 (the same, to three decimals, as the unpenalized least-squares value) when it is in millimetres. One λ\lambda only means one thing when the features share a scale.

See it: who is nearest?

The widget has five known people (the training rows) and a new person, Alice. Choose how the two features are scaled and see who is nearest. Alice is transformed with numbers learned from the five training rows only, which is the rule of the next sections.

Who is nearest to Alice?

Alice is a new person: age 25, income 50,000. Five known people are the training rows. Pick how the two features are scaled.

No scaling: the numbers are used as they are.

Nothing is learned from the data.

Alice becomes (25.00, 50,000) (age, income), using the same numbers.

  • Bob (60.00, 50,500)
    distance 501.2 (nearest)
  • Carol (26.00, 60,000)
    distance 10,000
  • Dan (45.00, 80,000)
    distance 30,000
  • Eva (33.00, 30,000)
    distance 20,000
  • Finn (52.00, 120,000)
    distance 70,000
Nearest to Alice: Bob (distance 501.2).
Age and income for five training people and a new person, Alice (age 25, income 50 000). Four buttons choose the scaling: raw, standardized, min–max or robust. The scaled coordinates of each person and the distance from Alice are shown as numbers and bars, and the nearest person is marked with the word “nearest” and a green border. In the raw numbers Bob (60, 50 500) is the nearest, 501.2 away, because 500 dollars outweigh 35 years. With any of the three scalers, Carol (26, 60 000) is the nearest.

Three scalers

Each scaler learns two numbers per feature from the training rows and then applies them as (x−centre)/scale(x-\text{centre})/\text{scale}.

  • Standardization (the zz-score of P1.D12): z=x−μσz=\dfrac{x-\mu}{\sigma}, with μ\mu the training mean and σ\sigma the training standard deviation. The result has mean 00 and standard deviation 11 on the training rows.
  • Min–max scaling: x−xmin⁡xmax⁡−xmin⁡\dfrac{x-x_{\min}}{x_{\max}-x_{\min}}. The training rows land in [0,1][0,1].
  • Robust scaling: x−medianQ3−Q1\dfrac{x-\text{median}}{Q_3-Q_1}, the median and the interquartile range (P1.D12).

On the training column 2, 4, 4, 4, 5, 5, 7, 92,\ 4,\ 4,\ 4,\ 5,\ 5,\ 7,\ 9 the mean is 55, the deviations are −3, −1, −1, −1, 0, 0, 2, 4-3,\ -1,\ -1,\ -1,\ 0,\ 0,\ 2,\ 4 and the squares add to 3232, so the variance is 32/8=432/8=4 and σ=2\sigma=2. Standardized, the column is −1.5-1.5, then −0.5-0.5 three times, then 00 twice, then 11 and 22. Min–max uses xmin⁡=2x_{\min}=2 and range 77. Robust uses median 4.54.5 and quartiles 44 and 5.55.5 (NumPy’s default rule; other tools differ slightly), so the IQR is 1.51.5. Here we divide by nn (the population form, which scikit-learn’s StandardScaler and NumPy’s std use). P1.D12’s sample form divides by n−1n-1 and would give 2.142.14.

Which one? Use standardization as the default, especially for methods that assume features are roughly centred (linear models, neural networks, PCA). Use min–max when a bounded range is natural, such as pixel values from 0 to 255, and the data has no extreme values. A single outlier sets the maximum and squeezes the rest: for P1.D12’s values 2, 3, 3, 5, 7, 8, 302,\ 3,\ 3,\ 5,\ 7,\ 8,\ 30 the six ordinary values land between 00 and 0.210.21. Use robust scaling when outliers are present, because the median and IQR hardly move for them: in the same data the robust value of 22 is −0.67-0.67 and that of 3030 is 5.565.56, so the ordinary values keep their spread and the outlier stays visibly far away. None of them changes the shape of a distribution, so a skewed feature stays skewed; take the log first if you want that fixed.

A word on names: “normalization” is used loosely. It can mean min–max scaling, standardization, or (in scikit-learn’s Normalizer) rescaling each row to length 1. Batch and layer normalization in neural networks (P4.19) standardize activations. When you read the word, check the formula.

When scaling does not matter

  • Decision trees and forests (P3.B3) ask whether a feature is above or below a threshold. Rescaling a feature moves the thresholds with it and leaves the order of the examples alone, so the splits and the tree are essentially unchanged.
  • Plain linear regression gives the same fitted predictions on rescaled features, because the weights absorb the units (P3.A2). Only the numbers in the weights change. With a penalty, as above, the scale does matter.
  • A 0/1 column from one-hot encoding is already on a small, comparable scale; scaling it is optional.
Go deeper Sparse data, constant columns and the n versus n minus 1 choice

Subtracting a mean turns the many zeros of a sparse matrix (for example word counts) into non-zeros and can make it huge. For sparse data, divide by the scale and skip the centring (in scikit-learn, set with_mean=False, or use MaxAbsScaler). A constant column has standard deviation 00, so zz would be 0/00/0; scikit-learn leaves its scale at 11 and the column becomes all zeros, and in NumPy you add a tiny eps to the divisor (P2.3 shows the standardizing one-liner). NumPy’s std and scikit-learn’s scalers divide by nn, while many statistics tools divide by n−1n-1 (as P1.D12 does), so state which one you use.

Fit on the training data only

A scaler has two jobs. Fit learns numbers from data (the mean and standard deviation). Transform applies them. The rule:

Fit on the training rows. Transform the training, validation, test and live rows with those same numbers.

Take the training column above, with mean 55 and σ=2\sigma=2, and two test values, 33 and 1111. Transformed with the training numbers they become −1-1 and 33. Min–max gives 0.1430.143 and 1.2861.286. The second is outside [0,1][0,1], and that is fine: it only says the value is above anything seen in training. Robust scaling gives −1-1 and 4.334.33.

Now the tempting mistake: compute the mean and standard deviation of train and test together. They become 5.45.4 and 2.652.65, and the test values become −0.90-0.90 and 2.112.11. The test rows have helped decide how the training rows are scaled, so some information about the test set has leaked into training. For a scaler this leak is usually small. Keep the habit anyway: the same slip with feature selection can be large, as we will see.

Two consequences follow. Scaled test data will not have exactly mean 00 and standard deviation 11, and they should not. (In the Titanic pipeline below, the scaled test ages have a mean of −0.03-0.03, not 00.) And the numbers must travel with the model: at prediction time a new passenger is scaled with the training mean and standard deviation, not with her own batch’s.

Encoding categories

A model needs numbers, so a category such as the Titanic port of embarkation (S, C or Q) must be encoded. There are two kinds of category: nominal (no order: port, colour, country) and ordinal (a real order: small, medium, large).

One-hot encoding

One-hot encoding makes one 0/1 column per category. A passenger who embarked at S becomes (C,Q,S)=(0,0,1)(\text{C},\text{Q},\text{S})=(0,0,1), one from C becomes (1,0,0)(1,0,0). Exactly one column is 11 in each row, which makes no category look bigger or closer to another. pd.get_dummies in P2.5 did this.

The dummy trap. With a bias (an intercept column of ones, P3.A2), the one-hot columns add to 11 in every row, so together they equal the intercept column. That is a copied feature: X⊤X\mathbf{X}^\top\mathbf{X} is singular and the weights are not unique. For KK categories plus an intercept there are K+1K+1 columns of rank KK. In the third cell of Try it, an intercept and 3 port columns give 4 columns of rank 3, and dropping one port column gives 3 columns of rank 3. The fix is to drop one category (drop_first=True in pandas, drop="first" in scikit-learn); that category becomes the baseline that the intercept describes, and each remaining weight is the difference from it. A penalized model (P3.A6) does not need this, because the penalty picks one solution (though the weights are then harder to read). A tree does not need it either, because it does not solve for weights.

Ordinal codes

For an ordered category, integer codes keep the order: small, medium, large become 1, 2, 31,\ 2,\ 3. This is only right if the steps are roughly equal, since the codes claim that large is as far above medium as medium is above small. Do not use integer codes for nominal categories. Coding S, C, Q as 0, 1, 20,\ 1,\ 2 says that C is between S and Q and that Q is twice as far from S as C is, which k-NN or a linear model would then believe.

New categories at prediction time

The test or live data can hold a category the training data never had, such as a port “X”. A default scikit-learn OneHotEncoder raises an error. Two common choices are handle_unknown="ignore", which encodes the unseen category as all zeros, and grouping rare categories into one “other” column (the min_frequency setting together with the infrequent_if_exist option of handle_unknown). Beware of a clash: with drop="first", the dropped category is also all zeros, so it cannot be told from an unseen one (the second static block below shows this).

Many categories

A zip code or a user ID can have thousands of values. One column each is wasteful and most columns are rarely 11. Options, from simplest:

  • Group the rare ones into “other” and keep the common ones.
  • Target encoding: replace each category by the mean of the label among the training rows in that category (with some shrinking towards the overall mean for small categories). It gives one dense column, and it leaks: each training row’s own label is part of its category’s mean. In the extreme, if every row has its own ID, the encoding of a row is its own label. In the third cell of Try it, 200 rows with their own ID and coin-flip labels give a correlation of 1.01.0 between the naive encoding and the label, a perfect feature for nothing. The fix is out-of-fold encoding: split the training rows into folds, and encode each fold with the means computed from the other folds, so no row sees its own label. For the unseen IDs the encoding falls back to the overall mean of the other folds, which is the honest answer, since the label carries no information about a random ID. scikit-learn’s TargetEncoder does this inside fit_transform (see the static block below).
Go deeper Embeddings and hashing for huge vocabularies

For very large vocabularies, learned embeddings (P4.21) give each category a short vector learned during training, the usual choice in neural networks. A hashing trick, which maps each category to one of a fixed number of columns, is a cheaper alternative.

Missing values, briefly

P2.5 covers the choices: drop the row or column, fill, or fill and add a “was missing” flag. The new point here is the order. A fill value (the median, the most common category) is a number learned from data, so compute it on the training rows and reuse it, exactly like a scaler. P2.5’s training median age was 28.2528.25, and the test rows’ own median would have been 27.027.0. Some tree libraries accept missing values directly (P3.B5).

Data leakage

The rule

Data leakage is information in the training or evaluation process that will not be available when the model is used, or information from the test data that reaches the training. Either way the test score overstates what you will get in practice. One question catches most cases: at the moment of prediction, will this value exist, and is it made without looking at the answer or at the test rows?

Three kinds are worth naming. The puzzles below use these labels.

  • Target leakage: a feature built from the outcome or from its consequences.
  • Contamination: test information reaches training (also called train–test leakage).
  • Time leakage: the future reaches the past.

Target leakage

P2.5 found two columns in the Titanic file that should not be features. Passengers with a lifeboat number in boat survived 98.1%98.1\% of the time (486486 passengers) and those without 2.8%2.8\% (823823 passengers), because the column records the boat that survivors left in. All 121121 passengers with a body number died. Both record what happened after the outcome.

What does that do to a model? In the static scikit-learn block below, one logistic regression with seven honest columns scores 0.8170.817 on 328 held-out passengers. Add a single column saying whether boat is filled in, and the same model scores 0.9730.973. That is the gap between the two classmates at the start of this lesson. The second number is useless for the real question, because before the event there is no boat.

The same pattern appears in business data: the number of collection calls made after a loan went overdue, a “cancellation processed” flag in data used to predict who will cancel a subscription, a file name that was assigned after the images were sorted by class. A small simulation (the fourth cell of Try it, made-up data) has three weak real features and a “refund” column that equals the label 97%97\% of the time. Without the refund column, test accuracy is 0.6140.614. With it, 0.9760.976. If the refund is unknown when the prediction is made and is filled with 00, the accuracy is 0.4770.477, no better than a coin flip.

Contamination

Here no feature is a copy of the answer. Instead, test information slips into what the model learns.

  • Preprocessing fitted on all rows. A scaler, an imputer, a PCA or a vocabulary fitted before the split. Usually small for a scaler, as above.
  • Feature selection on all rows. P3.A4 showed a small version of this (0.82 vs 0.46). Here is a larger one. Take 100100 rows and 10001000 features of pure noise, with coin-flip labels, so nothing can be learned and honest accuracy is 50%50\%. Pick the 1010 features most related to the label using all 100100 rows, then split into 60 training and 40 test rows and fit a nearest-centroid classifier (it gives each test row the class whose training rows have the closer average). Averaged over 200 repetitions, the test accuracy is 0.7880.788. With the features chosen on the 60 training rows only, it is 0.4940.494. With so many features and so few rows, some look related to the labels by chance, and including the test rows in the choice makes the test rows agree with them.
  • Duplicates across the split. The model is graded on rows it has memorized, and the test set holds fewer independent examples than it seems: 10001000 test rows that are 100100 rows copied ten times give a true standard error of 0.0400.040 at accuracy 0.80.8, not 0.01260.0126 (P1.D13).
  • Group leakage. Several rows come from one source (photos of one patient). Keep each group on one side of the split (P3.A4).
  • Time leakage. Time-ordered data are split by time, past for training and future for testing, and a feature window must not reach into the future (P3.A4).
Go deeper Other places where learned steps leak

Anything that learns from data before the split counts: oversampling the rare class before splitting (P3.A10), a PCA or an embedding fitted on all rows (P3.C3), imputing with a model trained on all rows, or choosing a threshold or a hyperparameter by looking at the test score (P3.A4, P4.23). Many of these look harmless because no label is visible, yet they still let the test rows shape the model. The test is an honest estimate only if it is used once, at the end.

Spot the leak

Eight short scenarios. Pick the best description, and read the explanation. Each answer follows from the rule above: will the value exist at prediction time, and did test information shape the model? Group leakage counts as contamination.

Spot the leak

Read the scenario, then pick the best description. Each answer is explained once you choose.

Scenario 1 of 8

Goal: decide when a loan is approved whether it will default. One feature is the number of collection calls made after the loan became overdue.

Choose an answer.

Answered 0 of 8. Correct: 0.

Eight scenarios, each with four possible answers: no leak, target leak, contamination, or time leak. After you choose, the answer locks, the right option is marked with a tick and the wrong one you chose with a cross, and a short explanation appears. Numbered buttons jump between scenarios and show which were answered correctly. The page keeps a running score, and Start over clears it.

Spotting a leak in your own project

A leak rarely announces itself. Habits that catch it:

  1. Write down, for each feature, when it is known and how it is made. A table with a “known at prediction time?” column is boring and effective.
  2. Check the split: count duplicate rows and see whether any ID, patient or user appears on both sides.
  3. Shuffle the labels and run the whole procedure. An honest pipeline then scores near chance. The selection example above is exactly this: its labels are coin flips, and the leaky procedure still scores 0.7880.788.
Go deeper More signs of a leak

A result that is too good is a prompt to look: compare with a simple baseline, and be suspicious of a jump from 0.820.82 to 0.970.97 from one new column. One feature that dominates the model is another sign: in the refund simulation the fitted weight on the refund column is 0.9050.905, against 0.0070.007 to 0.0260.026 for the three real features (printed by the fourth cell of Try it). And a model that was brilliant in testing and poor in use is the classic late symptom (monitoring is P12.5).

The fix: split first, then use a pipeline

Split the data before any step that learns from it. Then put every learned step (imputer, scaler, encoder, feature selection) together with the model in a pipeline, so that calling fit on the training rows fits all of them on those rows alone, and calling predict applies the stored numbers to new rows. In cross-validation (P3.A4), the pipeline is refitted inside every fold, so each fold’s scaler and encoder see only that fold’s training part. For grouped or time-ordered data use a group split or a split by time. The code block below does all of this for the Titanic table.

Where the pieces go in scikit-learn

The following blocks are static, because scikit-learn is not available in the in-browser runner. Their output is from a local run (scikit-learn 1.8.0, with the Titanic file of P2.5). Everything runnable on this page uses only NumPy.

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv("titanic.csv")
df["pclass"] = df["pclass"].astype(str)        # a category, not a number
df["boat_given"] = df["boat"].notna().astype(int).astype(str)   # the leak
y = df["survived"]
numeric = ["age", "fare", "sibsp", "parch"]
categorical = ["sex", "embarked", "pclass"]

def make_model(cat_columns):
    prep = ColumnTransformer([
        ("num", Pipeline([("fill", SimpleImputer(strategy="median")),
                          ("scale", StandardScaler())]), numeric),
        ("cat", Pipeline([("fill", SimpleImputer(strategy="most_frequent")),
                          ("onehot", OneHotEncoder(handle_unknown="ignore"))]),
         cat_columns),
    ])
    return Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])

honest = numeric + categorical
X_tr, X_te, y_tr, y_te = train_test_split(
    df, y, test_size=0.25, random_state=0, stratify=y)

model = make_model(categorical)
model.fit(X_tr[honest], y_tr)          # every fitted step sees training rows only
print("test accuracy:", round(model.score(X_te[honest], y_te), 3))
folds = StratifiedKFold(5, shuffle=True, random_state=0)
print("5-fold accuracy:", cross_val_score(model, df[honest], y, cv=folds).mean().round(3))

leaky = make_model(categorical + ["boat_given"])
leaky.fit(X_tr[honest + ["boat_given"]], y_tr)
print("with the boat leak:", round(leaky.score(X_te[honest + ["boat_given"]], y_te), 3))
test accuracy: 0.817
5-fold accuracy: 0.784
with the boat leak: 0.973

ColumnTransformer applies one recipe to the numeric columns (fill with the training median, then standardize) and another to the categorical ones (fill with the most common value, then one-hot encode), and Pipeline chains the preparation to the classifier. The preparation gives 12 columns for the 7 raw ones: the four numbers plus two sex columns, three port columns and three class columns. The age scaler learned a mean of 29.5929.59 and a standard deviation of 13.1413.14 from the training rows. The 0.8170.817 and the 0.7840.784 differ because one split is a noisy estimate, which is a good reason for the cross-validation of P3.A4. (cross_val_score refits the whole pipeline in every fold, which is how the preprocessing stays inside each fold.)

The encoders and the target encoder, on small made-up inputs:

import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder, TargetEncoder

ports = pd.DataFrame({"port": ["S", "C", "S", "Q"]})
new = pd.DataFrame({"port": ["C", "X"]})        # "X" was never seen

enc = OneHotEncoder(handle_unknown="ignore").fit(ports)
print(enc.categories_[0], enc.transform(new).toarray().tolist())
enc = OneHotEncoder(drop="first", handle_unknown="ignore").fit(ports)
print("drop first:", enc.transform(new).toarray().tolist())

ids = pd.DataFrame({"id": np.arange(200).astype(str)})   # one ID per row
y = np.random.default_rng(0).integers(0, 2, 200)         # coin-flip labels
te = TargetEncoder(cv=5, random_state=0)
print("fit, then transform:", np.corrcoef(te.fit(ids, y).transform(ids)[:, 0], y)[0, 1].round(2))
print("fit_transform:      ", np.corrcoef(te.fit_transform(ids, y)[:, 0], y)[0, 1].round(2))
['C' 'Q' 'S'] [[1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
drop first: [[0.0, 0.0], [0.0, 0.0]]
fit, then transform: 1.0
fit_transform:       -0.02

With drop="first" the category C is the baseline, so C and the unseen X both become (0,0)(0,0). For the target encoder, fit(...).transform(...) on the training rows is the leaky version (correlation 1.01.0 with the label), and fit_transform uses the cross-fitting of the out-of-fold idea (correlation near 00). Use fit_transform on the training rows and transform on new rows.

Intuition

Think of a school exam. If the questions leak into the revision notes, the marks are high and prove nothing about what students learned. A leak is any way for the exam to reach the notes: the answer printed beside the question (target leakage), notes written after reading the whole exam paper (contamination), or notes copied from next year’s course (time leakage). The analogy breaks in that students know when they cheat, while a data pipeline leaks silently, which is why the habits (split first, use a pipeline) matter more than good intentions.

Scaling is choosing the unit of measure so that no feature shouts louder than the others for no reason. Measuring a person’s height in millimetres and age in years would make height look 1000 times more important to a ruler (distance), a hill-walker (gradient descent) and a tax collector (a penalty on weights).

Math

Scalers on a training column with mean μ\mu, standard deviation σ\sigma, minimum xmin⁡x_{\min}, maximum xmax⁡x_{\max}, median mm and quartiles Q1,Q3Q_1,Q_3:

z=x−μσ,x−xmin⁡xmax⁡−xmin⁡,x−mQ3−Q1.z=\frac{x-\mu}{\sigma},\qquad \frac{x-x_{\min}}{x_{\max}-x_{\min}},\qquad \frac{x-m}{Q_3-Q_1}.

Multiplying feature jj by cjc_j divides its weight by cjc_j and turns the Hessian of the squared loss, 2NX⊤X\frac2N\mathbf{X}^\top\mathbf{X}, into C 2NX⊤X C\mathbf{C}\,\frac2N\mathbf{X}^\top\mathbf{X}\,\mathbf{C} with C=diag(cj)\mathbf{C}=\mathrm{diag}(c_j), so the curvature along that weight is multiplied by cj2c_j^2. Standardized features have diagonal entries equal to 22, which is why the bowl becomes round when the features are uncorrelated.

One-hot columns d1,…,dK\mathbf{d}_1,\dots,\mathbf{d}_K satisfy ∑kdk=1\sum_k\mathbf{d}_k=\mathbf{1}, the intercept column, so rank [1,D]=K\mathrm{rank}\,[\mathbf{1},\mathbf{D}]=K, not K+1K+1.

Target encoding of category cc with smoothing: nc yˉc+s yˉnc+s\dfrac{n_c\,\bar y_c+s\,\bar y}{n_c+s}, where ncn_c is the number of training rows in cc, yˉc\bar y_c their mean label, yˉ\bar y the overall mean and ss a smoothing weight. Out of fold, yˉc\bar y_c and ncn_c for a row come from the other folds.

Code

The model above is a pipeline: ColumnTransformer for the per-column recipes and Pipeline for the chain. A fitted StandardScaler stores mean_ and scale_; OneHotEncoder stores categories_. Calling fit on the whole pipeline passes the training rows through each step in turn, and predict or score applies the stored numbers. Nothing is learned from the test rows.

In NumPy the same idea is two lines: compute mean = X_train.mean(axis=0) and std = X_train.std(axis=0) once, then use (X - mean) / std for every set.

Try it

Four short NumPy cells reproduce the numbers of this lesson. All data are made up and the random generators are seeded. The first scales a column from the training numbers, shows the leaky alternative and repeats the Alice, Bob and Carol distances of P1.B4. The second shows why scaling helps gradient descent and the ridge penalty. The third shows the dummy trap and the out-of-fold idea for target encoding. The fourth builds the two leaks: a target leak and feature selection on all rows.

Try it: scale with the training numbers

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: why scaling helps descent and the penalty

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: the dummy trap and out-of-fold target encoding

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: a target leak and a selection leak

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Exercises

  1. Using the training column 2, 4, 4, 4, 5, 5, 7, 92,\ 4,\ 4,\ 4,\ 5,\ 5,\ 7,\ 9 (mean 55, σ=2\sigma=2, min 22, max 99, median 4.54.5, IQR 1.51.5), scale a new test value of 88 with each of the three scalers.
    Show answerStandardized: (8−5)/2=1.5(8-5)/2=1.5. Min–max: (8−2)/7=0.857(8-2)/7=0.857. Robust: (8−4.5)/1.5=2.333(8-4.5)/1.5=2.333.
  2. For P1.D12’s values 2, 3, 3, 5, 7, 8, 302,\ 3,\ 3,\ 5,\ 7,\ 8,\ 30 (median 55, quartiles 33 and 7.57.5), compute the min–max and robust values of 22 and of 3030. Which scaler keeps the ordinary values spread out?
    Show answerMin–max, with xmin⁡=2x_{\min}=2 and xmax⁡=30x_{\max}=30: 00 and 11, and the other six values fall between 00 and 0.2140.214. Robust, with IQR 4.54.5: (2−5)/4.5=−0.667(2-5)/4.5=-0.667 and (30−5)/4.5=5.556(30-5)/4.5=5.556, while the others spread from −0.444-0.444 to 0.6670.667. Robust scaling keeps the ordinary values spread out.
  3. A column has 5 categories, and the model is linear regression with an intercept and no penalty. How many dummy columns should you make, and what is the rank of the full set of 5 dummies plus the intercept?
    Show answerMake 4, dropping one as the baseline. The 5 dummies add up to the intercept column, so the 6 columns have rank 5, and X⊤X\mathbf{X}^\top\mathbf{X} would be singular.
  4. A one-hot encoder was fitted on ports S, C, Q with handle_unknown="ignore". What does a new passenger from port X become, and what does the model predict for her?
    Show answer(0,0,0)(0,0,0). All three port columns are 00, so the port contributes nothing and the model predicts from the intercept and her other features. The model is told nothing about her port, which is better than an error but is not a real encoding of X.
  5. Label each case as no leak, target leakage, contamination or time leakage. (a) Predicting whether a user clicks an ad, using the number of purchases the user makes in the 7 days after the ad was shown. (b) A sensor reading every second for a day, split into training and test seconds at random. (c) The median used to fill missing ages comes from the training rows only.
    Show answer(a) Target leakage: the purchases come after, and may be caused by, the click. (b) Time leakage (and near-duplicates): neighbouring seconds are nearly identical, so test seconds sit between training seconds; split by time, for example train on the first 18 hours and test on the last 6. (c) No leak, the correct procedure.
  6. Place hours on a circle with (sin⁡(2πh/24),cos⁡(2πh/24))(\sin(2\pi h/24),\cos(2\pi h/24)). Why is that better than the plain number hh for a method that uses distances, and how far apart are hours 00 and 1212?
    Show answerWith the plain number, hour 2323 and hour 00 are 2323 apart although they are one hour apart in real life. On the circle they are 0.260.26 apart. Hours 00 and 1212 are opposite points, a distance of 2.02.0 (the diameter).

Check your understanding

  1. A pipeline will standardize a feature and then train a model. Which procedure is correct?

  2. A decision tree (P3.B3) is trained on a column in dollars, and then again on the same column standardized. What is the most accurate expectation?

  3. A linear regression with an intercept uses all three one-hot columns for the port (C, Q, S) and has no penalty. What goes wrong?

  4. You replace a category with the mean label of the training rows in that category, using all training rows, and then train on that column. Why is this risky, and what is the remedy?

Next: this closes the core concepts of Part 3. P3.A4 shows how to split data and cross-validate, including group and time splits, which is the other half of the leakage cure. P3.A6 uses scaled features under L1 and L2 penalties, P3.A10 deals with class imbalance (and oversampling, which must happen after the split), P3.B1 uses distances, and P3.B3 builds trees, which do not care about scale. P4.19 puts standardization inside a network.

Key takeaways

  • A feature is one number about an example. Models do arithmetic, so text and categories must become numbers, and a feature must be something you will know at the moment you predict. A few standard moves: a ratio, the log of a right-skewed value, a product of two features, the parts of a date.
  • Scaling puts features on comparable sizes. Standardization is (x − mean) / std, min–max is (x − min) / (max − min), robust scaling is (x − median) / IQR. It matters for distances (k-NN), for gradient descent (a stretched bowl needs a tiny step), and for penalties (a weight is per unit of its feature). Trees do not care.
  • Fit the scaler on the training rows only and reuse the same numbers on validation, test and live data. With training mean 5 and std 2, a test value of 11 becomes 3, while statistics from train and test together would give 2.11.
  • One-hot encoding makes one 0/1 column per category. With an intercept, all the columns together add to the intercept column, so drop one (the dummy trap). Use ordinal codes only for categories with a real order. Plan for new categories at prediction time. Target encoding replaces a category by its mean label and leaks unless it is computed out of fold.
  • A leak is information that will not exist when the model is used, or test information that reaches training. Kinds: target leakage (a feature built from the outcome, like the Titanic boat column), contamination (preprocessing or feature selection on all rows, duplicates, one patient on both sides) and time leakage (the future reaches the past).
  • Selecting the 10 best of 1000 noise features on all 100 rows and then splitting gave 0.788 test accuracy on coin-flip labels; selecting on the training rows gave 0.494. The cure is to split first and put every fitted step in a pipeline, so each training fold fits its own numbers.
Found a mistake? Tell us