Normalize (in Feature Engineering)
Normalization rescales numeric features so that no column dominates through its units alone. Income in the tens of thousands and age in the tens are the standard illustration: to anything that measures distance, a year of age is worth nothing beside a dollar of income.
- Minโmax โ \(x’ = \dfrac{x - x_{min}}{x_{max} - x_{min}}\), mapping to [0, 1]. Bounded output, and defined entirely by the two most extreme values.
- Standardization โ \(x’ = \dfrac{x - \mu}{\sigma}\), mean 0 and standard deviation 1. Unbounded, and the usual default.
- Robust scaling โ median and interquartile range instead of mean and standard deviation.
- Unit norm โ \(x’ = x / \|x\|\), scaling each row to length 1. A different operation from the other three, used where direction matters and magnitude does not.
The usual advice is that “models need scaled features.” Which models, and how much, turns out to vary a great deal.
Who it actually helps
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
n = 4000
age = rng.normal(45, 12, size=n)
income = rng.normal(52_000, 18_000, size=n)
y = (rng.random(n) < 1 / (1 + np.exp(-((age - 45) / 12 + (income - 52_000) / 18_000)))).astype(int)
X = np.column_stack([age, income])
"""Age and income carry equal signal by construction. Only their units differ."""
def cv(model, data):
from sklearn.model_selection import cross_val_score
return cross_val_score(model, data, y, cv=5).mean()
print(f"{'model':<22} {'raw units':>10} {'standardized':>13} {'min-max':>9}")
for name, make in (("k-nearest neighbors", lambda: KNeighborsClassifier(15)),
("logistic regression", lambda: LogisticRegression(max_iter=200)),
("random forest", lambda: RandomForestClassifier(n_estimators=100, random_state=0))):
print(f"{name:<22} {cv(make(), X):>10.4f} {cv(make_pipeline(StandardScaler(), make()), X):>13.4f}"
f" {cv(make_pipeline(MinMaxScaler(), make()), X):>9.4f}")
outlier = X.copy()
outlier[0, 1] = 5_000_000
print(f"\none mistyped income of 5,000,000 changes the min-max scaled values of every other row")
print(f" before: the 100th row's income scales to {MinMaxScaler().fit_transform(X)[100, 1]:.4f}")
print(f" after: the same row scales to {MinMaxScaler().fit_transform(outlier)[100, 1]:.4f}")
print(f" standardized, the same row moves from {StandardScaler().fit_transform(X)[100, 1]:+.4f}"
f" to {StandardScaler().fit_transform(outlier)[100, 1]:+.4f}")
# model raw units standardized min-max
# k-nearest neighbors 0.6215 0.7175 0.7170
# logistic regression 0.7282 0.7282 0.7288
# random forest 0.6947 0.6947 0.6945
#
# one mistyped income of 5,000,000 changes the min-max scaled values of every other row
# before: the 100th row's income scales to 0.7857
# after: the same row scales to 0.0184
# standardized, the same row moves from +1.7205 to +0.3730
Age and income carry equal signal here by construction; only their units differ.
k-nearest neighbors goes from 0.6215 to 0.7175 โ 9.6 percentage points, because a neighborhood defined in raw units is a neighborhood in income and nothing else. Anything built on distances behaves this way: clustering, kernel SVMs, dimensionality reduction by PCA.
Logistic regression is 0.7282 with both raw and standardized inputs in this run. A linear model can rescale its own coefficients, so a feature measured in thousands simply gets a coefficient a thousand times smaller. Scaling still matters for it in two ways โ the optimizer converges faster, and L1 or L2 regularization penalizes coefficients without knowing their units, so unscaled features are penalized unevenly. Both are real; neither is the accuracy difference the advice implies.
The random forest changes little: 0.6947 for raw and standardized inputs, and 0.6945 for minโmax. A strictly increasing feature transformation preserves candidate order-based threshold splits in exact arithmetic, but an implementation can still produce small numerical differences. This example supports limited scaling sensitivity for this forest, rather than an exact invariance guarantee for every tree implementation.
One bad row moves everything
The second half of the run mistypes one income as 5,000,000 and rescales. The hundredth row โ untouched, correct, unrelated โ moves from 0.7857 to 0.0184 under minโmax.
That follows from the definition: minโmax is determined entirely by the two extreme values, so a single outlier compresses everything else into a corner of the range. Standardization is affected too, 1.7205 to 0.3730, because one enormous value inflates the standard deviation โ but it degrades rather than collapses.
Median and interquartile range are less sensitive to the magnitude of extreme values than the mean and standard deviation, but they are not invariant to a few contaminated rows. Replacing the first value in [0,1,2,3,4] by 100 moves the median from 2 to 3. Robust scaling is worth comparing where contamination is plausible; investigate unusual values rather than assuming that a large value is necessarily an error.
Fit the scaler inside the fold
A scaler learns parameters โ a mean, a standard deviation, a minimum and maximum โ and those are learned from data. Fitting them on the whole dataset before splitting lets the training set see summary statistics of the test set, which is ordinary leakage and produces an optimistic score.
The effect is usually small for standardization on large samples and can be large for minโmax, where a single test-set extreme defines the range every training row is scaled against. Either way the fix costs nothing: put the scaler in a Pipeline so it is refitted inside each cross-validation fold, on the training part only.
Two consequences to keep in mind afterward. Test values outside the training range will fall outside [0, 1] under minโmax, which is correct behavior and surprises people. And the fitted parameters are part of the model โ a scaler and the estimator that was trained against it have to be deployed and versioned together, or every prediction is made on differently scaled inputs.
The broader version of this question โ how much any arbitrary choice of representation changes the answer โ is in sensitivity.
References
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
