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 of P3.A1 is a list of them, and the data matrix has one column per feature. Two rules decide whether a column is a good feature.
- It must be a number. A model does arithmetic. Text, colours and categories are turned into numbers first (the encodings below).
- 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, and one at , have mean and median . On a scale the seven ordinary values run from to and the large one becomes . The jump from to is times the jump from to in raw units ( against ), and times on the log scale ( against ). Equal steps now mean equal factors, which is how many quantities behave (P1.D12). The log needs positive values, so is common when zeros occur.
- An interaction. The product lets a linear model say “the effect of depends on ”, 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 , weekday Wednesday, hour , 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 and hour are one hour apart, but as plain numbers they are apart. A common fix is to place the hour on a circle with two features, and . Then hours and are apart (straight-line distance), and hours and are 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 to Bob and 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 and , 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 , and . The largest stable step is , and at it takes steps to get within 1% of the best loss. After standardizing both features the three curvatures are , and , a nearly round bowl, the limit is , and takes steps. (P3.A2 saw the same effect from only centring .) 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 (P3.A3) differ a lot in size and are strongly correlated, so centre and scale before building the powers.
Penalties. A weight is “per unit of its feature”: the same relation gives a weight times larger for a length in metres than in millimetres. A penalty such as ridge’s (P3.A6) cannot tell the two apart, so it punishes the metre feature far more. In the same cell, with on made-up data, the ridge slope per metre is when the feature is in metres and (the same, to three decimals, as the unpenalized least-squares value) when it is in millimetres. One 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.
Three scalers
Each scaler learns two numbers per feature from the training rows and then applies them as .
- Standardization (the -score of P1.D12): , with the training mean and the training standard deviation. The result has mean and standard deviation on the training rows.
- Min–max scaling: . The training rows land in .
- Robust scaling: , the median and the interquartile range (P1.D12).
On the training column the mean is , the deviations are and the squares add to , so the variance is and . Standardized, the column is , then three times, then twice, then and . Min–max uses and range . Robust uses median and quartiles and (NumPy’s default rule; other tools differ slightly), so the IQR is . Here we divide by (the population form, which scikit-learn’s StandardScaler and NumPy’s std use). P1.D12’s sample form divides by and would give .
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 the six ordinary values land between and . Use robust scaling when outliers are present, because the median and IQR hardly move for them: in the same data the robust value of is and that of is , 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 , so would be ; scikit-learn leaves its scale at 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 , while many statistics tools divide by (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 and , and two test values, and . Transformed with the training numbers they become and . Min–max gives and . The second is outside , and that is fine: it only says the value is above anything seen in training. Robust scaling gives and .
Now the tempting mistake: compute the mean and standard deviation of train and test together. They become and , and the test values become and . 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 and standard deviation , and they should not. (In the Titanic pipeline below, the scaled test ages have a mean of , not .) 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 , one from C becomes . Exactly one column is 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 in every row, so together they equal the intercept column. That is a copied feature: is singular and the weights are not unique. For categories plus an intercept there are columns of rank . 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 . 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 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 . 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 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
TargetEncoderdoes this insidefit_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 , and the test rows’ own median would have been . 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 of the time ( passengers) and those without ( passengers), because the column records the boat that survivors left in. All 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 on 328 held-out passengers. Add a single column saying whether boat is filled in, and the same model scores . 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 of the time. Without the refund column, test accuracy is . With it, . If the refund is unknown when the prediction is made and is filled with , the accuracy is , 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 rows and features of pure noise, with coin-flip labels, so nothing can be learned and honest accuracy is . Pick the features most related to the label using all 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 . With the features chosen on the 60 training rows only, it is . 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: test rows that are rows copied ten times give a true standard error of at accuracy , not (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.
Spotting a leak in your own project
A leak rarely announces itself. Habits that catch it:
- 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.
- Check the split: count duplicate rows and see whether any ID, patient or user appears on both sides.
- 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 .
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 to 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 , against to 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 and a standard deviation of from the training rows. The and the 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 . For the target encoder, fit(...).transform(...) on the training rows is the leaky version (correlation with the label), and fit_transform uses the cross-fitting of the out-of-fold idea (correlation near ). 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 , standard deviation , minimum , maximum , median and quartiles :
Multiplying feature by divides its weight by and turns the Hessian of the squared loss, , into with , so the curvature along that weight is multiplied by . Standardized features have diagonal entries equal to , which is why the bowl becomes round when the features are uncorrelated.
One-hot columns satisfy , the intercept column, so , not .
Target encoding of category with smoothing: , where is the number of training rows in , their mean label, the overall mean and a smoothing weight. Out of fold, and 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.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Exercises
- Using the training column (mean , , min , max , median , IQR ), scale a new test value of with each of the three scalers.
Show answer
Standardized: . Min–max: . Robust: . - For P1.D12’s values (median , quartiles and ), compute the min–max and robust values of and of . Which scaler keeps the ordinary values spread out?
Show answer
Min–max, with and : and , and the other six values fall between and . Robust, with IQR : and , while the others spread from to . Robust scaling keeps the ordinary values spread out. - 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 answer
Make 4, dropping one as the baseline. The 5 dummies add up to the intercept column, so the 6 columns have rank 5, and would be singular. - 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
. All three port columns are , 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. - 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. - Place hours on a circle with . Why is that better than the plain number for a method that uses distances, and how far apart are hours and ?
Show answer
With the plain number, hour and hour are apart although they are one hour apart in real life. On the circle they are apart. Hours and are opposite points, a distance of (the diameter).
Check your understanding
A pipeline will standardize a feature and then train a model. Which procedure is correct?
The numbers are learned once from the training rows and then reused. Scaling each set with its own statistics gives the same raw value different scaled values in different sets, so the model would see inputs on a different scale from the one it was trained on. Computing them on all rows lets the test rows influence the training, which is contamination. And leaving the test rows unscaled gives the model inputs it was never trained on.
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?
Rescaling a feature by a positive factor and shifting it keeps the order of the examples, and the split of a tree depends only on that order, so the splits are the same and the thresholds move along with the data. Equal scales matter for distances, gradient steps and penalties, not for threshold tests. Speed does not depend on how large the numbers are, and large numbers do not stop a tree from training.
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?
In every row exactly one of the three columns is 1, so their sum is a column of ones, the intercept. That is a copied feature as in P3.A2: infinitely many weight vectors give identical predictions, and the normal equations have no unique solution. Dropping one category removes the redundancy. Predictions for seen ports are not affected, the weights are not forced equal, and nothing says the test accuracy falls.
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?
In a category with few rows, the mean is close to those rows’ own labels, and with one row per category it equals the label. The model then looks excellent in training and the column carries little real signal for new categories. Encoding each fold with means from the other folds removes the row’s own label from its feature. Label means are ordinary numbers, the column is not constant, and the test labels are untouched.
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.