Sub topic 5
Using StandardScaler and MinMaxScaler: fit, transform, fit_transform
This chapter assumes you know basic NumPy array operations, the mean and standard deviation, the purpose of a train/test split, and what a scikit-learn estimator is. The earlier chapters derived the formulas by hand. Here you will use the scikit-learn classes that implement them. You will see what each method call does, which attributes the scaler stores, and which mistakes come up most often.
The working model: learn, then apply
Both StandardScaler and MinMaxScaler are transformers. A transformer is an estimator that learns something from data and then uses it to change data. Scaling has two separate steps:
- fit learns per-column statistics from the data you pass in. It does not change the data.
- transform uses the stored statistics to rescale any array with the same columns.
fit_transform(X) runs both steps on the same array. It gives the same result as fit(X).transform(X). For some transformers it is faster, but for these two scalers it is mainly shorter.
The split matters because the statistics are a property of the scaler object, not of the array. Once fitted, a scaler can transform training data, test data, or one new row at prediction time, always with the same numbers.
StandardScaler in practice
StandardScaler computes (x - mean) / scale for each column. Here scale is the population standard deviation (ddof=0, dividing by n rather than n - 1).
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0]])
scaler = StandardScaler()
scaler.fit(X)
print(scaler.mean_) # [ 2. 400.]
print(scaler.scale_) # [ 0.81649658 163.29931619]
print(scaler.var_) # per-column variance
print(scaler.n_samples_seen_) # 3
X_scaled = scaler.transform(X)
print(X_scaled)
print(X_scaled.mean(axis=0)) # approximately [0. 0.]
print(X_scaled.std(axis=0)) # [1. 1.]The two columns have very different units, but after scaling both give [-1.2247, 0, 1.2247].
Attributes that end in an underscore, such as mean_ and scale_, exist only after fit. This is a scikit-learn convention for values learned from data. Constructor arguments such as with_mean do not end in an underscore.
Two constructor options are worth knowing:
with_mean=Falseskips centering and only divides by the scale. You need this for sparse matrices, because subtracting the mean would make them dense.with_std=Falseonly centers the data and does not divide by the standard deviation.
MinMaxScaler in practice
MinMaxScaler maps each column to a range, [0, 1] by default.
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 = MinMaxScaler()
X_mm = mm.fit_transform(X)
print(mm.data_min_) # [ 1. 200.]
print(mm.data_max_) # [ 3. 600.]
print(mm.data_range_) # [ 2. 400.]
print(X_mm) # each column becomes [0. 0.5 1. ]Internally, the scaler turns the formula into one multiply and one add. It stores scale_ = (hi - lo) / data_range_ and min_ = lo - data_min_ * scale_, where (lo, hi) is the target range. Then transform computes X * scale_ + min_.
To pick another range, use feature_range:
import numpy as np
from sklearn.preprocessing import MinMaxScaler
X = np.array([[1.0], [2.0], [3.0]])
sym = MinMaxScaler(feature_range=(-1, 1))
print(sym.fit_transform(X).ravel()) # [-1. 0. 1.]What each scaler learns
| Scaler | Learned attributes | Transform formula |
|---|---|---|
| StandardScaler | `mean_`, `scale_`, `var_`, `n_samples_seen_` | `(x - mean_) / scale_` |
| MinMaxScaler | `data_min_`, `data_max_`, `data_range_`, `scale_`, `min_` | `x * scale_ + min_` |
Both also record n_features_in_, the number of columns seen during fit. If the input was a DataFrame, they record feature_names_in_ too. These records drive the input checks described below.
fit_transform versus fit then transform
Use fit_transform when one array should both define the statistics and be scaled. In practice, that array is the training set.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0, 200.0], [2.0, 400.0], [3.0, 600.0]])
a = StandardScaler().fit_transform(X)
b = StandardScaler().fit(X).transform(X)
print(np.allclose(a, b)) # Truefit returns the scaler itself, which is why StandardScaler().fit(X).transform(X) chains. transform returns a new array. By default it copies the input. Passing copy=False to the constructor allows in-place scaling of a float array and saves memory. Integer arrays are always converted to floats first.
A new array can be scaled at any later time. For example, one new row at prediction time:
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0, 200.0], [2.0, 400.0], [3.0, 600.0]])
scaler = StandardScaler().fit(X_train)
new_row = np.array([[2.5, 500.0]])
print(scaler.transform(new_row))Note the double brackets. Scalers expect a 2D array of shape (n_samples, n_features).
Working with pandas
By default, a scaler returns a NumPy array even if you pass a DataFrame, so column names are lost. Since scikit-learn 1.2 you can ask for a DataFrame back:
import pandas as pd
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({"age": [20, 30, 40],
"income": [30000, 60000, 90000]})
scaler = StandardScaler().set_output(transform="pandas")
out = scaler.fit_transform(df)
print(out)
print(scaler.feature_names_in_) # ['age' 'income']The scaler also remembers the column names. If you later call transform with a DataFrame whose column names or order differ, scikit-learn raises an error or warns. This catches a silent bug, since reordered columns would otherwise be scaled with the wrong statistics.
Test data does not have to land inside the training range
A scaler applies fixed statistics. It does not renormalize new data. For StandardScaler this means test data will not have exactly mean 0 and standard deviation 1. That is expected. For MinMaxScaler, a test value outside the training min and max falls outside the target range:
import numpy as np
from sklearn.preprocessing import MinMaxScaler
train = np.array([[0.0], [10.0]])
test = np.array([[-5.0], [20.0]])
plain = MinMaxScaler().fit(train)
print(plain.transform(test).ravel()) # [-0.5 2. ]
clipped = MinMaxScaler(clip=True).fit(train)
print(clipped.transform(test).ravel()) # [0. 1.]Whether to clip depends on the model. Some models, such as neural networks with a bounded output activation, expect inputs in the stated range. Others work fine with values slightly outside. Clipping hides how far a value was outside the range, so decide deliberately.
Missing values
Both scalers ignore NaN when computing statistics in fit, and they keep NaN in place during transform. They do not fill missing values.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0], [np.nan], [3.0]])
print(StandardScaler().fit_transform(X).ravel()) # [-1. nan 1.]If your model cannot accept NaN, add an imputer step as well. The imputer and the scaler should be fitted on the same training data.
Learning from data in batches
If the data does not fit in memory, both scalers offer partial_fit. It updates the statistics one chunk at a time. Calling it repeatedly gives the same final statistics as calling fit on all the data at once, apart from floating-point rounding.
import numpy as np
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
data = rng.normal(loc=5.0, scale=2.0, size=(1000, 3))
batched = StandardScaler()
for chunk in np.array_split(data, 10):
batched.partial_fit(chunk)
full = StandardScaler().fit(data)
print(np.allclose(batched.mean_, full.mean_)) # True
print(np.allclose(batched.scale_, full.scale_)) # TrueA plain call to fit discards previous statistics and starts over. partial_fit accumulates them.
Common errors
Fitting on the wrong data
The most damaging mistake is calling fit_transform on the test set. The scaler then learns the test set's own mean and scale, so the two sets are scaled differently and the model sees inconsistent inputs. Fit on the training data only, then call transform on everything else. The next chapter explains this leakage problem in detail.
Calling transform before fit
import numpy as np
from sklearn.exceptions import NotFittedError
from sklearn.preprocessing import StandardScaler
try:
StandardScaler().transform(np.array([[1.0, 2.0]]))
except NotFittedError as err:
print("NotFittedError:", err)The error means no statistics exist yet. Call fit first.
Wrong number of columns
import numpy as np
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(np.zeros((4, 2)) + np.arange(4)[:, None])
try:
scaler.transform(np.ones((1, 3)))
except ValueError as err:
print("ValueError:", err)The message reads "X has 3 features, but StandardScaler is expecting 2 features as input." This usually means a column was added or dropped between training and prediction.
Passing a 1D array
A 1D array of shape (n,) raises an error saying that expected 2D array, got 1D array instead. For a single feature, reshape it with x.reshape(-1, 1). For a single sample with several features, use x.reshape(1, -1). The two reshapes mean different things, so check which one matches your data.
Scaling the target by accident
These scalers are meant for the feature matrix X. If you also scale a regression target y, you must invert predictions before reporting errors. Otherwise your error metrics are in scaled units.
Saving only the model
At prediction time, new data must pass through the same fitted scaler as the training data. If you save a model to disk, save the scaler with it, or better, save a Pipeline containing both. Pipelines are covered later in this tutorial.
Quick reference
| Task | Call |
|---|---|
| Learn statistics | `scaler.fit(X_train)` |
| Apply learned statistics | `scaler.transform(X)` |
| Learn and apply on the same array | `scaler.fit_transform(X_train)` |
| Update statistics with another chunk | `scaler.partial_fit(chunk)` |
| Keep column names | `scaler.set_output(transform="pandas")` |
| Keep values inside the range | `MinMaxScaler(clip=True)` |
| Handle sparse input | `StandardScaler(with_mean=False)` |
Exercise
You fit MinMaxScaler() on a training column with values 10, 20 and 30. A new test value of 40 is passed to transform. What does it return, and how could you force the result to stay inside [0, 1]?
Show answer
The scaler learned datamin = 10 and datamax = 30, so the scale is 1/20 and the result is (40 - 10) / 20 = 1.5. To keep the result inside [0, 1], create the scaler with MinMaxScaler(clip=True), which returns 1.0 for this value.
Exercise
A colleague writes X_test_s = StandardScaler().fit_transform(X_test) and gets good test accuracy. Explain what is wrong and show the correct two lines.
Show answer
The scaler is fitted on the test data, so it uses the test set's own mean and scale. The test features are then scaled differently from the training features, and information from the test set influences preprocessing. The correct code is scaler = StandardScaler().fit(X_train) followed by X_test_s = scaler.transform(X_test).
Exercise
After scaler = StandardScaler().fit(X_train), which attribute holds the per-column standard deviation used for scaling, and does it divide by n or n - 1?
Show answer
The attribute is scaler.scale_. It is the population standard deviation, so it divides by n (ddof=0). The related attribute var_ holds the variance, and scale_ is its square root.