Skip to content

Advanced User Guide

The model

For the columns in a model (one column in a univariate model, all of them in a joint model), each category except the column's reference category gets a dummy. The logit model is

log(P(y = 1) / P(y = 0)) = a + sum over columns j of b[j, category of row in j]

with b equal to 0 for reference categories. It is fit by minimizing the summed log loss plus 1 / C times the elastic net penalty l1_ratio * |b| + (1 - l1_ratio) / 2 * b'b. The intercept a is not penalized.

For a column j and category l, let base(i) be row i's linear predictor without column j's term. Then:

  • coefficient is b[j, l],
  • log_odds is b[j, l] plus the average of base(i) over the training rows, and
  • marginal_effect is the average over the training rows of expit(base(i) + b[j, l]) - expit(base(i)).

The marginal effect is the average discrete change in the probability of the outcome from setting column j to category l rather than to the reference category, with the other columns as observed. This is the effect that Stata's margins, dydx() reports for a factor variable. It differs from statsmodels' get_margeff(dummy = True) on hand-made dummies, which changes one dummy at a time and so, for rows in another non-reference category, compares rows with two categories switched on at once. The two agree for two-category columns.

Outcomes with more than two classes

An outcome with K classes is modeled with K - 1 baseline-category logits, one for each class k against the reference class r: log(P(y = k) / P(y = r)) = a[k] + sum of b[k, j, category]. Each is fit as a binary logit on the rows whose class is k or r (Begg and Gray, 1984). Without a penalty, these separate fits estimate the same coefficients as a multinomial logit (less efficiently), and they let the sklearn and statsmodels backends fit every model the same way, so the backends still agree.

The log odds and coefficients for class k come from its own logit. The marginal effects use all of the logits together: the probability of class k is exp(eta[k]) / (1 + sum over classes j of exp(eta[j])), with the reference class's eta fixed at 0, and the marginal effect is the average change in that probability from setting the column to a category rather than to its reference category. Without a penalty, in a univariate model, this is the difference between the category's share of class k and the reference category's share.

Standard errors

With return_uncertainty = True, each value's standard error comes from the inverse of the penalized information matrix of the model it came from, X'WX + ridge * I (with W the weights w * p * (1 - p), and ridge = (1 - l1_ratio) / C on the dummies only). This is the usual approximation for a penalized logit; the L1 part of an elastic net penalty is ignored.

The information matrix is restricted to the intercept and one column's dummies, holding the other columns' coefficients fixed. A column's dummies never share rows, so this is an "arrowhead" matrix whose inverse has a closed form. With a the intercept's information, u a dummy's information (which it shares with the intercept), d = u + ridge, and s = a - sum(u^2 / d) over the column's dummies:

  • a coefficient's variance is 1 / d + u^2 / (d^2 s),
  • the intercept plus a coefficient (the log odds) has variance 1 / d + (1 - u / d)^2 / s, and
  • the reference category's log odds (the intercept) has variance 1 / s.

For a univariate model, the restriction changes nothing, so the errors are exact: without a penalty, they equal statsmodels' Logit standard errors. For a joint model, ignoring the information that the columns share is an approximation, which understates the errors of columns that overlap. For a joint model's log odds, the average of the other columns' terms is treated as the intercept. Marginal effects' errors use the delta method, with the derivatives of the average change in each class's probability with respect to the category's coefficients for every class.

A category the model did not see has no rows, so u = 0 and its coefficient's variance is 1 / ridge: the spread that the penalty allows.

Aggregated fitting

A logit model's log likelihood is a sum over rows, and rows with the same categories and outcome contribute the same term. So the model is fit on the distinct combinations of category codes and outcome, weighted by their counts. This gives exactly the same estimates as fitting on every row, and it is much faster when the categories repeat: a univariate model of a column with k categories never has more than 2k rows, whatever the size of the data.

scikit-learn's SAGA solver, which fits L1 penalties, takes smaller steps the larger the largest sample weight is, and it diverges on large frequency weights. So the weights are divided by their largest value, and C is multiplied by it, which leaves the objective unchanged. statsmodels' elastic net divides the log likelihood by the number of (distinct) rows rather than by the summed weights, so its penalty is scaled to match scikit-learn's.

Parallel fitting

n_jobs fits the univariate models of the columns, and the models of the cross-fitting folds, in parallel with joblib. Use it with a joblib.parallel_config context to choose the backend.

scikit-learn compatibility

LogitEncoder subclasses logit_encode.utils.BaseEncoder and SupervisedTransformerMixin, which mirror the classes of the same names in category_encoders.utils but follow scikit-learn's estimator contract:

  • __init__ only stores the parameters, and fit never changes them (the columns that were encoded are in cols_).
  • Fitted attributes end with an underscore (mapping_, ordinal_encoder_, classes_, reference_class_, modeled_classes_, interaction_cols_, composite_members_, min_group_lumping_, n_iter_, cols_, invariant_cols_, feature_names_out_, n_features_in_, and feature_names_in_, plus error_mapping_ and count_mapping_ with return_uncertainty = True).
  • get_feature_names_out names the extra columns that multiclass outcomes, uncertainty, interactions, and composite columns add, and follows input_features.
  • Inputs are validated as scikit-learn validates them, with the same error messages, and a DataFrame's column names are checked between fit and transform.
  • get_feature_names_out and set_output work, so it can be used in a ColumnTransformer with pandas output.

The test suite runs scikit-learn's check_estimator on several settings. With cross-fitting on, two checks are expected to fail because they compare fit_transform with fit().transform(), which differ by design (as they do for scikit-learn's own TargetEncoder).

Drop-in for category_encoders

LogitEncoder can replace any supervised category_encoders encoder, such as TargetEncoder, without other changes to the code around it. The test suite fits both on the same data in many ways (DataFrames, Series, arrays, lists, every handle_missing and handle_unknown option, drop_invariant, composite_cols, and min_group_size) and checks that they return the same kind of output with the same columns and feature names.

  • Parameters. It takes TargetEncoder's parameters in the same order (by position or by name), except the ones specific to target encoding (min_samples_leaf, smoothing, and hierarchy): verbose, cols, drop_invariant, return_df, handle_missing, handle_unknown, and then, by name, min_group_size, min_group_name, combine_min_nan_groups, composite_cols, and keep_components. min_group_size lumps categories with category_encoders' own rule, and composite_cols joins columns with its own code, so they make the same groups.
  • Attributes and methods. mapping, ordinal_encoder, invariant_cols, and feature_names_out_ are there under category_encoders' names (as aliases of the sklearn-style attributes), as are get_feature_names_out, get_feature_names_in, the deprecated get_feature_names, and transform's y and override_return_df arguments.
  • Columns. By default it encodes the same columns: object, string, and categorical ones. Without input_features, get_feature_names_out returns the output's column labels, as category_encoders does (so 0, 1, ... for an array).
  • Inputs. It accepts DataFrames, Series, arrays, and lists (a flat list is one column). A DataFrame given to transform may have extra columns, which pass through in place, as long as it has every fitted column in the same order. An array given to transform after fitting on a DataFrame gets the fitted column names by position.

The one difference is that cols keeps the value it was given, as scikit-learn requires of parameters, while category_encoders replaces it with the list of encoded columns when fitting. The encoded columns are in cols_. And because a logit model needs a categorical outcome, LogitEncoder raises an error for a continuous one, where TargetEncoder would encode it.