Sub topic 8
Scaling Features Inside a Pipeline
This chapter assumes you can split data with train_test_split, you know why a test set must stay untouched, and you have seen the idea of data leakage from the previous chapter. You should also be comfortable with pandas DataFrames and with calling fit and predict on a scikit-learn estimator.
Why scale at all
The California housing columns sit on very different ranges. MedInc is roughly 0 to 15, while Population can reach tens of thousands. Many models, including Ridge regression, are sensitive to this. Ridge penalizes large coefficients, and a coefficient's size depends on the units of its feature. Without scaling, the penalty treats features unequally for reasons that have nothing to do with their usefulness.
StandardScaler fixes this. It learns the mean and standard deviation of each column, then transforms every value to (x - mean) / std. Each column ends up with mean 0 and standard deviation 1.
The leakage trap
The scaler learns from data, so it must learn only from training data. A common mistake is to scale everything first and split afterward:
from sklearn.preprocessing import StandardScaler
# Wrong: the scaler sees the test rows before the split
X_scaled = StandardScaler().fit_transform(X)Here the mean and standard deviation include test rows. Information about the test set has leaked into training. The effect on one split is often small, but the habit becomes harmful with cross-validation, where every fold's validation rows would influence the scaling.
The correct sequence has three steps:
- Call
fiton the training data only. The scaler stores the means and standard deviations. - Call
transformon the training data. - Call
transformon any new data, using the stored training values.
Doing this by hand is easy to get wrong. A pipeline does it for you.
Building a pipeline
A Pipeline chains steps. Every step except the last is a transformer, and the last is a model. make_pipeline names the steps automatically.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
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
)
ridge = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
ridge.fit(X_train, y_train)
print(ridge.named_steps)
print(ridge.predict(X_test.iloc[:3]))When you call ridge.fit(X_train, y_train), the pipeline fits the scaler on X_train, transforms it, and passes the result to Ridge. When you call ridge.predict(...), the pipeline applies the already fitted scaler and then asks Ridge for predictions. You never touch the test data during fitting.
Checking what the scaler learned
You can reach each step through named_steps. The names come from the lowercase class names.
scaler = ridge.named_steps["standardscaler"]
print(scaler.mean_)
print(scaler.scale_)These values come from X_train alone. If you compute the means on the full DataFrame, they will differ slightly. That difference is the leaked information.
Common errors
- Scaling before splitting. Always split first, then put the scaler in a pipeline.
- Calling
fit_transformon the test set. This refits the scaler on test data. Use the pipeline'spredict, or calltransformonly. - Scaling the target.
StandardScalerin the pipeline changes only the features. The targetystays in its original units, so your MAE remains in units of $100,000. - Wrong step name.
named_steps["StandardScaler"]raises aKeyError. The key is"standardscaler".
Exercise
You compute StandardScaler().fit_transform(X) on the full dataset and then split into train and test. What goes wrong, and how does a pipeline prevent it?
Show answer
The scaler's means and standard deviations include the test rows, so information from the test set leaks into training. A pipeline fits the scaler only on the data passed to fit (the training data, or the training fold during cross-validation) and reuses those stored values to transform any other data.
Exercise
After fitting ridge, how do you read the mean the scaler learned for each feature?
Show answer
Use ridge.named_steps["standardscaler"].mean_. It holds one mean per column, computed from the training data.