Sub topic 9
Transformers: fit, transform, and fit_transform
A transformer is an estimator that changes data instead of predicting a label. It takes a feature matrix X and returns a new matrix, usually with the same number of rows. Scalers, encoders, imputers, and feature selectors are all transformers. This chapter covers the transformer interface, the reason fit and transform are separate methods, and the mistakes that follow from mixing them up.
This chapter assumes you can write basic Python classes and read NumPy array shapes. It also assumes you know what fit does on an estimator and why a train/test split exists. Both come from earlier chapters.
The transformer interface
A transformer has three methods.
fit(X, y=None)learns values from the data and stores them on the object. It returnsself.transform(X)applies the learned values to data and returns a new array. It does not change the learned values.fit_transform(X, y=None)runsfitand thentransformon the same data.
StandardScaler is the standard example. It learns the mean and variance of each column during fit. It then uses those values in transform to compute (x - mean) / std.
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_)
print(X_train_scaled.mean(axis=0).round(6))
print(X_test_scaled.mean(axis=0).round(2))The training data ends up with a mean of 0 in each column. The test data does not, and it should not. The scaler applies the training mean to the test data, so the test columns are only roughly centered. That small difference is expected. It shows the scaler is treating the test set as new data it has not seen.
The learned values are attributes that end in an underscore: mean_, scale_, var_. As the previous chapter explained, the trailing underscore marks values that exist only after fit. Calling transform on an unfitted transformer raises NotFittedError.
Why fit and transform are separate
It would be simpler to have one method that does both. The split exists because the two steps happen on different data.
- Learning happens once, on the training data.
- Applying happens many times, on training data, test data, validation folds, and new data that arrives in production.
If transform re-learned values on each call, the same input could produce different outputs depending on what else was in the batch. A single new row could not be scaled at all, because one row has no meaningful variance. By storing the learned values in fit, the transformer behaves as a fixed function once it is trained.
import numpy as np
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(np.array([[10.0], [20.0], [30.0]]))
print(scaler.transform(np.array([[20.0]]))) # [[0.]]
print(scaler.transform(np.array([[40.0]]))) # about [[2.449]]Each call uses the mean of 20 and the standard deviation of about 8.16 learned from the three training values. A single new row works without a problem.
What fit_transform is for
fit_transform(X) is a convenience. For most transformers it gives the same result as fit(X).transform(X). Some classes override it to do the work in one pass, which can be faster.
Use fit_transform only on the training data. Use transform on everything else.
| Data | Method | Why |
|---|---|---|
| Training set | `fit_transform` | The transformer should learn from this data. |
| Test set | `transform` | The transformer must reuse what it learned from training. |
| New data in production | `transform` | Same reason as the test set. |
A few transformers produce slightly different output from fit_transform than from fit followed by transform. Target-aware encoders are the usual case, because they use cross-fitting inside fit_transform to avoid leaking the label. Do not assume the two paths are equal for every class. Check the documentation for the specific transformer.
Avoiding the most common error
The most frequent transformer mistake is calling fit or fit_transform on the test set, or on all of the data before splitting.
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)
# Wrong: the scaler sees the test rows before the split.
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, random_state=0)This code runs without an error. The test rows have contributed to the mean and variance, so information from the test set has reached the training pipeline. This is called data leakage, and the next chapter treats it in full. With simple scaling the effect is usually small, which is one reason it goes unnoticed. With imputers, feature selectors, or target-based encoders, the effect can be large enough to make a poor model look good.
The correct order is to split first, then fit the transformer on the training portion only.
Learned state differs by transformer
Different transformers learn different things in fit. Knowing what each one stores helps you inspect it and debug it.
| Transformer | Learned in `fit` | Attributes |
|---|---|---|
| `StandardScaler` | Mean and standard deviation per column | `mean_`, `scale_`, `var_` |
| `MinMaxScaler` | Minimum and maximum per column | `data_min_`, `data_max_` |
| `SimpleImputer` | Fill value per column | `statistics_` |
| `OneHotEncoder` | The set of categories per column | `categories_` |
| `PCA` | Principal directions | `components_`, `explained_variance_` |
Some transformers learn nothing. FunctionTransformer and Normalizer work on each row independently, so their fit does only input checks. They still follow the same interface, which is what lets them sit in a pipeline next to stateful steps.
Output shape and type
transform returns a NumPy array by default. Two details cause confusion.
First, the number of columns can change. OneHotEncoder turns one categorical column into several. PCA(n_components=2) reduces any number of columns to two. The number of rows stays the same.
Second, the number of columns seen at transform time must match the number seen during fit. If you fit on four columns and transform data with three, scikit-learn raises a ValueError.
import numpy as np
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(np.zeros((5, 4)))
print(scaler.n_features_in_) # 4
try:
scaler.transform(np.zeros((2, 3)))
except ValueError as error:
print("ValueError:", error)The n_features_in_ attribute records how many columns the transformer saw. When you fit on a DataFrame, scikit-learn also stores feature_names_in_ and checks column names at transform time.
Some transformers can also return a DataFrame instead of an array. Call set_output(transform="pandas") on the transformer to get that behavior.
import pandas as pd
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({"age": [22, 35, 47], "income": [30, 52, 61]})
scaler = StandardScaler().set_output(transform="pandas")
print(scaler.fit_transform(df))The result keeps the column names and the row index, which makes later steps easier to read.
Transformers that use y
fit accepts y=None for every transformer, so that a pipeline can pass labels to any step. Most transformers ignore it. A few use it.
SelectKBest scores each feature against the label and keeps the top ones. Its fit needs y, and it raises an error if you omit it. This is one more reason the transformer must be fit on training data only. The label from the test set must never reach fit.
from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest, f_classif
X, y = load_iris(return_X_y=True)
selector = SelectKBest(score_func=f_classif, k=2)
X_reduced = selector.fit_transform(X, y)
print(X_reduced.shape) # (150, 2)
print(selector.get_support())The life of a transformer
The diagram shows what happens to a transformer and to the data it sees.
Common errors
NotFittedError: you calledtransformbeforefit. Fit the transformer first.ValueErrorabout the number of features: the data passed totransformhas a different number of columns than the data passed tofit.fit_transformon the test set: no error, but the test score is too optimistic. Usetransform.- Fitting before splitting: also silent. Split first, or put the transformer inside a pipeline.
- Unseen categories:
OneHotEncoderraises an error attransformtime if it meets a category it did not see infit. Sethandle_unknown="ignore"to encode such values as all zeros. - Using the return value of
fit:fitreturns the transformer, not data. WritingX_new = scaler.fit(X)stores the scaler inX_new.
Summary
A transformer learns in fit, applies in transform, and offers fit_transform as a shortcut for the training data. The learned values live in attributes ending in an underscore. Keeping fit and transform separate is what lets the same transformer treat training, test, and production data consistently, and it is the foundation for the pipelines in a later chapter.
Exercise
You standardize the features of a dataset with StandardScaler().fit_transform(X), then call train_test_split on the result and train a model. Why is this a problem, and how do you fix it?
Show answer
The scaler computed its mean and standard deviation from all rows, including the rows that later become the test set. Information from the test set therefore influenced preprocessing, which is data leakage, and the test score will be too optimistic. Split first, call fit_transform on X_train only, and call transform on X_test. Putting the scaler and model in a Pipeline does this automatically.
Exercise
A StandardScaler was fit on a DataFrame with columns age and income. You call scaler.transform on a new DataFrame that contains only age. What happens, and which attribute records what the scaler expects?
Show answer
scikit-learn raises a ValueError because the number of features differs from what was seen in fit. The scaler recorded the expected count in n_features_in_ (2) and, because it was fit on a DataFrame, the column names in feature_names_in_.