Sub topic 8
Scaling Features Inside a Pipeline
This chapter assumes you have the train/test split from the earlier chapters and understand data leakage. It also assumes you can read basic scikit-learn code: fit, predict and transform. By the end you will have a scaler and a model wrapped in one object. That object is safe to cross-validate, tune and save.
Why the features need scaling
The California housing features sit on very different numeric ranges. Median income (MedInc) is in tens of thousands of dollars and usually falls between 0 and 15. Population is a block-group head count that often reaches thousands. Latitude and Longitude are degrees, so they are almost constant in size but large in absolute value.
Some models do not care about this. Tree-based models split on thresholds, so multiplying a column by 1000 changes nothing. Other models are sensitive to scale:
- Regularized linear models such as Ridge add a penalty on the size of the coefficients. A feature measured in small units needs a large coefficient, so it gets penalized more. The penalty then depends on your choice of units, which is arbitrary.
- Distance-based models such as k-nearest neighbors let the largest-range feature dominate the distance.
- Gradient-descent solvers converge faster and more reliably when features are on comparable scales.
The next chapter fits Ridge, so scaling matters from here on. The standard fix is StandardScaler, which rewrites each column as
z = (x - mean) / std
After scaling, every column has mean 0 and standard deviation 1. The values are computed per column, using only that column's statistics.
Scaling by hand, and where it goes wrong
A scaler is a transformer, so it has two stages. fit learns statistics from data (one mean and one standard deviation per column). transform applies them. The following code does this manually, with the statistics learned from the training set only.
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
scaler = StandardScaler().fit(X_train)
print(pd.DataFrame({"mean": scaler.mean_, "std": scaler.scale_}, index=X.columns))
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)
manual = LinearRegression().fit(X_train_s, y_train)
manual_pred = manual.predict(X_test_s)
pipe = make_pipeline(StandardScaler(), LinearRegression())
pipe.fit(X_train, y_train)
print(np.allclose(manual_pred, pipe.predict(X_test)))The printed table shows the learned statistics. Population has a mean above 1,000 and a standard deviation in the same range. MedInc has a mean near 4. The last line prints True, because the pipeline does exactly what the manual code does.
The manual version works, but it relies on you to avoid three mistakes:
- Calling
fitorfit_transformon the fullXbefore splitting. The test rows then influence the mean and standard deviation. - Calling
fit_transformonX_test. The test set then gets its own statistics, which differ from the training ones. The model sees features on a scale it was not trained on, and in effect you peek at the test distribution. - Forgetting to apply the same transform to new data later, at prediction time.
The first mistake is the leakage described in the previous chapter. It is subtle because nothing crashes, and the scores look slightly better than they should.
What a pipeline does
A Pipeline chains transformers and a final estimator into one object that behaves like an estimator. make_pipeline builds one and names the steps automatically from the lowercased class names.
Since the diagram must use the required fence, here it is in full.
The rules are simple:
pipe.fit(X, y)callsfit_transformon each transformer in order, thenfiton the last step.pipe.predict(X_new)callstransformon each transformer, thenpredicton the last step. No transformer is refit.- The scaler's statistics live inside the pipeline object, so saving the pipeline saves them too.
You can inspect individual steps after fitting:
print(pipe.named_steps["standardscaler"].mean_)
print(pipe[-1].coef_)pipe[0] is the scaler and pipe[-1] is the model. Because the model was trained on scaled features, each coefficient means "change in predicted value per one standard deviation of that feature". That makes coefficients comparable across features, which was not true on raw units.
Why pipelines matter for cross-validation
Cross-validation splits the training set into folds and repeatedly trains on some folds and validates on one. If you scale the whole training set first and then cross-validate, each validation fold has already contributed to the scaler's statistics. That is leakage inside the training set.
When you pass a pipeline to cross_val_score or GridSearchCV, scikit-learn clones the whole pipeline for each fold. It fits the scaler on that fold's training rows only, and applies it to the held-out fold. The next chapters rely on this behavior.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(
pipe, X_train, y_train, cv=5, scoring="neg_mean_absolute_error"
)
print("Linear CV MAE:", -scores.mean())For a plain StandardScaler, the leaked statistics barely change the score, because a mean and a standard deviation are summaries of thousands of rows. Do not take that as permission to skip the pipeline. The same structure protects you when a step is more powerful, such as target encoding, feature selection or imputation based on other columns. In those cases the leak can be large.
Scaling only some columns
All eight California housing features are numeric, so one scaler for every column is fine here. Real datasets mix numeric and categorical columns, and a ColumnTransformer applies different steps to different columns. This example scales two skewed columns and passes the rest through unchanged:
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
partial = ColumnTransformer(
[("scale", StandardScaler(), ["Population", "AveOccup"])],
remainder="passthrough",
)
partial_pipe = make_pipeline(partial, LinearRegression())
partial_pipe.fit(X_train, y_train)
print(partial_pipe.predict(X_test.iloc[:3]))A ColumnTransformer returns a NumPy array by default, so column names are lost after the transform. Call partial.set_output(transform="pandas") if you need a DataFrame between steps, for example to inspect the intermediate result.
Edge cases and choices
- Outliers.
StandardScaleruses the mean and standard deviation, which extreme values distort.AveOccupin this dataset has a few huge values, such as blocks with more than a thousand occupants per household. After scaling, most rows are squeezed into a narrow band.RobustScaleruses the median and interquartile range instead, and is a drop-in replacement if outliers bother your model. It does not remove them. - Constant columns. A column with zero variance gets a scale of 1 instead of 0, so you will not see a divide-by-zero.
- Missing values.
StandardScalerignoresNaNwhen learning statistics and keepsNaNin the output. A later model that cannot handle them will fail, so add an imputer step before the scaler if needed. - The target. Pipelines transform features, not
y. If you want to scale or log-transform the target, wrap the model inTransformedTargetRegressor. This tutorial keeps the target in its original units, so MAE stays readable as "hundreds of thousands of dollars". - Trees. Do not add a scaler in front of
HistGradientBoostingRegressor. It does no harm, but it adds nothing, and it makes the saved pipeline larger and harder to read. - Step names in tuning. Parameters of a pipeline step are addressed as
stepname__parameter, such asstandardscaler__with_meanorridge__alpha. You will need this form when you tune a pipeline.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Test score is better than cross-validation by a suspicious margin | Scaler fitted on all data before the split | Split first, then put the scaler in a pipeline |
| Predictions on new data are wildly off | New data was scaled with its own statistics, or not scaled at all | Call `pipe.predict` on raw data, not on pre-scaled arrays |
| `NotFittedError` on `transform` | Scaler was created but never fitted | Fit the pipeline, or fit the scaler on training data first |
| Feature names warning from scikit-learn | Model fitted on a DataFrame but given an array, or the reverse | Use the same input type for `fit` and `predict` |
| `KeyError` when accessing a step | Step name does not match the auto-generated name | Check `pipe.named_steps.keys()` |
What comes next
The pipeline you built here has a plain LinearRegression at the end. In the next chapter you replace it with Ridge. The scaler stays in place, which is what lets Ridge's penalty treat every feature on equal terms.
Exercise
A teammate writes X_scaled = StandardScaler().fit_transform(X), then calls train_test_split(X_scaled, y) and trains a model. Explain what is wrong, and write the corrected structure using a pipeline.
Show answer
The scaler learned its mean and standard deviation from every row, including the rows that later become the test set. Information from the test set has leaked into preprocessing, so the test score is optimistic. The fix is to split first and let the pipeline fit the scaler on the training rows only: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42), then pipe = make_pipeline(StandardScaler(), LinearRegression()).fit(X_train, y_train), then pipe.predict(X_test).
Exercise
You run 5-fold cross-validation with a pipeline containing a StandardScaler. How many times is the scaler fitted, and on which rows each time?
Show answer
Five times, once per fold. Each fit uses only the four folds that serve as training data for that round. The held-out fold is transformed with those statistics and never contributes to them.
Exercise
After fitting pipe = make_pipeline(StandardScaler(), LinearRegression()), how do you read the scaler's learned column means, and why can you compare the model's coefficients across features?
Show answer
Use pipe.named_steps["standardscaler"].mean_ or pipe[0].mean_. The model was trained on standardized features, so each coefficient is the change in predicted house value for a one-standard-deviation increase in that feature, which puts all features on the same footing.