Skip to content
BIASED

Data, features and leakage

How raw columns become an object–feature matrix — feature types, one-hot and out-of-fold target encoding, scaling, missing values, feature engineering — and the two ways an evaluation is fooled — target leakage and train–test contamination.

From a table to a matrix

The topic What machine learning is set the problem up with two assumptions. Every object arrives as a vector x∈Rdx \in \mathbb R^d, and every training row is an independent draw from the distribution the model will meet. It ended by admitting that neither holds for raw data, and that the easiest way to break the second is to let information about the target slip into the features. This topic turns raw columns into features and shows how leakage makes a useless model look excellent.

A table of loan applications has a district name, a date, an income that some applicants left empty, a free-text purpose, and columns filled in months after the application was decided.

The goal is the object–feature matrix X∈Rn×dX \in \mathbb R^{n \times d}: one row per object, one column per feature, with xijx_{ij} the feature jj of object ii and y=(y1,…,yn)y = (y_1, \dots, y_n) the targets. Getting there starts with the type of each column.

Type Example What a model needs
Numeric income, area, number of purchases often a scale and a transform for skew
Binary owns a car nothing: 0 or 1
Categorical (nominal) district, product, browser an encoding; the categories have no order
Ordinal education level, rating 1–5 the order, but not necessarily equal steps
Date and time application date parts (hour, weekday, month) and differences ("days since")
Text, sets loan purpose, tags a vector, for example word counts

The type decides which arithmetic is meaningful. The mean of two browsers is not a browser. Store Chrome, Firefox and Safari as 1, 2, 3, and a model that multiplies the column by a weight will treat those codes as amounts. Text becomes a vector of word counts, a bag of words: an object–feature matrix with thousands of mostly zero columns. The course NLP builds it properly.

One-hot encoding

One-hot encoding replaces a feature with CC categories by CC binary columns, one per category. Each row has a single 1, in the column of its category. A linear model then learns one weight per category, which is exactly the freedom a nominal feature should have.

With an intercept in the model there is a catch. In every row the CC columns add up to 1, so together they repeat the intercept column. Adding a constant to every category weight and subtracting it from the intercept gives the same predictions, so without a penalty the weights are not unique. The usual fix is to drop one column. Its category becomes the reference, described by the intercept, and the other weights measure differences from it.

With a ridge or lasso penalty all CC columns can stay, because the penalty itself picks one solution. Dropping a column then changes the fit: the remaining weights shrink toward the reference category instead of toward a common value. The topic Regularization returns to this.

One-hot works well up to a few hundred categories. A feature with 100,000 values, such as a user, a shop or a postcode, gives a huge matrix in which most categories have a handful of rows. Their weights are estimated from almost nothing.

Target encoding

Target encoding replaces each category by one number, an estimate of the mean target in that category, E[Y∣category=c]\mathbb E[Y \mid \text{category} = c]. Write ncn_c for the number of training rows in category cc, yˉc\bar y_c for their mean target and yˉ\bar y for the overall mean.

For a rare category the raw mean yˉc\bar y_c is noisy. A category with one row would be encoded by that row's label alone. So the mean is shrunk toward the overall mean:

g(c)=ncyˉc+a yˉnc+a.g(c) = \frac{n_c \bar y_c + a\, \bar y}{n_c + a}.

The prior weight a>0a > 0 acts like aa extra rows whose target equals the overall mean. A category with many rows keeps nearly its own mean; a rare one stays near yˉ\bar y.

This is a familiar estimator. For a binary target, g(c)g(c) is the posterior mean of the beta–binomial model from the topic Bayesian inference, with the prior Beta(ayˉ, a(1−yˉ))\mathrm{Beta}(a\bar y,\ a(1 - \bar y)): its pseudo-counts add up to aa, and ayˉa \bar y of them are positive. For a numeric target it is the same kind of shrinkage, toward yˉ\bar y.

A worked example: a category with 3 rows, 2 of them positive, in data with an overall positive rate of 0.2, and a=10a = 10. Then

g=2+10⋅0.23+10=413≈0.308,g = \frac{2 + 10 \cdot 0.2}{3 + 10} = \frac{4}{13} \approx 0.308,

rather than the raw 2/32/3.

How target encoding leaks

