Scaling and Pipelines: Preparation That Stays Honest
Before a model can learn from a table, the columns usually need some preparation: numbers put on a common scale, text categories turned into 0 and 1 columns. A model built on a weighted sum needs its numbers scaled to train properly. But preparation done in the wrong order can quietly let held-out rows influence training, so that a score looks better than it is. A scikit-learn pipeline joins preparation and model into one piece that keeps every score honest.
Features measured in very different ranges
Take a small table of five customers with three features: how many months each one has been a customer, how much they have paid in total, and whether they use technical support (1 for yes, 0 for no). The months run from 2 to 48, the total paid from 140 to 4,500, and the support column is only ever 0 or 1. Each column is measured in its own unit, and nothing about the units says how much the column matters for a prediction.
One way to see how far a column's values are spread out is its standard deviation: take each value's distance from the column's average, square those distances, average the squares, and take the square root. The result is a kind of typical distance from the average, in the column's own unit.
- Months as a customer 16.7
- Total paid 1,561.7
- Uses support 0.49
For a decision tree these ranges make no difference. A tree asks questions such as "is the total paid below 1,000?", and a question like that only depends on the order of the values: which rows fall below the threshold and which fall above it. The scikit-learn documentation describes tree models as "(almost) not affected by scaling".
A model built on a weighted sum, such as logistic regression, is different. It multiplies each feature by a weight and adds the results. Training finds those weights by starting from zero and adjusting them a little at a time; each step is guided by how much the error changes when a weight changes. With the columns above, a tiny change to the weight of total paid moves the sum by thousands. The weight of the support column, on the other hand, has to change a lot before it moves the sum at all. A step size that is safe for one weight is far too small for another, so the training needs many more steps to settle on all of them together.
scikit-learn's LogisticRegression allows at most 100 of these steps by default (its max_iter setting). When it reaches that limit without settling, it does not fail: it gives a ConvergenceWarning and returns a model whose weights simply stopped where they were. The warning itself suggests two ways out: allow more steps, or scale the data. Allowing more steps only gives the training more time; scaling removes the reason it was slow.
The ranges also affect the result itself, not only the training time. Logistic regression applies regularization by default: a pull that holds every weight back by the same rule, with its strength set by C. A feature measured in large numbers needs only a small weight to matter, and a feature in small numbers needs a large one. The same rule therefore holds the two features back unequally. On a common scale, the weights can also be compared with each other: a larger weight then means a stronger push.
True or false?
A logistic regression that reaches its step limit on unscaled data stops with an error and returns no model.
False. It gives a ConvergenceWarning and still returns a fitted model; its weights just stopped before they settled.
A decision tree trained on scaled features asks the same questions, only with different threshold numbers.
True. Scaling keeps the order of the values, so each threshold still splits the rows into the same two groups; only its number changes.
Standardizing: mean 0 and spread 1
The usual fix is to standardize each feature: subtract the column's average (its mean) from every value, then divide by the column's standard deviation. Afterwards every column has a mean of 0 and a standard deviation of 1, whatever its original unit. A value now says how many standard deviations a customer sits above or below the average customer.
Standardized value
| Customer | Months | Total paid | Months, standardized | Total paid, standardized |
|---|---|---|---|---|
| A | 2 | 140 | -1.31 | -1.13 |
| B | 10 | 660 | -0.84 | -0.79 |
| C | 24 | 1,500 | 0.00 | -0.26 |
| D | 36 | 2,700 | 0.72 | 0.51 |
| E | 48 | 4,500 | 1.43 | 1.66 |
| Mean | 24 | 1,900 | 0 | 0 |
| Standard deviation | 16.7 | 1,561.7 | 1 | 1 |
Standardizing only shifts and stretches each column. It does not change the shape of the values or their order: customer E still has the highest total paid, and the gaps between customers keep their proportions. A tree question "is the total paid below 1,000?" becomes "is the standardized total paid below -0.58?", and the same customers answer yes.
In scikit-learn this is StandardScaler. Like every preparation step, it works in two moves. fit learns the numbers from the rows it is given: the mean and standard deviation of each column, kept in its mean_ and scale_ attributes. transform then applies those stored numbers to any rows. Rows given to transform later, such as validation rows, are scaled with the training mean and standard deviation, not with their own. That split between learning and applying is what the rest of this page depends on.
True or false?
After standardizing, a column follows a bell-shaped curve.
False. Standardizing subtracts one number and divides by another. A lopsided column stays exactly as lopsided, only centred on 0 with a spread of 1.
Validation rows scaled with the training mean and standard deviation may come out with a mean that is not exactly 0.
True. The stored numbers were learned from the training rows, so only those are exactly centred; other rows land close to 0 but rarely on it.
Data leakage: held-out rows that reach the training
Held-out rows, the validation and test rows, exist to stand in for customers the model has never seen. Their score means something only if nothing about them took part in building the model. Data leakage is when information from held-out rows reaches the model during training anyway. The model then gets help it will not have on truly new rows, and its score looks better than its real performance.
Preparation is an easy place for this to happen. Standardizing the whole table first and splitting it afterwards looks harmless, but the mean and standard deviation the scaler learned then include the held-out rows. The training rows are scaled with numbers partly computed from the rows that will later judge the model. The same goes for any step that learns from data: the list of categories a one-hot encoder finds, a value used to fill blanks, a choice of which columns to keep.
- All rows
- Fit the scaler mean from all rows
- Split
- Train the model
- Score held-out rows looks too good
- All rows to Fit the scaler
- Fit the scaler to Split
- Split to Train the model
- Train the model to Score held-out rows
- All rows
- Split
- Fit the scaler training rows only
- Train the model
- Score held-out rows transformed, never fitted
- All rows to Split
- Split to Fit the scaler
- Fit the scaler to Train the model
- Train the model to Score held-out rows
The rule in the scikit-learn documentation is short: never call fit on held-out data. Split first, before any preparation; fit each preparation step on the training rows; and only transform the held-out rows with what was learned.
How much a leak inflates a score depends on the step. With a scaler on a large table, the mean of all rows is usually close to the mean of the training rows, so the gap can be small. With a step that chooses columns, it can be dramatic: the documentation shows a table of random numbers with random answers, where any honest model scores about 0.5. Choosing columns on all rows before splitting gave an accuracy of 0.76; choosing them on the training rows only gave the honest 0.5. A small gap is still a wrong number, and nothing in the score warns you which case you are in.
Cross-validation is not protected by itself. If the scaler is fitted on the whole training part and the scaled rows are then cut into folds, every fold that is held out for scoring has already shaped the scaler. To stay honest, the preparation has to be learned again in each round, from that round's training folds only.
True or false?
Leakage can only happen through the test set, so validation scores and cross-validation are safe from it.
False. Any held-out rows can leak. A scaler fitted before cross-validation has seen every fold that is later held out for scoring.
A preparation step fitted on all rows before splitting can make a score look better even when no label was used.
True. The scaler never sees the answers, but its mean and spread still carry information about the held-out rows into training.
A pipeline: preparation and model as one estimator
Keeping every preparation step fitted on the right rows by hand is easy to get wrong, especially inside cross-validation, where the training rows change every round. A pipeline removes that work. It chains the preparation steps and the model into one object that behaves like a single model: it has fit, predict and score, and it can be passed anywhere a model can.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X_train, y_train) # scaler learns from training rows, then the model trains
print(model.score(X_val, y_val)) # validation rows are only transformed, then scoredHere X_train and y_train are the training features and answers, X_val and y_val the validation ones. Calling fit on the pipeline fits each preparation step in turn on the rows it receives, passes the transformed rows on to the next step, and finally fits the model on the result. Calling predict or score runs the same steps with transform only, using what was learned during fit. For a classifier, score returns the accuracy on the rows it is given, so the printed number is the share of validation customers predicted correctly.
For this to work, every step except the last must be a transformer, a step with a transform method; the last one is the model. make_pipeline names the steps after their classes in lowercase (standardscaler, logisticregression), so model[-1] or model.named_steps["logisticregression"] reaches the trained model and its weights.
The pipeline pays off most under cross-validation. Give the pipeline, not the prepared rows, to cross_val_score, and each round fits the whole pipeline again, from scratch, on that round's training folds. The scaler's mean and standard deviation are learned from those folds, and the held-out fold is only transformed and scored.
- score
- fit
- fit
- fit
- fit
- fit
- score
- fit
- fit
- fit
- fit
- fit
- score
- fit
- fit
- fit
- fit
- fit
- score
- fit
- fit
- fit
- fit
- fit
- score
In every round the scaler and the model are fitted on the four folds marked fit and never see the fold being scored, so each of the five scores is measured on rows that took no part in any step of that round's training. The same holds for every other step placed in the pipeline.
True or false?
Under cross-validation, a pipeline learns its scaling numbers once and reuses them in every round.
False. Each round fits the whole pipeline again on that round's training folds, so the scaler gets new numbers every round.
Calling predict on a fitted pipeline scales the new rows with the numbers learned during fit.
True. predict runs every preparation step with transform only, then the model's predict, so new rows never change what the steps learned.
Different columns, different preparation
A real table mixes kinds of columns. Number columns such as months or a monthly bill need standardizing; text category columns such as a plan type or a payment method need one-hot encoding, one 0 or 1 column per category value. Neither step suits the other kind of column. scikit-learn's ColumnTransformer sends each group of columns to its own preparation step and places the results side by side as one table of numbers for the model.
- Customer table
- Number columns months, monthly bill
- Category columns plan, payment method
- StandardScaler
- OneHotEncoder
- Joined side by side one table of numbers
- LogisticRegression
- Customer table to Number columns
- Customer table to Category columns
- Number columns to StandardScaler
- Category columns to OneHotEncoder
- StandardScaler to Joined side by side
- OneHotEncoder to Joined side by side
- Joined side by side to LogisticRegression
The ColumnTransformer is itself a transformer, so it becomes the first step of the pipeline, and the model the last. The whole preparation is then fitted together with the model, on the training rows only.
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
prepare = ColumnTransformer([
("numbers", StandardScaler(), ["months", "monthly_bill"]),
("categories", OneHotEncoder(handle_unknown="ignore"), ["plan", "payment_method"]),
])
model = Pipeline([
("prepare", prepare),
("classify", LogisticRegression()),
])
scores = cross_val_score(model, X_train, y_train, cv=5)
print(scores.mean(), scores.std())Each entry of the ColumnTransformer is a name, a preparation step and a list of column names. The column names go in a list even when there is only one, because these steps expect a table of columns, not a single column. Pipeline takes its steps as (name, step) pairs; the names are yours to choose.
Two defaults deserve attention. Columns that no entry names are dropped (remainder="drop"), silently, so a forgotten column simply never reaches the model; remainder="passthrough" keeps them unchanged instead. And OneHotEncoder raises an error by default when it meets a category value it did not see during fit. Under cross-validation a rare value can sit only in the held-out fold, which is why the example sets handle_unknown="ignore": such a value then becomes all zeros in the category columns.
True or false?
A column left out of every entry of a ColumnTransformer is passed to the model unchanged.
False. The default remainder is drop, so it disappears from the output. Only remainder="passthrough" keeps it.
Inside a pipeline under cross-validation, the one-hot encoder learns its list of categories again from each round's training folds.
True. The ColumnTransformer is a step of the pipeline, so it is refitted with everything else in every round.