LogitEncoder(verbose=0, cols=None, drop_invariant=False, return_df=True, handle_missing='value', handle_unknown='value', encoding='log_odds', model='joint', backend='sklearn', C=1.0, l1_ratio=0.0, cv=5, reference='most_frequent', interactions=None, return_uncertainty=False, max_iter=5000, n_jobs=None, random_state=None, min_group_size=None, min_group_name=None, combine_min_nan_groups=None, composite_cols=None, keep_components=False)
¶
Bases: SupervisedTransformerMixin, BaseEncoder
Encodes categories with values from a logit model of the outcome.
Each categorical column is dummy-coded and a logit model of the outcome
is fit on the dummies. Each category is then replaced by one of three
values from that model (see encoding):
- 'coefficient': the level's coefficient, which is the log odds ratio of the outcome for that level against the column's reference level.
- 'log_odds': the average log odds of the outcome when the column is set to that level. In a univariate model, it is the intercept plus the coefficient.
- 'marginal_effect': the average change in the probability of the outcome from moving the column from the reference level to that level, holding the other columns as observed (a discrete change, since the level is a dummy).
The model can be one logit with every column's dummies ('joint', the default), whose values are adjusted for the other columns, or a separate logit for each column ('univariate'). Either sklearn or statsmodels can fit it. Both minimize the same penalized log loss, so they agree up to solver tolerances.
An outcome with more than two classes is modeled with a logit for each
class against a reference class (the most frequent class), so each
categorical column becomes one column per other class, named
'
interactions adds a column for each listed combination of columns,
encoded like any other categorical column, and return_uncertainty adds
each value's standard error ('
Encoding training rows with a model fit on those same rows leaks the
outcome into the features. So, like sklearn's TargetEncoder,
fit_transform (and transform given y) cross-fits: each training
row is encoded by a model fit on the other folds. transform without
y uses the model fit on all of the training data. Set cv to None to
turn cross-fitting off.
LogitEncoder is a drop-in replacement for the supervised
category_encoders encoders: it takes the same parameters (cols,
drop_invariant, return_df, handle_missing, handle_unknown,
min_group_size, min_group_name, combine_min_nan_groups,
composite_cols, and keep_components, in the same order as
TargetEncoder's), has the same mapping, ordinal_encoder,
invariant_cols, and feature_names_out_ attributes and
get_feature_names_out and get_feature_names_in methods, and passes
extra DataFrame columns through transform. It is also a full sklearn
transformer: it works in pipelines, column transformers,
cross-validation, and grid searches, supports set_output, and passes
sklearn's check_estimator. The one difference is that cols keeps the
value it was given; the columns that were encoded are in cols_.
LogitEncoder is not a dataclass because sklearn reads an estimator's
parameters from its __init__ signature and requires that __init__
only store them.
Attributes:
| Name | Type | Description |
|---|---|---|
mapping_ |
for each encoded column (including interactions and
composite columns), the encoded value of each category's ordinal
code, fit on all of the training data: a series for a binary
outcome, or a DataFrame with a column per modeled class. The
codes are in |
|
error_mapping_ |
the standard errors of |
|
count_mapping_ |
for each encoded column, the number of training rows
with each category's ordinal code, if |
|
ordinal_encoder_ |
the fitted |
|
classes_ |
the outcome's classes, in sorted order. |
|
reference_class_ |
the class that the others are compared with. |
|
modeled_classes_ |
the other classes, which each get a column. |
|
interaction_cols_ |
the names of the interaction columns. |
|
composite_members_ |
for each composite column, its member columns. |
|
min_group_lumping_ |
for each column with categories lumped together
by |
|
n_iter_ |
largest number of solver iterations that any of the models fit on all of the training data used. |
|
cols_ |
the input columns that were encoded on their own. |
|
invariant_cols_ |
the output columns dropped by |
|
feature_names_out_ |
names of the output columns. |
|
n_features_in_ |
number of columns seen in fitting. |
|
feature_names_in_ |
names of the columns seen in fitting, if they were all strings. |
Examples:
>>> import pandas as pd
>>> from logit_encode import LogitEncoder
>>> X = pd.DataFrame({'color': ['red', 'blue', 'red', 'green'] * 25})
>>> y = pd.Series([1, 0, 0, 1] * 25)
>>> encoder = LogitEncoder(encoding = 'log_odds', cv = None)
>>> encoded = encoder.fit_transform(X, y)
>>> encoded['color'].round(2).abs().unique().tolist()
[0.0, 2.29]
>>> table = encoder.get_mapping('color').round(2) + 0.0
>>> table
color
category
red 0.00
blue -2.29
green 2.29
<missing> 0.00
<unknown> 0.00
>>> recovered = encoder.inverse_transform(encoder.transform(X))
>>> recovered['color'][:4].tolist()
['red', 'blue', 'red', 'green']
Stores the parameters without validating them, as sklearn requires.
The parameters are checked when the encoder is fit. They can be
passed by position, in the same order as category_encoders'
TargetEncoder for the parameters the two share.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose
|
int
|
verbosity of the output. 0 for none. |
0
|
cols
|
list[Any] | str | None
|
columns to encode. If None, every object, string, and
categorical column is encoded, as in |
None
|
drop_invariant
|
bool
|
whether to drop encoded columns with no variance. |
False
|
return_df
|
bool
|
whether |
True
|
handle_missing
|
Any
|
how to encode missing values: 'value' (treat them
as a category, or use the prior if none were seen in
fitting), 'return_nan', 'error', a number, or a callable as
in |
'value'
|
handle_unknown
|
Any
|
how to encode categories not seen in fitting:
'value' (the prior), 'return_nan', 'error', a number, or a
callable as in |
'value'
|
encoding
|
Encoding
|
'log_odds', 'coefficient', or 'marginal_effect'. |
'log_odds'
|
model
|
Model
|
'joint' (one logit model with every column) or 'univariate' (a logit model for each column). |
'joint'
|
backend
|
Backend
|
'sklearn' or 'statsmodels'. statsmodels builds a dense design matrix, so sklearn is much faster for columns with many categories. |
'sklearn'
|
C
|
float | None
|
inverse strength of the penalty on the coefficients, as in
|
1.0
|
l1_ratio
|
float
|
share of the penalty that is L1 (lasso) rather than L2 (ridge), from 0 to 1. |
0.0
|
cv
|
int | None
|
number of folds for cross-fitting the training rows, or None to encode them with the model fit on all of them. |
5
|
reference
|
Reference
|
how to choose each column's reference level, which has a coefficient of 0: 'most_frequent', 'first' (the first category seen), or None (no reference level, so every category gets a dummy and coefficients are relative to the intercept). |
'most_frequent'
|
interactions
|
list[tuple[Any, ...]] | None
|
combinations of columns (any columns of X) to encode as one more categorical column each, such as [('state', 'county')], keeping their member columns. Each is named by joining its columns' names with '|', and a row with a missing value in any of them has a missing value in the combination. |
None
|
return_uncertainty
|
bool
|
whether to add each encoded value's standard
error (' |
False
|
max_iter
|
int
|
largest number of solver iterations. |
5000
|
n_jobs
|
int | None
|
number of parallel jobs for fitting the univariate models
and the cross-fitting folds, as in joblib. None means 1
unless in a |
None
|
random_state
|
int | RandomState | None
|
seed for shuffling the cross-fitting folds. |
None
|
min_group_size
|
float | None
|
as in |
None
|
min_group_name
|
str | None
|
name of the lumped group. If None, the lumped categories' names are joined (in sorted order) with '_'. |
None
|
combine_min_nan_groups
|
bool | str | None
|
whether missing values join the lumped group: True (if they are themselves too few, the default for None), 'force' (always), or False (never). |
None
|
composite_cols
|
list[tuple[Any, ...]] | None
|
as in |
None
|
keep_components
|
bool
|
whether the members of |
False
|
Source code in src/logit_encode/logit_encoder.py
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
invariant_cols
property
¶
Returns invariant_cols_, under category_encoders' name.
Returns:
| Type | Description |
|---|---|
list[Any]
|
The output columns dropped by |
mapping
property
¶
Returns mapping_, under category_encoders' name.
Returns:
| Type | Description |
|---|---|
dict[Any, Series | DataFrame]
|
The fitted mapping from ordinal codes to encoded values. |
ordinal_encoder
property
¶
Returns ordinal_encoder_, under category_encoders' name.
Returns:
| Type | Description |
|---|---|
OrdinalEncoder
|
The fitted ordinal encoder. |
fit(X, y=None, **fit_params)
¶
Fits the encoder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Any
|
training data, as a DataFrame or a two-dimensional array. |
required |
y
|
Any
|
training outcome. |
None
|
**fit_params
|
Any
|
unused; accepted for sklearn compatibility. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if the inputs are invalid. |
Returns:
| Type | Description |
|---|---|
BaseEncoder
|
The fitted encoder. |
Source code in src/logit_encode/utils.py
fit_transform(X, y=None, **fit_params)
¶
Fits the encoder and encodes the training data with its outcome.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Any
|
training data. |
required |
y
|
Any
|
training outcome. |
None
|
**fit_params
|
Any
|
passed to |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Returns:
| Type | Description |
|---|---|
DataFrame | ndarray
|
The encoded training data. |
Source code in src/logit_encode/utils.py
get_feature_names()
¶
Returns the output column names (deprecated, as in sklearn).
Kept for code written for category_encoders, which also deprecates
it.
Returns:
| Type | Description |
|---|---|
ndarray
|
The same names as |
Source code in src/logit_encode/utils.py
get_feature_names_in()
¶
Returns the names of the columns seen in fitting.
As in category_encoders, these are the DataFrame's column labels,
or 0, 1, ... for an array.
Returns:
| Type | Description |
|---|---|
ndarray
|
The input columns' labels. |
Source code in src/logit_encode/utils.py
get_feature_names_out(input_features=None)
¶
Returns the names of the transformed columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_features
|
Any
|
names of the input columns, or None to use the
output's column labels, as |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The output column names, without the columns dropped by |
ndarray
|
|
Source code in src/logit_encode/utils.py
get_mapping(column=None)
¶
Returns tables of each category's encoded values.
Each table is indexed by a column's categories as they appear in the
data (a missing value seen in fitting is its own category, NaN, and
categories lumped by min_group_size appear as their group). Its
columns are the output columns that transform makes from that
column, with the same names: one value column per modeled class and,
if return_uncertainty is True, their standard errors and the
category's number of training rows. Unless handle_unknown or
handle_missing is 'error', a row labeled '
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
Any
|
an encoded column (or the name of an interaction or composite column), or None for every one. |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
if |
Returns:
| Type | Description |
|---|---|
dict[Any, DataFrame] | DataFrame
|
The table for |
dict[Any, DataFrame] | DataFrame
|
table. |
Source code in src/logit_encode/logit_encoder.py
inverse_transform(X)
¶
Converts encoded data back to its categories.
Each row's encoded values for a column are matched to the category
with the same values (see get_mapping). This works for the output
of transform without y. It cannot recover training rows encoded
by fit_transform (or transform with y), which are cross-fitted
and so have values that no category has, nor categories that were
unknown in fitting or lumped by min_group_size (which come back as
their group). Values that match no category, or more than one, come
back missing, with a warning. Columns that composite_cols dropped
are recovered from their composite column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Any
|
encoded data, with the columns that |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Returns:
| Type | Description |
|---|---|
DataFrame | ndarray
|
The data with its original columns: categories for the encoded |
DataFrame | ndarray
|
columns, and the other columns unchanged. |
Source code in src/logit_encode/logit_encoder.py
transform(X, y=None, override_return_df=False)
¶
Encodes data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Any
|
data to encode. |
required |
y
|
Any
|
outcome of |
None
|
override_return_df
|
bool
|
whether to return a DataFrame regardless of
|
False
|
Returns:
| Type | Description |
|---|---|
DataFrame | ndarray
|
The encoded data. |