Sub topic 9
Scaling features with StandardScaler
This chapter assumes you can fit a LinearRegression, split data with train_test_split, and read coef_. It covers why feature scale matters, how StandardScaler works, and the most common mistake when using it.
Why scale at all
Plain least squares does not need scaled features. Its predictions are the same whether a feature is measured in meters or millimeters. Only the coefficient changes: a feature in millimeters gets a coefficient 1000 times smaller.
Scaling matters in two situations:
- Comparing coefficients. If features have different units, the sizes of
coef_values say little about importance. - Regularized models. Ridge, Lasso and ElasticNet penalize coefficient size. A feature with a small numeric range needs a large coefficient, so it is penalized more. Without scaling, the penalty treats features unfairly.
What StandardScaler does
StandardScaler is a transformer that rescales each column to mean 0 and standard deviation 1. For each value x in a column:
z = (x - mean) / stdIt learns mean and std during fit and applies them during transform. The learned values are stored in mean_ and scale_.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 100.0],
[2.0, 200.0],
[3.0, 300.0]])
scaler = StandardScaler()
Z = scaler.fit_transform(X)
print("means:", scaler.mean_)
print("stds:", scaler.scale_)
print("scaled means:", Z.mean(axis=0))
print("scaled stds:", Z.std(axis=0))Both columns end up with mean 0 and standard deviation 1, even though their original ranges differ by a factor of 100.
Fit on training data only
The scaler learns statistics from the data you give it. If you fit it on the full dataset before splitting, information from the test rows leaks into training. This is called data leakage, and it makes test scores look better than they should.
The correct order is:
- Split the data.
- Call
fit(orfit_transform) on the training set only. - Call
transformon the test set, using the training mean and standard deviation.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = np.column_stack([
rng.uniform(0, 1, 200),
rng.uniform(0, 1000, 200),
])
y = 5.0 * X[:, 0] + 0.01 * X[:, 1] + rng.normal(0, 0.5, 200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)
model = Ridge(alpha=1.0).fit(X_train_s, y_train)
print("coef:", model.coef_)
print("test R2:", model.score(X_test_s, y_test))After scaling, the coefficients are in the same units: change in y per one standard deviation of the feature. That makes them comparable.
flowchart TD
A[Full dataset] --> B[train_test_split]
B --> C[Training set]
B --> D[Test set]
C --> E[scaler.fit learns mean and std]
E --> F[scaler.transform on training set]
E --> G[scaler.transform on test set]
D --> GThe diagram above is the intended flow, but note the required format below for the rendered version.
Common errors
- Fitting on all the data. Leaks test statistics into training.
- Fitting a second scaler on the test set. The test data then uses different statistics than the model was trained on, so the scaled values mean different things.
- Scaling the target by accident.
StandardScalerhere is for features. If you scaley, you must convert predictions back. - Scaling one-hot columns. This works but makes the coefficients harder to read. A later chapter shows how to scale only the numeric columns.
Exercise
You call StandardScaler().fit_transform(X) on the full dataset, then split into train and test sets and fit a Ridge model. Why is the test score unreliable, and how do you fix it?
Show answer
The scaler's mean and standard deviation were computed using the test rows, so information from the test set leaked into training. Split first, fit the scaler on the training set only, and use transform on the test set.