Sub topic 10
Choosing between StandardScaler, MinMaxScaler and alternatives
This chapter assumes you can fit a scikit-learn estimator and know the earlier material on fit/transform, data leakage and outlier effects. Here the question is which scaler to use for a given model and dataset, and when to use none.
Start with the model, then look at the data
Choose in two steps. First ask whether the model needs scaling at all. Then pick the scaler that matches the shape of your features.
Scaling matters when the model's math mixes features together through distances, dot products, gradients or penalties:
- Distance-based models such as k-nearest neighbors, k-means and RBF-kernel SVMs. A feature with a large range dominates the distance.
- Gradient-trained models such as logistic regression, linear regression with gradient descent, and neural networks. Similar feature ranges give better-conditioned optimization and faster convergence.
- Regularized models such as Ridge, Lasso and ElasticNet. The penalty treats all coefficients alike, so unscaled features are penalized unevenly.
- PCA, which finds directions of maximum variance. Unscaled features with large units take over the first components.
Scaling is mostly unnecessary for decision trees, random forests and gradient-boosted trees. They split on thresholds, and a monotonic rescaling of one feature does not change which splits are possible. Scaling them is harmless, but it costs time and adds a step that can go wrong.
StandardScaler as the default
StandardScaler computes (x - mean) / std per column. It is the usual first choice because:
- Many models assume or work best with centered features. Linear models, PCA and neural networks all benefit from a mean near zero.
- The result is unbounded, so a test value outside the training range still maps to a sensible number.
- Regularization penalties then act on comparable units, meaning "standard deviations".
Its weakness is that the mean and standard deviation are both sensitive to outliers. A single extreme value inflates std, which shrinks the ordinary values toward each other, and it shifts the mean away from where most of the data sits.
Choose StandardScaler when features are roughly symmetric, outliers are mild, and you have no need for a fixed output range.
MinMaxScaler when you need a bounded range
MinMaxScaler computes (x - min) / (max - min) and maps training data to [0, 1] by default. Prefer it when:
- The downstream component expects bounded input, such as pixel intensities or inputs to a sigmoid or bounded activation.
- The feature has hard natural limits and no outliers, such as a percentage or a bounded sensor reading.
- You want to preserve the shape of the original distribution exactly, because the transform is a pure linear squeeze.
Its weaknesses:
- It depends on only two numbers, the training minimum and maximum, so one outlier compresses everything else.
- It does not center on zero, so it is not always ideal for models that prefer centered inputs.
- New data outside the training range falls outside
[0, 1]. The scaler does not clip unless you setclip=True.
The alternatives
Four other tools cover cases where the two main scalers struggle.
RobustScaler
RobustScaler computes (x - median) / IQR, where IQR is the interquartile range, the 75th percentile minus the 25th. Median and IQR are barely affected by a few extreme points, so ordinary values keep a sensible spread. Use it when outliers are real data that you do not want to drop but also do not want to control the scale.
It does not bound the output. Outliers still appear as large values, just without distorting everyone else.
MaxAbsScaler
MaxAbsScaler divides each column by its maximum absolute value, giving a range of [-1, 1]. It does not shift the data, so zeros stay zero. That makes it the safe choice for sparse matrices, where centering would turn the zeros into non-zeros and destroy the sparsity. It is as sensitive to outliers as MinMaxScaler.
PowerTransformer and QuantileTransformer
These two change the shape of the distribution, not only its location and scale.
PowerTransformerapplies a Yeo-Johnson (any real values) or Box-Cox (strictly positive values) transform and then standardizes by default. It reduces skew, which helps with features like income or counts.QuantileTransformermaps values through their empirical ranks to a uniform or normal distribution. It squashes outliers almost completely, but it is nonlinear. Distances between points are distorted, and it needs a reasonably large sample to estimate quantiles well.
Use these when a feature is heavily skewed and a linear rescaling will not fix it.
Normalizer is a different operation
Normalizer scales each row to unit norm, not each column. It is used for text vectors and similarity-based methods and is not a substitute for column scaling. If you meant to put features on comparable scales, you do not want it.
Comparison table
| Scaler | Formula | Output range | Outlier sensitivity | Typical use |
|---|---|---|---|---|
| `StandardScaler` | `(x - mean) / std` | Unbounded | High | Default for linear models, PCA, neural networks |
| `MinMaxScaler` | `(x - min) / (max - min)` | `[0, 1]` on training data | Very high | Bounded inputs, no outliers |
| `RobustScaler` | `(x - median) / IQR` | Unbounded | Low | Data with outliers you want to keep |
| `MaxAbsScaler` | `x / max(abs(x))` | `[-1, 1]` | Very high | Sparse data |
| `PowerTransformer` | Yeo-Johnson or Box-Cox, then standardize | Roughly bell-shaped | Moderate | Skewed features |
| `QuantileTransformer` | Rank-based mapping | Uniform or normal | Very low | Heavy skew and outliers, large samples |
Seeing the difference on skewed data
The same feature with one outlier gives quite different results depending on the scaler.
import numpy as np
from sklearn.preprocessing import (
StandardScaler, MinMaxScaler, RobustScaler, MaxAbsScaler
)
x = np.array([[1.0], [2.0], [3.0], [100.0]]) # 100 is an outlier
scalers = {
"standard": StandardScaler(),
"minmax": MinMaxScaler(),
"robust": RobustScaler(),
"maxabs": MaxAbsScaler(),
}
for name, scaler in scalers.items():
out = scaler.fit_transform(x).ravel()
print(f"{name:9s}", np.round(out, 3))Look at the first three values in each row. MinMaxScaler and MaxAbsScaler put them within about 0.02 of each other near zero, so the model sees almost no difference between 1, 2 and 3. StandardScaler also bunches them together, and its mean is pulled toward the outlier. RobustScaler keeps them spread over a small but usable range (roughly -0.06 to 0.02), while the outlier stays large at about 3.8. Whether that is what you want depends on whether the outlier is signal or noise.
Do not decide by theory alone: compare in a Pipeline
The right scaler also depends on the model and the data, so treat the choice as a hyperparameter. A pipeline step can be swapped inside GridSearchCV. Because the scaler lives in the pipeline, it is refit on each training fold and there is no leakage.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
X, y = load_breast_cancer(return_X_y=True)
pipe = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
param_grid = {
"scaler": [StandardScaler(), MinMaxScaler(), RobustScaler(), "passthrough"],
}
search = GridSearchCV(pipe, param_grid, cv=5)
search.fit(X, y)
for params, score in zip(search.cv_results_["params"],
search.cv_results_["mean_test_score"]):
print(type(params["scaler"]).__name__
if params["scaler"] != "passthrough" else "passthrough",
round(score, 4))The "passthrough" entry means "no scaling", which gives you a baseline. If the scores are within noise of each other, pick the simplest option and move on. Differences of a fraction of a percent on a single dataset rarely justify a more exotic scaler.
Scores for tree-based models in the same grid would be nearly identical across scalers. That is a useful check that you understood which model families need scaling.
Mixed features need mixed scalers
Real datasets rarely suit one scaler. A ColumnTransformer lets each group of columns get the treatment that fits it. The column names below are placeholders for your own.
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler
preprocess = ColumnTransformer(
[
("symmetric", StandardScaler(), ["height", "temperature"]),
("skewed", RobustScaler(), ["income"]),
("bounded", MinMaxScaler(), ["percent_complete"]),
],
remainder="passthrough",
)Keep it simple. Using three scalers in one table is justified when the columns really differ in shape. Using three because it feels thorough adds complexity without evidence.
Practical decision criteria
Work through these in order.
- Model family. Tree-based: skip scaling. Distance, gradient, penalty or PCA: scale.
- Sparsity. Sparse input:
MaxAbsScaler, orStandardScaler(with_mean=False), which scales without centering. - Outliers. Heavy outliers that are real data:
RobustScaler. Outliers that are errors: fix or remove them first, then use a standard choice. - Skew. Strongly skewed feature: consider
PowerTransformerbefore scaling, or use it alone since it standardizes by default. - Required range. A bounded input is a requirement:
MinMaxScaler, ideally withclip=Trueif new data may exceed the training range. - Otherwise.
StandardScaler.
Common mistakes
- Choosing
MinMaxScalerby habit. It is popular in tutorials, but it is the most outlier-sensitive of the common scalers. Use it for a reason. - Expecting scaling to fix skew. Linear scalers change location and spread, not shape. A skewed feature stays skewed.
- Scaling the target by accident.
StandardScalerin a feature pipeline does not touchy. If you scaleyfor a regressor, useTransformedTargetRegressorso predictions come back in original units. - Comparing scalers on a leaky setup. Fitting each scaler on the full dataset before cross-validation makes the comparison unreliable. Compare inside a pipeline.
- Applying
Normalizerwhen you meant column scaling. It works on rows and changes the meaning of the data. - Scaling one-hot columns. Standardizing 0/1 indicator columns is allowed but usually pointless, and it destroys their easy interpretation.
Exercise
A dataset has two numeric features. "age" is roughly symmetric with no outliers. "purchase_amount" is right-skewed, with a few very large orders that are genuine customers, not errors. You will train a logistic regression with L2 regularization. Which scaler would you assign to each column, and how would you set it up so the cross-validation score is not leaked?
Show answer
Use StandardScaler for "age" and RobustScaler (or a PowerTransformer) for "purchaseamount", because the median and IQR are not dragged by the genuine large orders. Combine them in a ColumnTransformer and put that and the LogisticRegression in a Pipeline, then pass the pipeline to crossval_score or GridSearchCV. The scalers are then refit on each training fold, so the validation folds never influence the learned statistics.