Sub topic 3
Feature Names and Sparse Output
Assume you know pandas DataFrames, NumPy arrays, feature matrices, and training/test splits. This chapter focuses on practical choices after learning the one-hot encoding idea.
Feature names and sparse output
OneHotEncoder creates one output column per category. Use get_feature_names_out() to inspect those columns.
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame({"city": ["Paris", "Berlin", "Paris"]})
encoder = OneHotEncoder(handle_unknown="ignore")
encoded = encoder.fit_transform(X)
print(encoder.get_feature_names_out())
print(type(encoded).__name__, encoded.shape)The result is usually a sparse matrix. A sparse matrix stores nonzero values instead of storing every zero. This saves memory when each row has only a few active categories.
Redundant columns and the drop option
For one categorical column, all indicator values sum to one. With an intercept, this creates perfect redundancy for some linear models. Use drop="first" to omit one category:
encoder = OneHotEncoder(drop="first", sparse_output=False)The omitted category becomes the reference category. Coefficients then describe differences from that reference. Regularization often makes the full representation workable, while dropping a column can simplify interpretation.
Missing values in categorical columns
Treat missing values deliberately. You can replace them with a label such as "missing" when absence is meaningful. Otherwise, impute the most frequent category before encoding. Do not let training and prediction code choose different policies.
Putting it in a ColumnTransformer and Pipeline
A ColumnTransformer applies different preprocessing to different columns. A Pipeline fits those steps together, preventing test data from influencing preprocessing.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
preprocess = ColumnTransformer([
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("encode", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
("num", StandardScaler(), ["age"]),
])
model = Pipeline([
("prep", preprocess),
("classifier", LogisticRegression()),
])Rare categories and high-cardinality features
A column with thousands of categories can create thousands of mostly empty columns. Use min_frequency to group rare values:
OneHotEncoder(
min_frequency=2,
handle_unknown="infrequent_if_exist"
)This limits dimensionality, but grouping can lose useful distinctions.
When not to use one-hot encoding
For high-cardinality identifiers, consider feature hashing, frequency encoding, target encoding, or learned embeddings. Target encoding requires careful cross-validation because it can leak the target into training features. For ordered categories, ordinal encoding may preserve meaningful order.
Exercise
Why can a sparse matrix be preferable after one-hot encoding?
Show answer
It stores mostly nonzero entries, reducing memory use when each row activates only a few columns.