Sub topic 5
Scaling Numeric Features
This chapter assumes you know basic pandas, the scikit-learn fit and transform workflow, and what mean and variance are. It also assumes you know why a model is fitted on training data only.
Why scale
Numeric columns often live on very different ranges. age might run from 18 to 90, while income runs from 20,000 to 500,000. Some models treat the raw numbers as distances or as step sizes, so the column with the biggest range dominates.
Scaling changes the range of a column without changing the order of its values.
| Model family | Needs scaling? | Reason |
|---|---|---|
| k-nearest neighbors, SVM, k-means | Yes | They compute distances. |
| Logistic and linear regression with regularization | Yes | The penalty depends on coefficient size, which depends on feature units. |
| Neural networks, gradient descent | Usually | Scaled inputs make optimization faster and more stable. |
| PCA | Yes | It looks for directions of largest variance. |
| Decision trees, random forests, gradient boosting | No | Splits depend only on the order of values. |
Common scalers
StandardScalersubtracts the mean and divides by the standard deviation, so each column has mean 0 and variance 1.MinMaxScalermaps the training minimum to 0 and the training maximum to 1.RobustScalersubtracts the median and divides by the interquartile range (IQR). Outliers affect it much less.
import numpy as np
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler
X_train = np.array([[25.0, 40000.0], [32.0, 52000.0], [47.0, 61000.0], [51.0, 900000.0]])
X_test = np.array([[30.0, 45000.0]])
for scaler in (StandardScaler(), MinMaxScaler(), RobustScaler()):
scaler.fit(X_train)
print(type(scaler).__name__)
print(scaler.transform(X_test))The extreme income of 900,000 stretches the minimum and maximum and inflates the standard deviation. RobustScaler keeps the typical rows spread out, while MinMaxScaler squeezes them into a narrow band near 0.
Fit on training data only
A scaler learns statistics (mean, standard deviation, minimum, maximum) from the data it sees in fit. If you fit it on the full dataset, information from the test rows leaks into training. Fit on the training set, then apply the same fitted scaler to validation, test and production data.
The safest way is to put the scaler inside a Pipeline, as covered later in this tutorial. Cross-validation then refits it on each training fold.
Common errors
- Scaling the target by accident. Scale features, not the label. For regression targets, use
TransformedTargetRegressorif you need a scaled target. - Scaling one-hot columns. It does no harm for most models, but it makes coefficients harder to read. Apply scalers to numeric columns only, using
ColumnTransformer. - Using
MinMaxScalerwith outliers. One extreme value compresses everything else. PreferRobustScaler, or reduce skew first with a log transform. - Expecting scaling to fix skew. Scaling shifts and stretches a column but keeps its shape. A skewed column stays skewed.
- Test values outside the training range.
MinMaxScalerwill output values below 0 or above 1 for them. This is expected, not a bug.
Exercise
You fit a StandardScaler on all rows, then split into train and test sets, and your random forest score barely changes. Is the leakage harmless, and should you still change the code?
Show answer
The score barely changes partly because a random forest ignores feature scale, so it is not a good detector of the problem. The leakage is still real: the test rows influenced the mean and standard deviation. Fit the scaler on the training split only, ideally inside a Pipeline, so the code stays correct if you switch to a scale-sensitive model such as logistic regression or an SVM.
Exercise
A column has most values between 1 and 100, plus a few values near 1,000,000. Which of StandardScaler, MinMaxScaler and RobustScaler is the best first choice, and why?
Show answer
RobustScaler. It uses the median and IQR, which the few extreme values barely move. StandardScaler's mean and standard deviation, and MinMaxScaler's maximum, are dominated by the outliers, so the typical values end up squeezed into a tiny range.