Target encoding has a trap. Computed on the training rows, yˉc\bar y_c includes each row's own target. A category seen once is encoded by its own label, and a model that reads the encoding reads the answer.

Prokhorenkova et al. (2018), the CatBoost paper, give the clean case. Let every category be unique and every label a fair coin. On the training rows the encoding equals the label, so one threshold separates them perfectly. Every test row gets the prior and the model scores 0.5. The encoded feature behaves differently on training and test rows, which is exactly what a model must not be trained on.

Leaving only the row itself out does not fix it. When many rows share a category, their leave-one-out means still move with each row's own label, and the model can read that movement.

The fix is to encode each training row with statistics of other rows. Split the training rows into kk parts, called folds. Out-of-fold encoding encodes the rows of each fold with the category means of the remaining folds; test rows get the means of the whole training set. The same idea, used to estimate risk, is cross-validation, and the next topic builds it properly.

Eight rows, two categories, two folds, no smoothing:

Row Category yy Fold Naive gg Out-of-fold gg
1 A 1 1 0.75 1.0
2 A 0 1 0.75 1.0
3 A 1 2 0.75 0.5
4 A 1 2 0.75 0.5
5 B 0 1 0.25 0.5
6 B 1 2 0.25 0.0
7 B 0 2 0.25 0.0
8 B 0 1 0.25 0.5

Rows 1 and 2 are encoded from rows 3 and 4, both positive. The out-of-fold values are noisier: that is the honest price of not looking at a row's own label, and the reason they are smoothed in practice. CatBoost uses an ordered variant: it shuffles the rows and encodes each one from the rows before it.

How much does it matter? Take 2,000 rows, a category with 500 values of about 4 rows each, and random labels, so the category carries no information. A logistic regression on the naive encoding, computed on all rows, gets a cross-validated accuracy of 0.684. With the out-of-fold encoding fitted inside each training fold it gets 0.502, the chance level it deserves.

Scaling

A feature in roubles and a feature in years differ in spread by a factor of thousands. Several methods treat numbers as if their units were comparable.

  • Distances. Two applicants with incomes 50,000 and 52,000 and ages 25 and 60 are at Euclidean distance 20002+352≈2000.3\sqrt{2000^2 + 35^2} \approx 2000.3. The age difference adds almost nothing. On the wine data bundled with scikit-learn, where one feature has a standard deviation of 314 and another of 0.12, a 5-nearest-neighbour classifier has a cross-validated accuracy of 0.663 on the raw columns and 0.961 on standardized ones. The topic Nearest neighbours comes back to this.
  • Gradient descent. For least squares with two independent centred features of standard deviations 1 and 100, the condition number of X⊤XX^\top X is about 10410^4; after standardization it is 1.02. The condition number was defined in the topic Conditioning and numerical stability; the topic Gradient descent shows that the number of steps grows with it.
  • Penalties. A penalty on the weights treats all of them alike. A feature on a large scale needs a small weight and is barely penalized; the same information on a small scale is penalized heavily.

Standardization subtracts the mean of each column and divides by its standard deviation. Min–max scaling maps each column to [0,1][0, 1]. Robust scaling uses the median and the interquartile range, so that a few extreme values do not set the scale.

Not everything cares. A decision tree splits on a threshold of one feature at a time, and no monotone transformation of a feature changes its splits. Unpenalized least squares solved exactly gives the same predictions on any scale: the weight simply absorbs the change of units.

Whatever the method, its means and spreads are statistics of the data. They must be computed on the training rows only; the last block of this topic says why.

Missing values and new features

A value can be missing for reasons that matter. Rubin (1976) distinguishes three cases. Values missing completely at random are unrelated to anything, like a sensor dropout. Values missing at random depend only on features we observe. Values missing not at random depend on the missing value itself: high earners declining to report their income. In the last case the gap is itself information.

How pandas marks a missing cell (NaN, pd.NA, NaT) and fills it is in the topic Data frames with pandas. Here the question is what to fill it with. Most models need a number in every cell. The standard recipe fills the gap with a statistic of the training column, the median for skewed features or the most frequent category, and adds a binary missing indicator:

y^=w0+w1x1+w2 [x1 missing]+…\hat y = w_0 + w_1 x_1 + w_2\, [x_1 \text{ missing}] + \dots

