Tutorial¶
Encoding categories¶
LogitEncoder replaces each category with a value from a logit model of a
binary outcome. Fit it on the training data and its outcome, then encode new
data:
import pandas as pd
from logit_encode import LogitEncoder
X = pd.DataFrame({
'color': ['red', 'blue', 'red', 'green', 'blue', 'red'] * 50,
'size': ['S', 'M', 'L', 'M', 'S', 'L'] * 50,
'price': range(300)})
y = pd.Series([1, 0, 1, 0, 0, 1] * 50)
encoder = LogitEncoder()
train = encoder.fit_transform(X, y)
test = encoder.transform(X.head())
By default, every object, string, and categorical column is encoded (the
same columns that category_encoders picks), and other columns (here,
price) pass through unchanged. Name the
columns to encode with cols, or pass cols = 'all' to encode every column.
Choosing an encoding¶
encoding picks the value that replaces each category:
encoding |
Value | Scale |
|---|---|---|
'log_odds' (default) |
The average log odds of the outcome for rows in the category. In a univariate model, the intercept plus the category's coefficient. | log odds |
'coefficient' |
The category's coefficient: the log odds ratio of the outcome for the category against the reference category, which is 0. | log odds ratio |
'marginal_effect' |
The average change in the probability of the outcome from moving a row from the reference category to the category. | probability |
Within a univariate model, the log odds and the coefficients differ only by a constant (the intercept), so tree models split them the same way. The marginal effects are an increasing function of the coefficients, so tree models also split them the same way. The encodings differ most for linear models, which treat the log odds and coefficients as linear in the log odds of the outcome, and the marginal effects as linear in its probability.
Without a penalty (C = None), a univariate model's values have closed
forms. With p the share of a category's rows with the outcome and p_ref
the reference category's share:
- log odds:
log(p / (1 - p)), - coefficient:
log(p / (1 - p)) - log(p_ref / (1 - p_ref)), and - marginal effect:
p - p_ref.
So an unpenalized univariate log odds encoding is target encoding on the log odds scale. The penalty is what makes the logit model useful: it shrinks the coefficients of rare categories toward the reference category.
Univariate or joint models¶
With model = 'joint' (the default), one logit model has every column's
dummies, so a category's value is adjusted for the other columns. With
model = 'univariate', each column gets its own logit model, so a
category's value describes the outcome among all rows with that category.
For example, if large items are often red and large items often have the
outcome, a univariate model credits red for some of the effect of size,
while a joint model does not. In the benchmarks, joint
models did better with logistic regression and gradient boosting, and
univariate models slightly better with random forests.
In a joint model, a category's log odds is its coefficient plus the average linear predictor of the other columns, and its marginal effect is averaged over the rows with the other columns as observed.
Penalties¶
C is the inverse strength of the penalty on the coefficients, as in
scikit-learn's LogisticRegression: smaller values shrink more. l1_ratio
is the share of the penalty that is L1 (lasso) rather than L2 (ridge). An L1
penalty sets the coefficients of weak categories to exactly 0, merging them
with the reference category. C = None fits an unpenalized model, whose
coefficients for categories with only one outcome grow without bound.
Reference categories¶
Coefficients and marginal effects are relative to each column's reference
category, which gets 0. reference = 'most_frequent' (the default) uses the
category with the most rows, which keeps the estimates stable. reference =
'first' uses the first category seen in the training data. reference =
None gives every category a dummy, so the coefficients are relative to the
intercept and the penalty shrinks every category toward a common center
rather than toward one category.
Cross-fitting¶
A category's value comes from the outcomes of the rows in that category. If
a training row is encoded with a model that saw its own outcome, the
encoding leaks the outcome, and a classifier trained on it overfits,
especially for rare categories. So fit_transform cross-fits: the training
rows are split into cv folds (5 by default), and each fold is encoded with
a model fit on the other folds. transform on new data uses the model fit
on all of the training data.
As in category_encoders, passing y to transform marks the data as
training data, so transform(X, y) cross-fits too, and
fit(X, y).transform(X) does not. Set cv = None to turn cross-fitting off.
Missing and unknown categories¶
handle_missing and handle_unknown work as in category_encoders:
'value'(the default) treats missing values as a category of their own, and encodes unknown categories (and missing values, if there were none in the training data) with the prior: the column's average encoded value over the training rows.'return_nan'encodes them as missing values.'error'raises an error.- A number encodes them with that number.
Backends¶
backend = 'sklearn' (the default) fits the model with scikit-learn's
LogisticRegression on a sparse design matrix. backend = 'statsmodels'
fits the same model with statsmodels' GLM (binomial family, logit link) on
a dense design matrix. Both minimize the same penalized log loss, so they
give the same encodings up to the solvers' tolerances. The sklearn backend
is much faster for columns with many categories; the statsmodels backend is
there for users whose workflows are built on statsmodels.
Outcomes with more than two classes¶
An outcome with K classes is modeled with K - 1 logits, one for each class
against a reference class (the most frequent class), so each categorical
column becomes one column per other class, named <column>_<class>:
y = pd.Series(['no', 'maybe', 'yes', 'no', 'no', 'maybe'] * 50)
encoder = LogitEncoder().fit(X, y)
encoder.reference_class_ # 'no'
encoder.modeled_classes_ # ['maybe', 'yes']
encoder.get_feature_names_out()
# ['color_maybe', 'color_yes', 'size_maybe', 'size_yes', 'price']
For class k, the log odds and coefficients are on the scale of the log
odds of class k against the reference class, and the marginal effects are
changes in the probability of class k, computed from all of the classes'
logits together. With two classes, the first class (in sorted order) is the
reference class and each column stays one column.
Uncertainty columns¶
A category with few rows gets an uncertain value. With
return_uncertainty = True, each encoded column is followed by the standard
error of its value (<column>_se, or <column>_<class>_se) and the number
of training rows with the category (<column>_count), so a model can trust
the values of rare categories less:
encoder = LogitEncoder(return_uncertainty = True)
encoder.fit(X, y).get_feature_names_out()
# ['color', 'color_se', 'color_count', 'size', 'size_se', 'size_count',
# 'price']
A category not seen in fitting gets a count of 0 and the standard error of
a category with no rows, which comes from the penalty alone. Without a
penalty (C = None), that error is missing. See the
Advanced User Guide for how the errors are
computed.
Interactions¶
interactions lists combinations of columns to encode as one more
categorical column each, so the encoder can capture effects that depend on
two columns at once:
encoder = LogitEncoder(interactions = [('color', 'size')])
encoder.fit(X, y).get_feature_names_out()
# ['color', 'size', 'price', 'color|size']
Each interaction's values are its columns' values joined by '|', and a
row with a missing value in any of them has a missing interaction. The
interaction columns follow the other columns in the output. In a joint
model, the interaction's values are adjusted for its member columns.
Lookup tables¶
get_mapping returns, for each encoded column, a table of its categories
and their encoded values, with the same columns that transform makes from
it (including standard errors and counts with return_uncertainty = True):
encoder.get_mapping('color')
# color
# category
# red 1.865
# blue -2.679
# green -0.556
# <missing> -0.053
# <unknown> -0.053
The <missing> row is the value of a missing category when none were seen
in fitting, and the <unknown> row the value of a category that was not seen
in fitting. get_mapping() with no column returns a dict of every column's
table. (mapping_, as in category_encoders, holds the same values by
ordinal code, and ordinal_encoder_.category_mapping holds the codes.)
Converting back to categories¶
inverse_transform matches each encoded value to the category that has it:
This works for the output of transform on new data. It cannot recover
training rows encoded by fit_transform, since cross-fitting gives them
values that no category has, nor categories that were unknown in fitting.
Categories with identical values (rare, but possible) cannot be told apart.
Values that match no category, or more than one, come back missing, with a
warning.