Sub topic 8
How outliers distort each scaler
This chapter assumes you can use StandardScaler and MinMaxScaler with fit and transform, and that you know why scalers are fitted on training data only. It also assumes you know mean, standard deviation, quartiles and NumPy basics. Here you will see how one extreme value changes what each scaler learns, and what to do about it.
Why a single value matters
A scaler learns a few numbers from the training data. It then applies one formula to every row using those numbers. If an outlier (a value far from the rest of the column) changes the learned numbers, it changes the scaled value of every row, not only its own.
| Scaler | Learned statistics | Formula | Sensitivity to one outlier |
|---|---|---|---|
| `MinMaxScaler` | `data_min_`, `data_max_` | (x − min) / (max − min) | The outlier becomes the min or max, so it sets the whole scale. |
| `StandardScaler` | `mean_`, `scale_` (standard deviation) | (x − mean) / std | The outlier shifts the mean and inflates the standard deviation. |
| `RobustScaler` | `center_` (median), `scale_` (IQR) | (x − median) / IQR | Barely affected, because the median and quartiles ignore extreme values. |
IQR is the interquartile range, the 75th percentile minus the 25th percentile.
Min-max scaling: the outlier sets the scale
The min-max formula divides by max - min. An outlier is by definition the max or the min, so it controls the denominator completely. Take nine ordinary values, 1 through 9, and one outlier, 100. The range is 99, so the ordinary values are divided by 99.
- The value 1 maps to 0.
- The value 9 maps to 8 / 99, about 0.081.
- The value 100 maps to 1.
All nine ordinary values land in the bottom 8% of the interval. Without the outlier, they would cover the whole interval from 0 to 1. A model that sees these inputs can barely tell the ordinary values apart. A distance-based model such as k-nearest neighbors would see differences of about 0.01 between neighbors in this column. Another feature that was not distorted would dominate the distance, which is the problem scaling was meant to solve.
The result is still technically in [0, 1], so nothing looks wrong. The failure is silent.
Standardization: the outlier shifts and stretches
The mean and standard deviation both depend on every value, so the outlier affects both. For the same ten values:
- The mean is 14.5. The ordinary values average 5, so the mean is far above all of them but one.
- The standard deviation is about 28.6. Without the outlier it is about 2.58.
Every ordinary value is therefore negative after scaling, and they are crowded into a narrow band. The result does not have the "centered, unit-scale" look you expect from standardization, even though the column's overall mean is exactly 0 and its standard deviation is exactly 1. The statistics describe the column as a whole, and the whole column is dominated by one point.
A useful fact for small samples: with the population standard deviation (ddof=0, which StandardScaler uses), no z-score can exceed sqrt(n - 1) in absolute value. With n = 10 the cap is 3. So the common rule of thumb "flag anything with |z| > 3" cannot fire on a sample this small. The outlier gets a z-score of about 2.99 and looks only mildly unusual. Standardization does not make outliers easy to spot in small data.
Comparing the scalers on the same data
This script fits all three scalers on the same column and reports how much room the nine ordinary values get.
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 100], dtype=float).reshape(-1, 1)
scalers = {
"MinMaxScaler": MinMaxScaler(),
"StandardScaler": StandardScaler(),
"RobustScaler": RobustScaler(),
}
for name, scaler in scalers.items():
out = scaler.fit_transform(x).ravel()
typical = out[:9] # the nine ordinary values
width = typical.max() - typical.min()
print(
f"{name:15s} typical range: [{typical.min():.3f}, {typical.max():.3f}] "
f"width={width:.3f} outlier={out[9]:.3f}"
)The output is approximately:
MinMaxScaler typical range: [0.000, 0.081] width=0.081 outlier=1.000
StandardScaler typical range: [-0.472, -0.192] width=0.280 outlier=2.989
RobustScaler typical range: [-1.000, 0.778] width=1.778 outlier=21.000Read the width column. It measures how much of the output scale the ordinary values keep.
MinMaxScalerleaves them 0.081 of the scale.StandardScalerleaves them 0.280.RobustScalerleaves them 1.778.
For comparison, if you remove the outlier and rescale 1 through 9, min-max gives a width of 1 and standardization gives about 3.1.
RobustScaler does not make the outlier disappear. The outlier is still at 21.0, far from everything else. What changes is that the ordinary values keep their spread, because the median (5.5) and the IQR (4.5) are computed from the middle of the data. The outlier can only move them slightly, however large it is.
Outliers that appear after fitting
The previous sections covered outliers present in the training data. The opposite case is common in production: the scaler is fitted on clean data, and a new row contains an extreme value. The scaler applies the stored statistics unchanged, so nothing is distorted for the other rows. The extreme row itself maps far outside the usual range.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
train = np.array([[1.0], [2.0], [3.0], [4.0], [5.0]])
test = np.array([[0.0], [3.0], [50.0]])
plain = MinMaxScaler().fit(train)
print(plain.transform(test).ravel())
clipped = MinMaxScaler(clip=True).fit(train)
print(clipped.transform(test).ravel())The first line prints [-0.25 0.5 12.25]. The training range is 1 to 5, so 0 maps below 0 and 50 maps to 12.25. This breaks the promise that min-max output lies in [0, 1]. Models that assume bounded inputs, such as a neural network with a sigmoid input layer, can behave badly on these values.
The second line prints [0. 0.5 1.]. With clip=True, scikit-learn clamps transformed values to feature_range. This protects the model from out-of-range inputs. It also hides the fact that the input was far outside anything seen in training, so log or monitor such rows if the information matters.
StandardScaler has no clip option. A test-time outlier maps to a large z-score, and you can clip it yourself with np.clip after scaling if your model needs that.
What to do about outliers
Pick the response based on what the outliers are.
- They are errors. A sensor reading of 9999 or an age of −1 should be fixed or removed before scaling, ideally in a cleaning step at the start of the pipeline.
- They are real but rare, and the model should not be dominated by them. Use
RobustScaler, or clip (winsorize) the column to chosen percentiles before scaling. Clip bounds must be learned on training data only, like any other statistic. - The column is heavily skewed, such as incomes or counts. A log transform (
np.log1porFunctionTransformer(np.log1p)) often fixes the problem at its source. Scaling afterward then behaves well. - The outliers carry the signal. In fraud detection, for example, the extreme values may be exactly what you want to predict. Do not clip them away. Standardization is usually preferable to min-max here, because it keeps the outlier visible instead of compressing everything else.
Whichever response you choose, put it inside a Pipeline so it is refitted on each training fold. Choosing clip bounds or checking for outliers on the full dataset before splitting leaks information, just as fitting a scaler on the full dataset does.
Gotchas
- Few outliers, big effect. A single bad value in a column of thousands rows can still change min-max output noticeably. Standardization is more tolerant of one outlier in a large sample, because the mean and standard deviation average over many rows, but a heavy tail still inflates the standard deviation.
- Tree-based models. Random forests and gradient-boosted trees split on thresholds and do not depend on scale, so scaling does not change their predictions. Outliers can still matter through other routes, for example in the loss function.
- Standardized output is not bounded. Do not assume z-scores stay within −3 and 3. The bound
sqrt(n - 1)only limits small samples. In a large sample, an outlier of 1,000 standard deviations is possible. - Checking after scaling is too late for the cause. Plot or summarize the raw column first, for example with
describe()and a box plot, then choose the scaler.
Exercise
A training column has values 10, 12, 11, 13, 12, 11, 10, 12, 13 and one data-entry error, 10000. You fit MinMaxScaler on it. Roughly where do the nine ordinary values end up in the output, and what is the simplest scikit-learn change that keeps them spread out?
Show answer
The range is about 10000 − 10 = 9990, so the ordinary values (10 to 13) map to between 0 and 3/9990, about 0.0003. They are almost indistinguishable from each other. Because the outlier is a data-entry error, the best fix is to correct or remove it before scaling. If it has to stay, use RobustScaler, which uses the median and IQR and keeps the ordinary values spread out, or clip the column to training percentiles before scaling.
Exercise
You fit StandardScaler on a column with 50 values and it learns mean = 20 and scale = 4. A new row arrives with value 100. What z-score does transform give it, and does fitting a scaler differently change what transform does with this new row?
Show answer
The z-score is (100 − 20) / 4 = 20. transform applies the stored statistics and does not refit, so the new row does not change mean or scale. The extreme row simply gets a large z-score. A different scaler changes the number: MinMaxScaler would map it above 1 unless clip=True, and RobustScaler would use the training median and IQR. None of them refit during transform.
Exercise
In the comparison script, the outlier gets a StandardScaler z-score of about 2.99 even though it is 100 against ordinary values of 1 to 9. Why can this not exceed 3 with 10 samples, and what does that imply for flagging outliers with |z| > 3 on small samples?
Show answer
StandardScaler uses the population standard deviation (ddof=0), and with that definition no z-score can exceed sqrt(n − 1) in absolute value. For n = 10 the cap is 3. So a rule that flags |z| > 3 can never fire on 10 samples, even for an extreme point. For small samples, use a robust method such as median and IQR, or look at the data directly.