Sub topic 9
Scaling features with StandardScaler
This chapter assumes you can fit a LinearRegression, split data with train_test_split, and read coef_ and intercept_. You should also know what a mean and a standard deviation are. By the end you will know when scaling changes a linear model and when it does not. You will also know how to scale without touching the test set.
Why scale at all
Features often live on very different numeric ranges. A house might have an area of 120 square metres and 3 bedrooms. The raw numbers are not comparable, and some algorithms behave differently depending on their size.
For ordinary least squares, scaling does not change the predictions. This surprises many learners. If you multiply a column by 10, the fitted coefficient shrinks by a factor of 10 and the prediction stays the same. Scaling only changes the units of the coefficients.
Scaling does matter in these cases:
- Regularized models. Ridge, Lasso and ElasticNet penalize the size of the coefficients. A feature measured in tiny units needs a large coefficient, so it is penalized more heavily. The penalty then depends on the units you chose.
- Interpreting coefficients. After scaling, coefficients are measured per standard deviation, so you can compare them across features.
- Iterative solvers. Some solvers converge faster and more reliably on scaled data. Lasso and ElasticNet use coordinate descent, and
SGDRegressoruses gradient steps. - Polynomial features. A squared term of a large number is huge. Scaling afterwards keeps the columns on a similar footing.
What StandardScaler computes
StandardScaler transforms each column independently:
z = (x - mean) / stdThe mean and standard deviation are computed from the data you pass to fit. After the transform, each column has a mean of 0 and a standard deviation of 1. The scaler stores the statistics in mean_ and scale_. scale_ is the standard deviation. It uses the population formula (divide by n), not the sample formula (divide by n − 1).
The scaler follows the estimator API you already know, with transform in place of predict:
fit(X)learns the mean and standard deviation of each column.transform(X)applies those stored values to any data.fit_transform(X)does both in one call and is meant for training data only.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[50.0, 1.0],
[80.0, 2.0],
[120.0, 3.0],
[150.0, 4.0]])
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
print("means:", scaler.mean_)
print("scales:", scaler.scale_)
print("scaled column means:", X_scaled.mean(axis=0).round(10))
print("scaled column stds:", X_scaled.std(axis=0))The scaled columns have mean 0 and standard deviation 1. The stored mean_ and scale_ are what you reuse later on new data.
Scaling does not change OLS predictions
You can check the claim above directly. The next script fits the same data with and without scaling and compares the predictions and the coefficients.
import numpy as np
from sklearn.linear_model import LinearRegression
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, 1000, size=200),
rng.uniform(0, 1, size=200),
])
y = 0.01 * X[:, 0] + 5.0 * X[:, 1] + 2.0 + rng.normal(0, 0.5, size=200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
raw = LinearRegression().fit(X_train, y_train)
scaler = StandardScaler().fit(X_train)
scaled = LinearRegression().fit(scaler.transform(X_train), y_train)
pred_raw = raw.predict(X_test)
pred_scaled = scaled.predict(scaler.transform(X_test))
print("same predictions:", np.allclose(pred_raw, pred_scaled))
print("raw coef: ", raw.coef_)
print("scaled coef:", scaled.coef_)The predictions match. The raw coefficients are about 0.01 and 5.0, which cannot be compared at a glance, since the first feature spans 0 to 1000 and the second spans 0 to 1. The scaled coefficients are each "change in y per one standard deviation of the feature". The first feature spans a wide range, so its effect per standard deviation turns out to be larger. The raw numbers hid this.
The scaled intercept also changes meaning. It becomes the prediction when every feature is at its training mean.
Fit on training data only
The most common mistake with scalers is data leakage. Leakage means information from the test set influences the model during training. If you call fit_transform on the full dataset before splitting, the mean and standard deviation include test rows. The test score then looks slightly better than it should.
The correct order is:
- Split the data.
- Fit the scaler on the training portion.
- Transform the training portion and the test portion with that same fitted scaler.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(1)
X = rng.normal(loc=50, scale=10, size=(100, 3))
X_train, X_test = train_test_split(X, test_size=0.25, random_state=1)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train) # learns from train only
X_test_s = scaler.transform(X_test) # reuses the train statistics
print("train means:", X_train_s.mean(axis=0).round(6))
print("test means: ", X_test_s.mean(axis=0).round(3))The training means are exactly 0. The test means are close to 0 but not equal. That is expected and correct. The test set is meant to behave like unseen future data, and future data will not have exactly the training mean.
Never call fit or fit_transform on the test set. Doing so computes new statistics from test rows, so the same raw value would map to different scaled values in training and testing.
Handling this by hand works, but it is easy to get wrong inside cross-validation, where each fold needs its own scaler. The next chapter wraps the scaler and the model in a Pipeline, which does this correctly for you.
Scaling and regularization
The effect on Ridge is easy to see. Ridge adds a penalty proportional to the sum of squared coefficients. If one feature is measured in grams and another in kilograms, the penalty treats their coefficients equally, even though the gram coefficient is naturally a thousand times smaller. Unscaled Ridge shrinks the large-unit feature barely at all and shrinks the small-unit feature much more.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(2)
n = 300
a = rng.normal(0, 1, n) # unit-scale feature
b = rng.normal(0, 1, n) * 1000 # same signal, large units
y = 2.0 * a + 0.002 * b + rng.normal(0, 0.1, n)
X = np.column_stack([a, b])
plain = Ridge(alpha=100.0).fit(X, y)
scaled = make_pipeline(StandardScaler(), Ridge(alpha=100.0)).fit(X, y)
print("unscaled coef:", plain.coef_)
print("scaled coef: ", scaled[-1].coef_)Both features contribute equally to y when measured in standard deviations: 2.0 * a and 0.002 * b each have a standard deviation of about 2. In the unscaled fit, the penalty hits feature a hard because its coefficient has to be large (about 2). Feature b needs only a tiny coefficient, so the penalty barely touches it. After scaling, both features are penalized on equal terms, and their coefficients end up similar. The same logic applies to Lasso and ElasticNet.
Scaling the target y is usually not needed for these models. It is a separate decision and is not covered here.
Edge cases
- Constant columns. If a column has zero variance, the standard deviation is 0.
StandardScalerhandles this by setting the scale to 1 for that column, so the column becomes all zeros and no division by zero occurs. - Outliers. The mean and standard deviation are sensitive to extreme values. A few outliers inflate the standard deviation and squeeze the remaining points into a narrow band.
RobustScaleruses the median and interquartile range and is a common alternative. - Missing values.
StandardScalerignoresNaNwhen computing statistics and leaves them in place. A regressor likeLinearRegressionwill still fail on them, so impute first. - Sparse data. Subtracting the mean turns a sparse matrix into a dense one. Use
StandardScaler(with_mean=False)to scale only by the standard deviation and keep the sparsity. - Binary and one-hot columns. Scaling a 0/1 column is allowed but makes its coefficient harder to read, since "one standard deviation" of a dummy variable is not a natural unit. Many practitioners scale only the numeric columns. You will see this with
ColumnTransformerlater in the tutorial. - DataFrames.
transformreturns a NumPy array by default and loses the column names. You can callscaler.set_output(transform="pandas")to keep a DataFrame.
When to scale: a quick guide
| Model | Scaling needed? | Reason |
|---|---|---|
| `LinearRegression` | No, for predictions | OLS predictions are unchanged by rescaling |
| `LinearRegression` | Yes, to compare coefficients | Puts coefficients in standard deviation units |
| `Ridge`, `Lasso`, `ElasticNet` | Yes | The penalty depends on feature units |
| `PolynomialFeatures` then a regularized model | Yes | Powers create very different magnitudes |
| Tree-based models | No | Splits depend only on ordering |
Putting it together
The diagram shows the data flow. The scaler learns its statistics from the training split only, and those same statistics are applied to both splits.
Exercise
You standardize a training set and fit LinearRegression. A colleague says the model's test-set R-squared should now be higher than without scaling. Is that right? What does scaling change in this case?
Show answer
No. For ordinary least squares, rescaling the features does not change the fitted predictions, so the test R-squared is the same (up to floating-point error). Scaling changes the coefficients: each becomes the change in the target per one standard deviation of that feature, and the intercept becomes the prediction at the mean of the training features. This makes coefficients comparable, but it does not improve accuracy.
Exercise
A script calls scaler.fittransform(X) on the whole dataset, then runs traintest_split, then fits Ridge. Name the problem and give the corrected order of steps.
Show answer
This leaks test information: the mean and standard deviation include test rows. The correct order is to run traintestsplit first, call scaler.fit_transform on the training features only, call scaler.transform on the test features, then fit Ridge on the scaled training data and score on the scaled test data.
Exercise
Why does an unscaled Ridge model treat a feature measured in grams differently from the same feature measured in kilograms, while an unscaled LinearRegression does not?
Show answer
Ridge penalizes the sum of squared coefficients, and a coefficient's size depends on the feature's units: the gram version needs a coefficient 1000 times smaller, so it is penalized far less than the kilogram version. OLS has no penalty, so a change in units only rescales the coefficient and leaves the predictions unchanged.