Sub topic 3
How Outliers Distort Each Scaler
Assume you know NumPy arrays, means, standard deviations, and training/test splits. An outlier is a value far from most observations. Outliers can change the statistics that a scaler learns.
How outliers distort each scaler
Standardization uses:
(x - mean) / standard deviation
Min-max scaling uses:
(x - minimum) / (maximum - minimum)
Both formulas depend on the data range or distribution. Therefore, an extreme value affects both scalers.
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
x = np.array([[1.0], [2.0], [3.0], [100.0]])
print(MinMaxScaler().fit_transform(x).ravel())
print(StandardScaler().fit_transform(x).ravel())Min-max scaling maps 100 to 1 and squeezes the ordinary values near 0. Standardization is also affected because the outlier changes both the mean and standard deviation.
Undoing scaling with `inverse_transform`
A fitted scaler stores the statistics needed to return values to their original units.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[10.0], [20.0], [30.0]])
scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
X_original = scaler.inverse_transform(X_scaled)
print(X_original)Use the same fitted scaler for both operations. Do not fit a new scaler before calling inverse_transform.
Choosing a scaler
- Use
StandardScalerfor many linear, gradient-based, and distance-based models when features are roughly symmetric. - Use
MinMaxScalerwhen a fixed interval such as[0, 1]is required. - Use
RobustScalerwhen valid outliers strongly affect the mean or range. - Do not scale solely for tree-based models. Decision trees and random forests usually do not depend on feature magnitude.
Edge cases
A constant column has zero variance. StandardScaler avoids division by zero by using scale_ = 1, so its transformed values are zero. MinMaxScaler maps a constant feature to the lower end of its target range.
For sparse matrices, centering creates many stored zeros and can destroy sparsity. Use StandardScaler(with_mean=False). MaxAbsScaler is another sparse-friendly option. MinMaxScaler does not support sparse input directly.
With MinMaxScaler(clip=True), transformed values outside the training range are clipped to the chosen range. Without clipping, new values can fall below 0 or above 1.
Exercise
Which scaler is a reasonable first choice for a feature column containing valid extreme values?
Show answer
Try RobustScaler, then compare model validation results with StandardScaler.