Sub topic 11
Why penalties need scaled features
This chapter assumes you know how ridge and lasso add a penalty to a loss, and that you can use scikit-learn's fit and transform on a pipeline. It explains why a penalised model gives different answers when you change the units of a feature, and how to prevent that.
The penalty does not know your units
Ridge regression in scikit-learn minimises this quantity:
sum of squared errors + alpha * (w1^2 + w2^2 + ... + wp^2)The penalty adds up the squared coefficients. It does not look at the features that those coefficients multiply. A coefficient's size depends on the units of its feature.
Suppose a house's floor area is stored in square metres, and the model learns a coefficient of 3000 per square metre. If you store the area in square centimetres instead, each unit is 10,000 times smaller. The same prediction now needs a coefficient of 0.3. The model has not changed, but the penalty on that coefficient has shrunk from 9,000,000 to 0.09.
This means an unscaled penalised model treats features unequally for an arbitrary reason:
- A feature measured in small numbers (small variance) needs a large coefficient to matter, so the penalty hits it hard.
- A feature measured in large numbers (large variance) needs only a small coefficient, so the penalty barely touches it.
Ordinary least squares has no such problem. Rescaling a feature there just rescales its coefficient, and the predictions stay the same. The penalty breaks that invariance.
How strong the effect is
For one centred feature x fitted alone, the ridge coefficient is the least-squares coefficient multiplied by a shrinkage factor:
w_ridge = w_ols * s / (s + alpha), where s = sum of x_i^2If s is much larger than alpha, the factor is close to 1 and the coefficient is barely shrunk. If s is much smaller than alpha, the factor is close to 0 and the coefficient is crushed. Here s grows with the feature's variance, so the feature's scale decides how much it is shrunk.
The next example makes two features equally useful, then expresses the second one in units 100 times smaller.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 200
a = rng.normal(size=n)
b = rng.normal(size=n)
y = 2 * a + 2 * b + rng.normal(0, 0.5, size=n)
X = np.column_stack([a, b * 0.01]) # second column uses tiny units
raw = Ridge(alpha=100).fit(X, y)
print("raw coef: ", np.round(raw.coef_, 3))
X_std = StandardScaler().fit_transform(X)
scaled = Ridge(alpha=100).fit(X_std, y)
print("scaled coef:", np.round(scaled.coef_, 3))Both features carry the same signal. On the raw data, the second feature needs a coefficient near 200 to carry its share. At alpha=100 that is shrunk to a value near zero, so the model effectively ignores a useful feature. After standardisation, both coefficients come out similar, each shrunk by the same moderate factor. (This code is for illustration only. Fitting the scaler on all the data is the leak that the last section warns about.)
What scaling does
StandardScaler subtracts each column's mean and divides by its standard deviation. Every feature then has mean 0 and variance 1, so a coefficient measures the effect of a one-standard-deviation change. Coefficients become comparable, and one alpha means the same thing for every feature.
Centring has a second benefit. Scikit-learn does not penalise the intercept, and centred features make the intercept equal the mean of y. The penalty then acts only on the slopes.
Lasso is affected too
L1 regularisation has the same sensitivity, with a sharper consequence. Lasso sets some coefficients to exactly zero, and the features that survive depend on scale. An informative feature in small units can be zeroed out while a noisy feature in large units survives. The lasso example in this tutorial uses StandardScaler for this reason. Without it, the sparsity pattern would reflect units rather than usefulness.
Weight decay in neural networks is the same L2 penalty, so the same rule holds. Standardise network inputs, or the decay will favour some input columns for arbitrary reasons.
Choosing a scaler
| Scaler | What it does | Use when |
|---|---|---|
| `StandardScaler` | Mean 0, variance 1 | Default choice for dense numeric features |
| `StandardScaler(with_mean=False)` | Divides by the standard deviation only | Sparse matrices, where centring would make them dense |
| `MinMaxScaler` | Maps each feature to [0, 1] | You need bounded inputs. It is sensitive to outliers |
| `RobustScaler` | Uses median and interquartile range | Features have heavy outliers |
| `MaxAbsScaler` | Divides by the maximum absolute value | Sparse data where you want to keep zeros as zeros |
Tree-based models such as random forests do not need scaling, because they split on thresholds and no penalty on coefficients is involved.
Common errors
- Scaling before splitting. If you fit the scaler on the full dataset, the validation rows influence the mean and standard deviation used to transform the training rows. This is data leakage. The effect is usually small, but it makes the validation score slightly optimistic.
- Scaling outside cross-validation. Scaling the whole matrix once and then calling
cross_val_scoreleaks in every fold. Put the scaler inside a pipeline so that each fold fits it on its own training part only. - Forgetting to scale at prediction time. The model was trained on standardised inputs. New data must go through the same fitted scaler. A pipeline does this automatically.
- Scaling the target. Ridge and lasso do not need a scaled
y. Scaling it changes the meaning ofalphaand is not required. - Assuming one-hot columns must be left alone. Standardising 0/1 columns is acceptable and keeps the penalty even-handed. It makes coefficients harder to read in the original units. Many practitioners accept that trade-off for penalised models.
- Scaling before building polynomial features. Powers of a feature have wildly different ranges. In the degree-15 example, the highest power is enormous compared with the first. Place
StandardScalerafterPolynomialFeaturesso every generated column is scaled.
The leak-safe pattern
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
rng = np.random.default_rng(1)
X = rng.normal(size=(150, 5)) * [1, 10, 100, 0.1, 1000]
y = X[:, 0] + 0.1 * X[:, 1] + rng.normal(0, 0.5, size=150)
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_val_score(model, X, y, cv=5, scoring="r2")
print(np.round(scores, 3))On each of the five folds, the pipeline fits StandardScaler on the four training parts, transforms both the training and held-out parts with those statistics, and then fits Ridge. The held-out fold never contributes to the scaling statistics.
Exercise
A colleague fits Ridge(alpha=10) on raw features. One feature is a salary in dollars (values around 50,000) and another is the number of children (values 0 to 4). Both are equally predictive. Which feature does the penalty shrink more, and why? What change fixes it?
Show answer
The number of children is shrunk more. Its values are small, so it needs a large coefficient to have the same effect, and the penalty on a squared coefficient is large. The salary needs only a tiny coefficient, so the penalty barely affects it. Standardising both features (inside a pipeline, so the scaler is fitted on training data only) gives them equal variance, so the penalty treats them fairly.