Sub topic 2
Transformers: scaling, imputing, and encoding
What this chapter covers
This chapter assumes you can fit a scikit-learn model with fit and predict, split data into train and test sets, and use NumPy arrays and pandas DataFrames. It covers the three most common kinds of preprocessing transformer: scalers, imputers, and encoders. You will learn what each one learns during fit, what each one does during transform, and the errors that come up most often.
A transformer is an estimator that converts a feature matrix into a new feature matrix. It has fit and transform methods. Later chapters chain transformers into pipelines. Here we use them on their own so you can see what each does.
The transformer contract
A transformer follows two steps.
fit(X)learns numbers from the data. A scaler learns means and standard deviations. An imputer learns fill values. An encoder learns the list of categories.transform(X)applies what was learned. It does not learn anything new.
fit_transform(X) does both in one call. It gives the same result as fit(X).transform(X), though some transformers implement it more efficiently.
The learned numbers are stored as attributes that end in an underscore, such as mean_ or categories_. The underscore convention means "set during fit". You can read these attributes to check what the transformer learned.
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]])
X_new = np.array([[4.0, 800.0]])
scaler = StandardScaler()
scaler.fit(X_train)
print(scaler.mean_)
print(scaler.scale_)
print(scaler.transform(X_new))The scaler learned its statistics from X_train only. When it transforms X_new, it reuses the training mean and standard deviation. It does not recompute them from the new row. This rule is the basis of the next chapter, on data leakage.
Scaling numeric features
Many models are sensitive to feature scale. Linear models with regularization, k-nearest neighbors, support vector machines, and neural networks all behave differently when one feature ranges over thousands and another over fractions. Tree-based models split on thresholds and mostly do not care about scale.
StandardScaler
StandardScaler subtracts the training mean from each column and divides by the training standard deviation. Each output column then has mean 0 and standard deviation 1 on the training data. It is the default choice for most linear and distance-based models.
MinMaxScaler
MinMaxScaler maps each column to a fixed range, by default 0 to 1, using the training minimum and maximum. Values in new data can fall outside that range, because the new data may contain values beyond the training minimum or maximum. The scaler does not clip them unless you pass clip=True.
RobustScaler
RobustScaler subtracts the median and divides by the interquartile range (the distance between the 25th and 75th percentiles). Because a few extreme values barely move the median or quartiles, this scaler is a better fit when your data has outliers.
| Scaler | Learns | Output | Sensitive to outliers |
|---|---|---|---|
| `StandardScaler` | mean, standard deviation | mean 0, std 1 | Yes |
| `MinMaxScaler` | minimum, maximum | range 0 to 1 by default | Yes, strongly |
| `RobustScaler` | median, interquartile range | median 0, spread near 1 | Much less |
Here is how an outlier affects each scaler.
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
X = np.array([[1.0], [2.0], [3.0], [4.0], [1000.0]])
for scaler in (StandardScaler(), MinMaxScaler(), RobustScaler()):
out = scaler.fit_transform(X).ravel()
print(type(scaler).__name__, np.round(out, 3))With MinMaxScaler, the first four values are squeezed close to 0 because the outlier sets the maximum. With RobustScaler, they keep a reasonable spread and only the outlier is far away.
Imputing missing values
Most scikit-learn models raise an error when the input contains NaN. Imputation replaces missing values with an estimate. SimpleImputer handles the common cases.
SimpleImputer has a strategy parameter.
"mean"and"median"work on numeric columns. The median is safer with skewed data."most_frequent"works on numeric and categorical columns."constant"fills with the value you give infill_value.
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[1.0, 10.0], [2.0, np.nan], [np.nan, 30.0], [4.0, 50.0]])
imputer = SimpleImputer(strategy="median")
imputer.fit(X_train)
print(imputer.statistics_)
print(imputer.transform(np.array([[np.nan, np.nan]])))The attribute statistics_ holds one fill value per column. A new row with missing values receives the medians learned from training data.
Keeping track of what was missing
Sometimes the fact that a value is missing carries information. For example, a missing income field may correlate with the label. Pass add_indicator=True to append extra columns that mark where values were missing.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, np.nan], [2.0, 5.0], [np.nan, 7.0]])
imputer = SimpleImputer(strategy="mean", add_indicator=True)
print(imputer.fit_transform(X))The output has two imputed columns followed by two indicator columns of 0 and 1.
Common imputer errors
- A column that is entirely missing in the training data is dropped by default, because there is nothing to compute. This changes the number of output columns, which can surprise you later.
- Using
"mean"or"median"on a text column raises an error. Use"most_frequent"or"constant"for categorical data.
Encoding categorical features
Models need numbers, so categories such as city names must be converted.
OneHotEncoder
OneHotEncoder creates one binary column per category. A row gets a 1 in the column for its category and 0 elsewhere. It makes no claim that one category is larger than another, which makes it the usual choice for nominal data (categories with no natural order).
import numpy as np
from sklearn.preprocessing import OneHotEncoder
X_train = np.array([["Oslo"], ["Bergen"], ["Oslo"], ["Trondheim"]])
encoder = OneHotEncoder(handle_unknown="ignore")
encoder.fit(X_train)
print(encoder.categories_)
print(encoder.transform(np.array([["Bergen"], ["Stavanger"]])).toarray())The categories are sorted alphabetically: Bergen, Oslo, Trondheim. The unseen city "Stavanger" becomes a row of all zeros because of handle_unknown="ignore".
By default, OneHotEncoder raises an error when transform meets a category it did not see in fit. In production this happens regularly, so setting handle_unknown="ignore" is a common choice. It returns a sparse matrix by default, so .toarray() converts it to a dense array for printing. Sparse output saves memory when a column has many categories.
Two further parameters are worth knowing:
drop="first"removes one column per feature. This avoids perfectly redundant columns, which matters for some unregularized linear models.min_frequencygroups rare categories into one "infrequent" column. This limits the width of the output for high-cardinality columns.
OrdinalEncoder
OrdinalEncoder maps each category to an integer. Use it only when the categories have a real order, such as "low", "medium", "high". Give the order explicitly so the integers follow it.
import numpy as np
from sklearn.preprocessing import OrdinalEncoder
X = np.array([["low"], ["high"], ["medium"], ["low"]])
encoder = OrdinalEncoder(categories=[["low", "medium", "high"]])
print(encoder.fit_transform(X).ravel())Without the categories argument, the order would be alphabetical, giving "high" 0, "low" 1, and "medium" 2. That order would be wrong for this feature.
LabelEncoder is for targets
LabelEncoder encodes the target y, not the features. It accepts one-dimensional input. Most classifiers already accept string labels, so you rarely need it.
Choosing and combining transformers
Each transformer in this chapter works on a whole array. Real datasets mix numeric and categorical columns, and the two kinds need different treatment. A scaler applied to a text column fails, and a one-hot encoder applied to a numeric column creates one column per distinct number. Chapter 5 shows how ColumnTransformer routes each column group to the right transformer.
Order also matters inside one column group. Missing values should usually be imputed before scaling, because a scaler's statistics are computed on whatever values it sees.
The diagram shows a typical flow.
Output types and feature names
Transformers return NumPy arrays by default, even if you pass a DataFrame. Column names are lost. Two features help.
get_feature_names_out()returns the names of the output columns. ForOneHotEncoderthe names look likecity_Oslo.set_output(transform="pandas")makes a transformer return a DataFrame with those names. This is available in recent scikit-learn versions.
import pandas as pd
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({"age": [20, 30, 40], "income": [30000, 50000, 70000]})
scaler = StandardScaler().set_output(transform="pandas")
out = scaler.fit_transform(df)
print(out)
print(scaler.get_feature_names_out())Common mistakes
- Fitting on all the data before splitting. The scaler or imputer then uses statistics from test rows. The next chapter explains this leak.
- Calling
fit_transformon the test set. This refits the transformer on test data. Usetransform. - Forgetting that a sparse matrix is not a dense array. Some functions, and
print, behave differently. Convert with.toarray()when needed, or setsparse_output=FalseonOneHotEncoder. - Using
OrdinalEncoderfor unordered categories. UseOneHotEncoderunless the order is real. - Scaling a column that has
NaN. Scalers ignoreNaNwhen computing statistics and keep it in the output, so the model still fails later. Impute first.
Exercise
A teammate fits a StandardScaler on the full dataset, then splits into train and test sets, then trains a model. Which attribute values were computed using test rows, and what should the teammate change?
Show answer
The scaler's mean and scale (the column means and standard deviations) include information from the test rows. The teammate should split first, call fit (or fit_transform) on the training set only, and call transform on the test set using the training statistics.
Exercise
You apply OneHotEncoder(handle_unknown="ignore") fitted on the cities Bergen, Oslo, and Trondheim. A new row contains "Stavanger". What does its encoded row look like, and why might this be preferable to the default behavior?
Show answer
The row is [0, 0, 0], with no category marked. The default behavior raises an error when transform sees an unseen category, which would crash a prediction service. Ignoring unknowns lets the model still produce a prediction.
Exercise
A numeric column has a few extreme outliers, and you plan to scale it before fitting a k-nearest neighbors model. Which scaler would you try first, and why?
Show answer
RobustScaler. It centers on the median and divides by the interquartile range, so a few extreme values barely change the scaling. StandardScaler and MinMaxScaler both use statistics that outliers distort, and MinMaxScaler would compress most values into a narrow band.