Sub topic 9
Transformers: fit, transform, and fit_transform
This chapter assumes you can fit an estimator and call predict, and that you know what X_train and X_test are. A transformer is an estimator that changes the data instead of predicting a label. Scalers, encoders, and imputers are all transformers.
The two-step contract
A transformer has two main methods:
fit(X)learns values from the data. AStandardScalerlearns the mean and variance of each column.transform(X)applies the learned values and returns a new array. It does not learn anything.
fit_transform(X) runs both in one call. It is the method you use on training data.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(scaler.mean_)The scaler computes mean_ from X_train only. It then reuses that same mean and variance on X_test. The values it learned are stored in attributes that end in an underscore, such as mean_ and scale_.
What happens at each step
Why you never call fit on test data
If you call fit or fit_transform on the test set, the scaler learns the test set's own mean. Information from data you meant to hold out then shapes your preprocessing. Your test score looks better than it should, and it no longer predicts how the model behaves on new data. This is data leakage, and the next chapter covers it in detail.
The rule is short: call fit or fit_transform on training data only. Call transform on everything else.
Checking what was learned
You can inspect a fitted transformer to confirm that it learned from the right data.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
scaler = StandardScaler().fit(X)
X_scaled = scaler.transform(X)
print(np.round(X_scaled.mean(axis=0), 6)) # close to 0 in every column
print(np.round(X_scaled.std(axis=0), 6)) # close to 1 in every columnfit returns the estimator itself, so StandardScaler().fit(X) can be chained with other calls. After scaling the same data it was fitted on, each column has mean 0 and standard deviation 1. Scaled test data will not match exactly, and that is expected.
Common errors
| Symptom | Likely cause |
|---|---|
| `NotFittedError` | You called `transform` before `fit`. |
| Test data has mean far from 0 after scaling | Probably nothing is wrong. The training mean and variance differ from the test data's. |
| Test mean is exactly 0 | You called `fit_transform` on the test data. |
| Shape error in `transform` | The test data has a different number of columns from the training data. |
Some transformers also accept y in fit(X, y), for example supervised feature selection. Even then, y must come from the training set only.
Summary
A transformer follows the same conventions as other estimators. It is configured in the constructor, learns in fit, and keeps what it learned in underscore attributes. transform applies those values. fit_transform is the shortcut for training data. Because the transformer's learned values live inside the object, you can reuse them later on new data. Chaining these steps by hand gets tedious, which is why scikit-learn offers Pipeline.
Exercise
You fit a StandardScaler on Xtrain. A colleague then writes `scaler.fittransform(X_test)` to scale the test set. What is wrong, and what should the line be?
Show answer
fittransform refits the scaler on the test data, so the scaler's mean and variance come from the test set and no longer match the training data. This leaks test information into preprocessing and gives the model inputs on a different scale. The line should be `scaler.transform(Xtest)`.
Exercise
After scaler = StandardScaler().fit(X_train), which attribute holds the learned column means, and why does its name end in an underscore?
Show answer
scaler.mean_. By scikit-learn convention, attributes learned during fit end in an underscore, which separates them from the hyperparameters set in the constructor.