Sub topic 5
Scaling Numeric Features
This chapter assumes you know basic pandas and scikit-learn's fit/transform workflow. It also assumes you understand mean, variance, and the idea of a training and test split. You have already seen why every fitted step must learn only from training data. Here we apply that rule to scaling.
Why scale at all
Numeric columns often live on very different ranges. age might span 18 to 90, while income spans 20,000 to 500,000. Some models treat each unit of a feature as equally meaningful, so the large-range column dominates. Scaling puts columns on comparable ranges so the model sees them fairly.
Which models care depends on how they use the numbers:
| Model family | Sensitive to scale? | Reason |
|---|---|---|
| k-nearest neighbors, k-means, SVM with RBF kernel | Yes | They compute distances, and a large-range column dominates the distance. |
| Linear and logistic regression with regularization | Yes | The penalty on coefficients depends on feature size. |
| Neural networks | Yes | Gradient descent converges slowly or unstably on mismatched scales. |
| PCA | Yes | It finds directions of maximum variance, which favors large-range columns. |
| Decision trees, random forests, gradient boosting | No | Splits depend only on the ordering of values. |
Plain, unregularized linear regression gives the same predictions with or without scaling. Scaling still helps its numerical stability and makes coefficients comparable. Tree models do not need scaling, so leaving it out keeps their pipelines simpler.
The main scalers
Standardization
StandardScaler subtracts the training mean and divides by the training standard deviation:
z = (x − mean) / std
The result has mean 0 and standard deviation 1 on the training data. It is the default choice for linear models, SVMs, neural networks, and PCA. It does not bound values to a fixed range, and outliers still pull the mean and standard deviation.
Min-max scaling
MinMaxScaler maps the training minimum to 0 and the training maximum to 1:
x' = (x − min) / (max − min)
Use it when you need a bounded range, for example with some neural network inputs or image pixel values. It is very sensitive to outliers. One extreme value squeezes all the others into a narrow band near 0.
Robust scaling
RobustScaler subtracts the median and divides by the interquartile range (IQR, the distance between the 25th and 75th percentiles). The median and IQR barely move when a few extreme values are present, so it is a good choice for columns with outliers.
Other scalers
MaxAbsScalerdivides by the largest absolute value. It keeps zeros as zeros, so it suits sparse data.Normalizeris different in kind. It rescales each row to unit length, rather than each column. Use it for row-wise comparisons such as cosine similarity on text vectors, not as a replacement for column scaling.
A worked example
The following code is complete and runs as shown. It fits each scaler on a small training set containing one outlier, then applies it to new rows.
import numpy as np
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler
X_train = np.array([[25.0], [32.0], [41.0], [38.0], [29.0], [400.0]])
X_test = np.array([[30.0], [45.0]])
scalers = {
"standard": StandardScaler(),
"minmax": MinMaxScaler(),
"robust": RobustScaler(),
}
for name, scaler in scalers.items():
scaler.fit(X_train)
train_scaled = scaler.transform(X_train).ravel()
test_scaled = scaler.transform(X_test).ravel()
print(name)
print(" train:", np.round(train_scaled, 2))
print(" test: ", np.round(test_scaled, 2))The value 400 is an outlier. With min-max scaling, the five ordinary values land between about 0 and 0.04, so they are nearly indistinguishable. With robust scaling, the ordinary values keep a useful spread and only 400 becomes large. Standardization falls in between, because the outlier inflates both the mean and the standard deviation.
Fit on training data only
A scaler learns statistics: the mean and standard deviation, or the min and max. If you compute them on the full dataset, information from the test set leaks into training. The scores then look better than the model's real performance.
The correct pattern is to call fit on the training set and transform on every other set, using the training statistics. The common mistake is calling fit_transform on the test set, which silently refits the scaler.
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0], [2.0], [3.0]])
X_test = np.array([[10.0]])
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train) # learns mean and std from train
X_test_s = scaler.transform(X_test) # reuses them, does not refit
print(scaler.mean_, scaler.scale_)
print(X_test_s)A test value far outside the training range produces a large scaled value. That is correct behavior and tells you the new data differs from what the model saw.
The safest approach is to put the scaler inside a Pipeline, as the pipelines chapter shows. Cross-validation then refits it on each training fold automatically.
Edge cases and common errors
- Constant columns. If a column has zero variance,
StandardScalersets its scale to 1 instead of dividing by zero, so the column becomes all zeros. It is still useless to the model, so consider dropping it. - Missing values. The scalers ignore
NaNwhen computing statistics and keepNaNin the output. Most models then fail. Impute first, or place the imputer before the scaler in the pipeline, as the earlier chapter on missing values describes. - Sparse matrices.
StandardScalerwith centering would turn a sparse matrix into a dense one, using much more memory. Scikit-learn raises an error for this case. UseStandardScaler(with_mean=False)orMaxAbsScalerinstead. - One-hot columns. Scaling 0/1 indicator columns is usually unnecessary. Apply scalers only to the numeric columns, which is what
ColumnTransformeris for. - Target scaling. Scaling
yfor regression is sometimes useful, but it needsTransformedTargetRegressorso that predictions are converted back to the original units. - Interpreting coefficients. After standardization, a linear model coefficient is the change in the target per one standard deviation of the feature. That makes coefficients comparable across features, but it is no longer per original unit.
- Drift. In production, new data may shift away from the training range. Min-max scaled values can then fall outside 0 to 1. Check that downstream code does not assume the bounds hold.
Choosing a scaler
- If the model is a tree ensemble, skip scaling.
- If the model is distance-based, linear, or a neural network, start with
StandardScaler. - If the column has heavy outliers you want to keep, use
RobustScaler. - If you need a fixed bounded range, use
MinMaxScaler, after checking for outliers. - If the data is sparse, use
MaxAbsScalerorStandardScaler(with_mean=False).
Scaling treats a column's shape as given. If a column is strongly right-skewed, scaling will not fix the skew. Only a transform such as the log does that.
Exercise
You build a k-nearest-neighbors classifier. A colleague calls scaler.fittransform(Xtest) before predicting, "so the test data is also normalized". Why is this wrong, and what should be done instead? Also, would the same step matter for a random forest?
Show answer
Calling fit_transform on the test set refits the scaler on test data, so the test rows are scaled with different statistics than the training rows. The model then sees inputs on a different scale from the one it learned, and the evaluation no longer reflects how it would work on new data. The scaler should be fitted once on the training set and only transform should be called on the test set, ideally inside a Pipeline. A random forest splits on value ordering, so scaling does not change its predictions and the step is unnecessary.
Exercise
A column holds salaries where one entry is 50 times larger than the rest. You must feed it to logistic regression. Which scaler would you choose over MinMaxScaler, and why?
Show answer
RobustScaler. It centers on the median and divides by the interquartile range, so the single extreme value hardly changes the scale applied to the other entries. MinMaxScaler would use the extreme value as the maximum and squeeze the ordinary salaries into a very narrow range near 0.