Sub topic 5
Using StandardScaler and MinMaxScaler: fit, transform, fit_transform
This chapter assumes you know basic NumPy array operations, mean and standard deviation, and what a scikit-learn estimator is. You have already seen the two formulas by hand. Here you will use scikit-learn's classes that implement them and learn the three methods that drive them.
Scalers as transformers
A scikit-learn scaler is a transformer. It is an object that learns something from data and then uses what it learned to change data. The work is split into two steps:
fit(X)learns statistics fromXand stores them on the object. It does not changeX.transform(X)applies the stored statistics toXand returns a new array.fit_transform(X)runs both steps in one call on the same data.
The split matters because the statistics are kept. You can learn them from one array and apply them to another, which the next chapter relies on to prevent data leakage.
StandardScaler
StandardScaler computes (x - mean) / std for each column. During fit it stores mean_ and scale_. The attribute scale_ is the standard deviation of each column.
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
std_scaler = StandardScaler()
X_std = std_scaler.fit_transform(X)
print(std_scaler.mean_, std_scaler.scale_)
print(X_std)The learned values are mean_ = [2, 400] and scale_ = [0.8165, 163.299]. Each output column now has mean 0 and standard deviation 1.
StandardScaler uses the population standard deviation (ddof=0), the same as X.std(axis=0) in NumPy. It does not use the sample standard deviation that pandas' .std() returns by default. If you compare against pandas, pass ddof=0 or the numbers will differ slightly.
MinMaxScaler
MinMaxScaler computes (x - min) / (max - min) for each column. During fit it stores data_min_ and data_max_. By default the output range is [0, 1]. You can change it with feature_range.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
mm_scaler = MinMaxScaler(feature_range=(0, 1))
X_mm = mm_scaler.fit_transform(X)
print(mm_scaler.data_min_, mm_scaler.data_max_)
print(X_mm)The minimum of each column becomes 0 and the maximum becomes 1. Here both columns become [0, 0.5, 1], because the original columns were evenly spaced.
Fitting once, transforming many times
This is the working model. fit reads one dataset. transform can then be called on any dataset with the same number of columns, and it always reuses the stored statistics.
import numpy as np
from sklearn.preprocessing import MinMaxScaler
train = np.array([[0.0], [5.0], [10.0]])
new = np.array([[2.5], [12.0]])
scaler = MinMaxScaler().fit(train)
print(scaler.transform(new))The output is [[0.25], [1.2]]. The value 12 is above the training maximum of 10, so it maps outside [0, 1]. MinMaxScaler does not clip by default. Always keep this in mind when new data may fall outside the range you trained on.
fit_transform is a shortcut
scaler.fit_transform(X) gives the same result as scaler.fit(X).transform(X). Use it only on the data you want to learn from, usually the training set. Do not call it on test data, because that would learn new statistics from the test set.
| Call | Learns statistics | Returns scaled data | Typical use |
|---|---|---|---|
| `fit(X)` | Yes | No (returns the scaler) | Learn from training data |
| `transform(X)` | No | Yes | Apply to train, test or new data |
| `fit_transform(X)` | Yes | Yes | Learn from and scale the training data |
Common errors
Other mistakes you are likely to meet:
- Wrong number of columns. Calling
transformwith a different number of columns thanfitsaw raises aValueError. - Passing a 1-D array. Scalers expect a 2-D array of shape
(n_samples, n_features). For a single feature, usex.reshape(-1, 1). - Reading the output as a DataFrame. The output is a NumPy array even if the input was a pandas DataFrame. Column names are lost unless you rewrap the array.
- Forgetting the learned attributes end in
_. The attributesmean_,scale_,data_min_anddata_max_exist only afterfit. Reading them earlier raises anAttributeError.
Exercise
You run scaler = StandardScaler().fit(X_train) and then X_test_s = scaler.fit_transform(X_test). What is wrong, and what should the second line be?
Show answer
fit_transform refits the scaler on the test data, so the test set is scaled with its own mean and standard deviation instead of the training ones. The second line should be X_test_s = scaler.transform(X_test).
Exercise
A MinMaxScaler is fitted on a column with values 0 to 10. What does transform return for the value 15, and why?
Show answer
It returns 1.5. The formula is (15 - 0) / (10 - 0), and MinMaxScaler does not clip values outside the training range by default.