MinMaxScaler
- Machine Learning course
- Beginner
- Lesson 77/112
- 5 min
MinMaxScaler compresses data between 0 and 1.
MinMaxScaler
MinMaxScaler moves each feature into the [0, 1] range with (x - min) / (max - min). The smallest value becomes 0 and the largest 1:
from sklearn.preprocessing import MinMaxScaler
mm = MinMaxScaler()
print(mm.fit_transform([[10], [20], [30]])) # [[0. ] [0.5] [1. ]]It is handy where a bounded range is expected, like image pixels (0-255) and neural network inputs. The range can be changed with feature_range=(-1, 1).
Outlier sensitivity and RobustScaler
Since MinMax relies on min and max, a single outlier squeezes all the other values into a narrow range. RobustScaler uses the median and the interquartile range:
x = np.array([[1], [2], [3], [4], [100]])
print(MinMaxScaler().fit_transform(x).ravel().round(2)) # [0. 0.01 0.02 0.03 1. ]
from sklearn.preprocessing import RobustScaler
print(RobustScaler().fit_transform(x).ravel()) # [-1. -0.5 0. 0.5 48.5]With RobustScaler, typical values stay in a sensible range and the outlier stands out as large.
Practice Two scalers
Transform X with MinMaxScaler and print it. Then transform the example [[30, 7500]] with the same scaler and print it.
Starter code
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[25, 3000], [35, 5000], [45, 10000]], dtype=float)
# buraya yazSample solution
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[25, 3000], [35, 5000], [45, 10000]], dtype=float)
mm = MinMaxScaler()
print(mm.fit_transform(X))
print(mm.transform([[30, 7500]]))Expected output
[[0. 0. ] [0.5 0.28571429] [1. 1. ]] [[0.25 0.64285714]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For a feature with min=0 and max=200, what does 50 become with MinMaxScaler?
- 0.2
- 0.25 Correct answer
- 0.5
- 50
Explanation: (50 - 0) / (200 - 0) = 0.25.
2 Move the values into the range -1 to 1.
mm = MinMaxScaler(____=(-1, 1))
mm = MinMaxScaler(feature_range=(-1, 1))
Explanation: feature_range takes the target range as (low, high).
3 Match the scalers.
| Term | Meaning |
|---|---|
StandardScaler |
Mean 0, std 1 |
MinMaxScaler |
[0, 1] range |
RobustScaler |
Median and IQR |
feature_range |
Target range |