Sub topic 4
Min-max scaling to a fixed range
Min-max scaling rescales each numeric column so that its values fall in a fixed interval, usually [0, 1]. This chapter covers the formula, how MinMaxScaler implements it, and what happens to new data that falls outside the range seen during fitting. It also covers how outliers, constant columns and missing values behave, and when to prefer min-max scaling over standardization.
It assumes you know basic NumPy, the idea of a train/test split, and the scikit-learn fit and transform pattern.
The idea
Take one column. Find its smallest and largest values. Then map the smallest value to 0 and the largest to 1, and place every other value proportionally between them:
xscaled = (x - xmin) / (xmax - xmin)
The shape of the distribution is unchanged. Only the units and the offset change. Two values that were twice as far apart before are still twice as far apart after. The scaling is a linear (affine) transformation, so it is reversible and preserves the order of the values.
The result has a guaranteed range, but not a guaranteed mean or standard deviation. This is the main difference from standardization, which guarantees mean 0 and standard deviation 1 but no fixed bounds.
Computing it by hand
The formula works column by column, so axis=0 is needed in every reduction.
import numpy as np
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
col_min = X.min(axis=0)
col_max = X.max(axis=0)
mm = (X - col_min) / (col_max - col_min)
print(mm)
# [[0. 0. ]
# [0.5 0.5]
# [1. 1. ]]The two columns started with very different magnitudes (single digits versus hundreds). After scaling they are identical. A distance-based or gradient-based model now sees both columns on the same footing.
Using MinMaxScaler
MinMaxScaler splits the work into two steps. fit learns the per-column minimum and maximum from the data you give it. transform applies the formula using those stored values.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
scaler = MinMaxScaler()
X_mm = scaler.fit_transform(X)
print(scaler.data_min_) # [ 1. 200.]
print(scaler.data_max_) # [ 3. 600.]
print(scaler.data_range_) # [ 2. 400.]
print(scaler.scale_) # [0.5 0.0025]
print(scaler.min_) # [-0.5 -0.5]
print(X_mm)fit_transform is shorthand for calling fit and then transform on the same data. It is appropriate for training data only. The next chapter explains why.
The learned attributes end with an underscore, which is the scikit-learn convention for values estimated during fit. Internally, the scaler does not evaluate the division directly. It precomputes two arrays and applies:
Xscaled = X * scale + min_
Here scale_ is (feature_range_max - feature_range_min) / data_range_, and min_ is feature_range_min - data_min_ * scale_. You do not need these to use the class, but they explain the output above. For the second column, scale_ is 1/400 = 0.0025, and min_ is 0 - 200 * 0.0025 = -0.5.
Choosing a different range
The default interval is [0, 1]. The feature_range parameter changes it.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
X = np.array([[10.0], [20.0], [30.0]])
scaler = MinMaxScaler(feature_range=(-1, 1))
print(scaler.fit_transform(X).ravel()) # [-1. 0. 1.]Internally the scaler first computes the [0, 1] result, then stretches and shifts it: x_std * (max - min) + min, where max and min are the bounds in feature_range. A range of (-1, 1) is common for models whose activation functions are centered on zero, such as tanh. A range of (0, 1) suits inputs that are interpreted as intensities or probabilities.
New data can fall outside the range
The guarantee "every value lies in [0, 1]" holds only for the data used in fit. A later batch is scaled with the old minimum and maximum. If it contains a value smaller than the training minimum or larger than the training maximum, the result falls outside the range.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
train = np.array([[10.0], [20.0], [30.0]])
new = np.array([[5.0], [25.0], [40.0]])
scaler = MinMaxScaler().fit(train)
print(scaler.transform(new).ravel()) # [-0.25 0.75 1.5 ]
clipped = MinMaxScaler(clip=True).fit(train)
print(clipped.transform(new).ravel()) # [0. 0.75 1. ]With clip=True, transformed values are cut off at the bounds of feature_range. Clipping keeps the output inside the interval, but it also discards information: 40 and 4000 would both become 1. Whether that trade is acceptable depends on the model.
Values outside [0, 1] are not an error. They are a signal that the new data differs from what the model was trained on. If a model expects bounded inputs (for example, a neural network with a sigmoid input layer, or an image pipeline), clip. Otherwise, consider leaving the values alone and monitoring how often they occur.
Outliers
The minimum and maximum are the two most extreme values in a column. A single outlier moves one of them, and that changes the scaling of every other value.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
x = np.array([[1.0], [2.0], [3.0], [100.0]]) # 100 is an outlier
print(MinMaxScaler().fit_transform(x).ravel())
# [0. 0.01010101 0.02020202 1. ]The three ordinary values occupy about 2% of the interval, which is [0, 0.02]. To a model, they look almost identical. The scaled column is still valid and reversible, but most of the range is effectively wasted on one point.
Standardization is not immune. Its mean and standard deviation also depend on the outlier. But it does not promise a bounded range, so the damage shows up differently. The chapter on outliers compares both scalers side by side.
Practical options when you see this pattern:
- Remove or cap the outliers before scaling, if they are data errors.
- Use
clip=Trueonly after fitting on a trimmed training set, so that extreme later values are limited. - Use a scaler based on quantiles, such as
RobustScaler, which ignores the extremes when computing its statistics.
Constant columns and missing values
A column where every value is the same has x_max - x_min = 0. The formula would divide by zero. MinMaxScaler handles this: it replaces a zero range with 1 internally, so the column is transformed without warnings or NaN values.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
X = np.array([[5.0, 1.0],
[5.0, 2.0],
[5.0, 3.0]])
print(MinMaxScaler().fit_transform(X))
# [[0. 0. ]
# [0. 0.5]
# [0. 1. ]]The constant column becomes all zeros, the lower bound of feature_range. It carries no information either way, and you may want to remove such columns with a variance filter before scaling.
Missing values are also tolerated. NaN entries are ignored when the minimum and maximum are learned, and they stay NaN after the transform.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
X = np.array([[1.0], [np.nan], [3.0]])
print(MinMaxScaler().fit_transform(X).ravel()) # [ 0. nan 1.]You still need to impute the NaN values before passing the data to most models. Imputation can happen before or after scaling, but whichever order you choose, keep it consistent and put both steps in a pipeline.
One more limit: MinMaxScaler rejects sparse matrices, because subtracting the minimum would turn zeros into nonzero values and destroy the sparsity. For sparse data, MaxAbsScaler divides by the largest absolute value and keeps zeros as zeros.
When to use min-max scaling
| Situation | Min-max scaling | Standardization |
|---|---|---|
| Model needs inputs in a known interval (image pixels, some neural networks) | Good fit | Not bounded |
| Data has no extreme outliers and a stable range | Good fit | Also works |
| Data has heavy outliers | Compresses ordinary values | Also affected, but not squeezed into a fixed interval |
| Model assumes roughly zero-centered inputs (linear models with regularization, PCA) | Less natural, since the mean is not 0 | Usual choice |
| Sparse input | Not supported | `with_mean=False` is needed |
| Later data may exceed the training range | Out-of-range output unless `clip=True` | No bound to violate |
A reasonable default for tabular data with regularized linear models or PCA is standardization. Min-max scaling is the usual choice when you need bounded inputs, or when the feature has a natural fixed range, such as a percentage or a pixel intensity.
Tree-based models (decision trees, random forests, gradient boosting) split on thresholds, and a monotonic rescaling does not change which splits are possible. They do not need either scaler.
Common mistakes
- Fitting on the full dataset before splitting. The minimum and maximum then include test values, which leaks information. Fit on the training split only.
- Scaling the target. If you scale
y, you must callinverse_transformon predictions. For regression, many people leaveyalone or useTransformedTargetRegressor. - Assuming the output is always in [0, 1]. This is only true for the fitting data, as shown above.
- Passing a pandas
DataFrameand expecting aDataFrameback. By default, the scaler returns a NumPy array. Callscaler.set_output(transform="pandas")if you need column names preserved. - Reusing one scaler object across unrelated datasets. Each call to
fitoverwrites the stored statistics.
Exercise
A scaler is fitted on the training values [10, 20, 30] with MinMaxScaler(feature_range=(0, 1)). What does transform return for the new value 45, and what does it return if the scaler was created with clip=True?
Show answer
The training minimum is 10 and the range is 20, so 45 maps to (45 - 10) / 20 = 1.75. With clip=True, the value is cut off at the upper bound of feature_range, so the result is 1.0.
Exercise
A column contains the values [4, 4, 4, 4]. What does MinMaxScaler().fit_transform return for it, and why does it not produce NaN values from a division by zero?
Show answer
It returns all zeros. The data range is 0, and the scaler replaces a zero range with 1 internally, so each value becomes (4 - 4) * 1 + 0 = 0, the lower bound of feature_range.
Exercise
A column has 999 values between 0 and 1 and one outlier equal to 1000. After MinMaxScaler, roughly where do the 999 ordinary values fall, and what would you try first?
Show answer
They all fall within about [0, 0.001], since (1 - 0) / (1000 - 0) is about 0.001, so a model can barely tell them apart. First check whether the outlier is a data error and remove or cap it. If it is genuine, use a scaler that ignores extremes, such as RobustScaler.