AI from scratch · Features and leakage · Stage 3: classic ML and judging models
Features and leakage
A model only sees the columns you hand it. Most of the work in real ML is making those columns honest and useful: cleaning codes that pretend to be numbers, putting columns on comparable scales, turning categories into numbers, and above all making sure no column, and no step of your process, quietly tells the model the answer. This lesson uses 10,297 real phone calls a Portuguese bank made to sell term deposits, 2008 to 2010, and the question the bank cared about: will this person say yes?
Data: the Bank Marketing dataset (Moro, Cortez and Rita, UCI Machine Learning Repository, CC BY 4.0), every fourth row of the full file, in date order.
1. Look before you model
Before any model: how many rows, which columns, what the answer looks like. Every box below reuses this one's table df.
About 11.4% of calls ended in a yes. A model that says "no" to everyone: what accuracy, in percent?
Look first: the shape, the balance and the do-nothing baseline tell you what a good score even means.
2. Cleaning: codes that pretend to be numbers
Real tables are full of values that aren't what they look like. Here, pdays is "days since this person was last contacted", except that 999 means never contacted. A model reading it as a number thinks never-contacted people were called 999 days ago: technically far away, but the real story is a yes/no fact. Category columns hide "unknown" the same way. The usual fixes: turn the code into its own yes/no column, and give missing values a sensible fill (often the median) plus a flag saying they were missing, because being missing often carries information.
A column "years at current job" uses −1 for "not employed". For a linear model, what's the cleanest fix?
- Leave it: −1 is just a number
- Add a 0/1 column "not employed", and fill the −1s with a neutral value like 0
- Delete the rows with −1
A code like 999 is a fact dressed as a number; give the fact its own yes/no column.
3. Scaling: who cares about units
Age runs from 17 to 98, the interest rate from 0.6 to 5. Anything that measures distance or takes gradient steps cares: calculus 3 showed that stretched features make a stretched valley that gradient descent zigzags down, and regularization (chapter 11) punishes big weights, which depend on units. Two common rescalings:
\[ z = \frac{x - \mu}{\sigma} \ \ \text{(standardize: mean 0, spread 1)} \qquad x' = \frac{x - \min}{\max - \min} \ \ \text{(min-max: 0 to 1)} \]
Trees don't care: "is age < 40?" asks the same question in any units. Linear models, neural networks and anything with distances (k-nearest neighbors, clustering) do.
One rule matters more than which scaling you pick: the mean, spread, min and max come from the training data only, and the same numbers are then applied to validation, test and real traffic. Section 4 shows how to make that automatic.
Models built on distances or gradient steps need columns on comparable scales, with the scaling learned from training rows only.
4. Categories into numbers, and pipelines
Models need numbers. For a category like job, writing admin = 1, blue-collar = 2, … invents an order (is a technician "between" two jobs?) that a linear model will take literally. One-hot encoding gives each category its own 0/1 column instead. Categories with a real order (education levels) can be numbered in that order. A column with thousands of categories (zip codes, product ids) is better replaced by counts or by learned embeddings (stage 6).
New columns from old ones are often the biggest win, because they say what you know about the problem: the hour and weekday from a timestamp, a ratio (debt ÷ income), a log of a skewed amount (probability 2), a flag for a code. Chapter 13's boosted trees find some interactions themselves; a well-chosen feature still beats hoping.
Every step above learns something from data: the scaler its means, the encoder its list of categories, an imputer its medians. Each must learn from the training rows only. A pipeline chains the steps with the model, so fit learns everything from the data you give it and predict reuses it, and cross-validation refits the whole chain inside every fold. make_column_transformer sends each group of columns to its own step.
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
prep = make_column_transformer((OneHotEncoder(handle_unknown="ignore"), category_columns),
(StandardScaler(), number_columns))
model = make_pipeline(prep, LogisticRegression(max_iter=2000))
model.fit(X_train, y_train) # the scaler's means and the encoder's categories: from training rows only
model.predict(X_test) # ...reused here, never refitted
Every step that learns from data belongs inside the pipeline, so it learns from training rows only.
5. Imbalance: when yes is rare
With 11% yes, a model minimizing average loss learns that "no" is usually safe, and at the default threshold of 0.5 it finds few of the yeses. Three tools, from the simplest:
- Split with
stratify=y, so train and test keep the same 11%. - Weight the classes:
class_weight="balanced"makes each rare example count as much as several common ones in the loss. - Move the threshold (chapter 12), using what a missed yes and a wasted call each cost. Resampling (copying rare rows, dropping common ones) does roughly what weighting does, with more ways to go wrong.
Class weights roughly tripled the recall, accuracy fell, and the AUC didn't move. Why didn't the AUC move?
- Weighting mostly shifts every score the same way, like moving the threshold, so the ranking of calls (which is all AUC measures) barely changes
- AUC ignores the model's scores
- The weights had no effect
Weights and thresholds change which calls get flagged, not how the calls are ranked.
6. Leakage: the model that's too good
Leakage is when something available while you build the model won't be available when it's used, so the test score measures a world that doesn't exist. It's the most expensive bug in ML: everything works, the numbers are great, and the model fails at launch. Three kinds cover most real cases.
A column that knows the answer. duration is how long the call lasted. Long calls are calls where the person was interested, so it predicts yes superbly, but nobody knows a call's length before making it. The dataset's own notes say to drop it for any realistic model. A split that peeks at the future. Below are the calls in time order: the yellow line is the share who said yes, the blue line the 3-month interest rate (euribor). After the 2008 crash, rates collapsed and people started saying yes far more often. A random split puts calls from the same weeks in both training and test, so the model can look up "what did people say when the rate was 1.06%?", and that column alone works like a calendar.
The AUCs in the readout are real: a boosted-tree model (chapter 13) trained on this table in each of the four settings. Run them yourself:
The honest number is the last one with the honest columns: about 0.67, not 0.94. The interest rate alone drops from 0.77 to exactly 0.5, a coin flip, once it can't look up its neighbors. That's not the model getting worse; it's the test getting honest. Whenever the data has time in it, split by time, as the model will meet it.
A preprocessing step that saw the test rows. The subtle kind. Fitting a scaler, choosing features, or filling missing values on all the data before splitting lets the test rows shape the training. Here is the classic demonstration, on pure noise: 100 people, 5,000 random columns, coin-flip labels. Pick the 20 columns that best match the labels using all 100 rows, then cross-validate.
About 85% accuracy on coin flips, because each fold's test rows helped choose the columns. Inside a pipeline, every fold chooses its own columns from its own training rows, and the score falls to a coin flip, which is the truth. A scaler fitted on everything leaks far less, but the habit is the same: everything that learns goes inside the pipeline.
Why choosing columns on all the data turns noise into signal
- Each of the 5,000 noise columns matches the 100 coin-flip labels a little, by chance: its correlation with them is spread around 0 with a standard deviation of about \(1/\sqrt{100} = 0.1\).
- With 5,000 tries, the best ones sit far out in the tail. In one run the top correlation was 0.38 and the 20th best 0.28, three to four spreads out.
- Those 20 columns were picked because they happen to line up with every row's label, including the rows that later serve as test folds.
- So in each fold the test rows' labels aren't fresh: they already voted on which columns to keep, and the columns agree with them. The model looks 85% right.
- Inside a pipeline, each fold picks its columns from its own training rows. The test rows never voted, the chance agreement doesn't carry over, and the score falls to about 50%.
- The general rule: any choice made by looking at labels (columns, thresholds, settings) has to be made without the rows that will judge it.
A fourth kind hides in the rows: the same person, patient, or house in both training and test. The model recognizes them instead of generalizing. Split by the group (scikit-learn's GroupKFold), so each person is entirely on one side.
A hospital model predicts pneumonia from patient records and scores 0.99 AUC. Its strongest feature is "antibiotics prescribed". What's wrong?
- Nothing: antibiotics are a real clue
- The classes are imbalanced
- Target leakage: antibiotics are prescribed after a diagnosis, so the column records the answer
Leakage is anything the model sees while you build it that it won't see at the moment it has to decide.
7. A leak checklist
| Ask | If yes |
|---|---|
| Is any column filled in after the moment of prediction (treatment, duration, status, refund)? | Drop it, or rebuild it from what was known at that moment. |
| Does the data have time in it? | Split by time: train on the past, test on the later period. |
| Can the same person, device or place appear twice? | Split by group. |
| Did anything learn from data before the split (scaling, filling, selecting, encoding, deduplicating)? | Move it into a pipeline. |
| Is one feature suspiciously strong, or the score better than anyone expected? | Treat it as a leak until proven otherwise: look at that feature's importance (chapter 13) and how it's made. |
Where it breaks: fixes that cause their own problems
- Class weights bend the probabilities. On the first 75% of the calls (6.6% yes), plain logistic regression's average predicted probability is 0.066, matching reality; with
class_weight="balanced"it's 0.44. That's fine for ranking and flagging and wrong for anyone who reads the number as a chance (expected sign-ups, a budget). Recalibrate on validation data (chapter 12), or keep the unweighted model and move the threshold. - A time split can still leak through a feature. "Customer's total purchases", computed over the whole history, includes purchases after the prediction date even when the rows are split by time. Build every feature as of the moment of prediction, from earlier rows only.
- Groups you didn't name.
GroupKFoldonly knows the groups you give it. The same photo resized, the same house relisted, one patient under two ids: near-duplicates cross the split anyway. Deduplicate, or group by a fingerprint (a hash of the image, the address) before splitting.
8. What to carry forward
- Look first: shape, the answer's balance, codes like 999 and "unknown". Turn codes into flags.
- Scale for gradient descent, distances and regularization; trees don't need it. One-hot for categories without an order.
- Everything that learns from data (scalers, encoders, imputers, feature selection) is fitted on training rows only: put it in a pipeline.
- Rare positives: stratify, weight the classes or move the threshold, and judge with recall, precision and AUC, not accuracy.
- Leakage: a column that knows the answer, a split that peeks at the future or at the same person, a step that saw the test rows. The honest score is the one that matches launch day.
All lessons: AI from scratch. Kaggle Learn's free "Data Leakage" lesson has more examples.
Last updated