Gradient boosting libraries handle missing values natively: they send them down whichever branch of a split reduces the loss more.

Filling gaps makes features usable; feature engineering makes patterns easy to find. Typical constructions on tabular data:

  • Ratios and differences: debt divided by income, price per square metre, days from registration to the first purchase.
  • Parts of dates: hour, day of week, month, a holiday flag. Demand and fraud both have strong weekly cycles.
  • Transforms of skewed amounts: log⁡(1+x)\log(1 + x) for incomes, so a linear model sees proportional rather than absolute differences.
  • Aggregates over history: purchases in the last 30 days, the mean basket, the share of returned orders. Each is computed as of the moment of prediction, from events before it.
  • Interactions: the product of two features, for models that cannot form it themselves. Trees and neural networks form interactions on their own.

Target leakage

Key idea. A model is evaluated honestly only if, for every evaluation row, the features and every fitted step of the pipeline use nothing that would not be available when the prediction is made in deployment. Leakage is any violation of this rule, and it almost always makes the estimate optimistic.

The first kind is target leakage: a feature that carries information about the target that will not exist at prediction time (Kaufman et al., 2012). Typical forms:

  • Computed after the event. Predicting hospital readmission with a diagnosis code entered at the readmission. The column exists in the historical table only because the outcome already happened.
  • A disguised copy of the target. Predicting churn with "account closing date is filled in".
  • Aggregates that include the future. "Number of support calls this year" when the churn prediction is made in March.
  • Artefacts of collection. Rows sorted by outcome, so the row number predicts the label; positive examples gathered from a different source in a different format.

The symptom is a model far better than anyone expected, with one or two features doing most of the work. The cure is a timestamp for every feature and the rule that a feature may only use information from before the moment of prediction.

This is not a beginner's mistake. Kapoor and Narayanan (2023) found leakage in published work in 17 scientific fields, affecting 294 papers. In their re-analysis of civil-war prediction, complex models lost their advantage over logistic regression once the leakage was removed.

Train–test contamination

The second kind of leakage needs no bad feature. Train–test contamination happens when any fitted step of the pipeline, not only the model, sees the rows used for evaluation:

  • an imputer or a scaler whose statistics were computed on all rows;
  • a target encoding computed on all rows;
  • feature selection on all rows: keep the features most associated with the label, then cross-validate a model on them;
  • duplicates of the same object in training and evaluation data.

The topic Data frames with pandas ended with the first item: a mean fill computed on the whole table had seen the test period. How much harm a step does depends on how much it learns about the target. A scaler learns only means and spreads: on the wine data, standardizing all rows before cross-validation gives the same 0.961 as standardizing inside each fold. Feature selection learns which features agree with the labels, the evaluation labels included. On pure noise the effect is dramatic:

import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
 
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 10_000))              # pure noise
y = rng.permutation(np.repeat([0, 1], 50))      # labels unrelated to X
cv = StratifiedKFold(5, shuffle=True, random_state=0)
 
X20 = SelectKBest(f_classif, k=20).fit_transform(X, y)   # selected on all rows
wrong = cross_val_score(LogisticRegression(), X20, y, cv=cv).mean()
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
right = cross_val_score(pipe, X, y, cv=cv).mean()        # selected inside each fold
print(round(wrong, 2), round(right, 2))
0.87 0.49

Among 10,000 noise features, some agree with the 100 labels by chance. Selecting on all rows picks exactly those chance agreements, and the held-out folds then "confirm" them: 0.87 accuracy from nothing. Inside the pipeline, selection is redone on each training part and the estimate falls to the true 0.5 (Hastie, Tibshirani and Friedman, 2009, Section 7.10.2).

The rule: every data-dependent step is part of the model, a pipeline fitted on the training part of each split and only applied to the evaluation part. The same rule covers the person tuning the model. Choosing features by looking at test results is feature selection on the test set.

Leakage and contamination test a model on data it has, in some way, already seen. Removing them is necessary but not enough. Even a clean validation score is a random number with an error bar, the best of many models looks better than it is, and the split must match the way the model will be used. The next topic, Validation and overfitting, builds the protocol for estimating the risk honestly.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.