Sub topic 2
Transformers: scaling, imputing, and encoding
This chapter assumes you know fit and predict on a scikit-learn model, and that you can use NumPy arrays and pandas DataFrames. It covers the three most common kinds of preprocessing step and the rules they all follow.
What a transformer is
A transformer is an estimator that converts input data into new data. Instead of predict, it has transform. It learns from the data in fit, and it applies what it learned in transform.
Each transformer learns something different:
| Transformer | Learns in `fit` | Does in `transform` |
|---|---|---|
| `StandardScaler` | Mean and standard deviation of each column | Subtracts the mean and divides by the standard deviation |
| `SimpleImputer` | A fill value for each column (mean, median, most frequent) | Replaces missing values with that fill value |
| `OneHotEncoder` | The set of categories in each column | Turns each category into a 0/1 column |
The learned values are stored as attributes that end in an underscore, such as mean_ or categories_. The underscore marks values that exist only after fitting.
Scaling numeric columns
Many models, including logistic regression, support vector machines, and k-nearest neighbors, are sensitive to feature scale. A column measured in the hundreds can dominate a column measured in single digits. StandardScaler rescales each column to mean 0 and standard deviation 1.
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0, 100.0], [2.0, 200.0], [3.0, 300.0]])
X_new = np.array([[4.0, 400.0]])
scaler = StandardScaler()
scaler.fit(X_train)
print(scaler.mean_)
print(scaler.transform(X_new))The output is [ 2. 200.] and then [[2.44948974 2.44948974]]. The new row is scaled with the mean and standard deviation of the training data, not its own. This is the central rule of transformers. Fit on training data, then reuse the learned values everywhere else.
Imputing missing values
Most scikit-learn models raise an error when the input contains NaN. SimpleImputer fills the gaps. The strategy argument chooses the fill value: "mean", "median", "most_frequent", or "constant".
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, np.nan],
[3.0, 4.0],
[np.nan, 8.0]])
imputer = SimpleImputer(strategy="median")
print(imputer.fit_transform(X))This prints [[1. 6.], [3. 4.], and [2. 8.] on separate rows. The median of the first column is 2, and the median of the second is 6. Use median when a column has outliers, and use most_frequent for categorical columns.
fit_transform is a shortcut for calling fit and then transform on the same data. Use it only on training data.
Encoding categories
Models need numbers, so text categories must be converted. OneHotEncoder creates one column per category. A row gets a 1 in the column for its category and 0 in the others.
import numpy as np
from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder(handle_unknown="ignore")
enc.fit(np.array([["Oslo"], ["Bergen"], ["Oslo"]]))
print(enc.categories_[0])
print(enc.transform(np.array([["Bergen"], ["Tromso"]])).toarray())The categories are sorted, so the output is ['Bergen' 'Oslo']. The row for Bergen becomes [1. 0.]. Tromso never appeared in training, so with handle_unknown="ignore" it becomes [0. 0.].
The encoder returns a sparse matrix by default, which stores only the nonzero entries. Call .toarray() when you want to print it.
Common errors
- Fitting on test data. Calling
fitorfit_transformon the test set computes new statistics from data the model should not see. Call onlytransformon test data. - Unseen categories. Without
handle_unknown="ignore",OneHotEncoderraises aValueErrorthe first time it meets a category it did not see duringfit. - Wrong column type.
StandardScalerfails on text columns, andOneHotEncoderis the wrong tool for continuous numbers. Choose the transformer by column type. The chapter onColumnTransformershows how to apply different ones to different columns. - Imputing before splitting. The imputer's fill value is a learned statistic like any other. Fit it on training data only.
Applying the same rule everywhere
Every transformer follows the same pattern, so you can swap one for another. MinMaxScaler rescales to a fixed range, OrdinalEncoder maps categories to integers, and KNNImputer fills gaps from similar rows. Once you know fit then transform, you know the interface for all of them.
Exercise
You fit a StandardScaler on Xtrain. A colleague then calls scaler.fittransform(X_test) and passes the result to the trained model. What is wrong, and what should they call instead?
Show answer
fittransform refits the scaler, so the test data is scaled with the test set's own mean and standard deviation instead of the training values the model learned from. The statistics also leak information from the test set. They should call scaler.transform(Xtest), which reuses the training statistics.