Skip to content

logit-encode

Version PyPI Latest Release GitHub Latest Release
Status Build Status Code Coverage Development Status Project Stability
Documentation Hosted By
Tools Documentation Linter Type Checker Dependency Manager Pre-commit CI Editor Settings Repository Template Dependency Maintainer
Compatibility Compatible Python Versions Linux MacOS Windows
Stats PyPI Download Rate (per month) GitHub Stars GitHub Contributors GitHub Issues GitHub Forks

What is logit-encode?

logit-encode encodes categorical features with values from a logit (logistic regression) model of a binary or multiclass outcome. Each category is replaced by one of:

  • its log odds: the average log odds of the outcome for rows in that category,
  • its coefficient: the log odds ratio of the outcome for that category against a reference category, or
  • its marginal effect: the average change in the probability of the outcome from moving a row from the reference category to that category.

The logit model can be fit with every column at once (model = 'joint', the default), so that each column's values are adjusted for the others, or separately for each column (model = 'univariate'). Either scikit-learn or statsmodels can fit it.

Why use logit-encode?

  • A full scikit-learn transformer. LogitEncoder works in pipelines, column transformers, cross-validation, and grid searches, supports set_output and get_feature_names_out, and passes scikit-learn's check_estimator.
  • A drop-in for category_encoders. It takes the same parameters (including min_group_size and composite_cols), has the same attributes and methods, and handles inputs the same way as the encoders in category_encoders, so it can replace TargetEncoder without other changes.
  • Readable and reversible. get_mapping gives a table of each category's encoded values, and inverse_transform converts encoded data back to its categories.
  • No target leakage. Like scikit-learn's TargetEncoder, it cross-fits the training rows, so each row is encoded by a model that never saw its outcome.
  • Shrinkage for rare categories. The model's L2 (or L1) penalty pulls categories with few rows toward the reference category.
  • Interpretable values. The encodings are quantities that analysts already report from logit models.
  • Multiclass outcomes. An outcome with K classes gets K - 1 columns per categorical column, one for each class against the most frequent class.
  • Uncertainty columns. return_uncertainty = True adds each value's standard error and each category's number of training rows, so a model can discount rare categories.
  • Interactions. interactions = [('state', 'county')] encodes combinations of columns as columns of their own.
  • Fast. The model is fit on the distinct combinations of categories and outcome, weighted by their counts, which gives the same estimates as fitting on every row.

Comparison with sklearn and category-encoders

The plot and table compare the best LogitEncoder setting, the best category_encoders encoder, and scikit-learn's TargetEncoder on each of the nine benchmark datasets where every encoder ran: tic-tac-toe, credit-approval, credit-g, dresses-sales, colic, churn, telco-churn, adult, and bank-marketing (all from OpenML). Each dot is the area under the ROC curve (AUC) on held-out data, averaged over five cross-validation folds and three classifiers (logistic regression, gradient boosting, and random forest); higher is better. Every dataset is on the same scale, from 0.5 to 1, so encoders with similar AUCs overlap; the table below gives the exact values and names each dataset's best encoders.

Dot plot of each library's best encoder's mean AUC on each of the nine datasets

Dataset Best LogitEncoder setting LogitEncoder AUC Best category_encoders encoder category_encoders AUC TargetEncoder AUC
tic-tac-toe log odds, joint 0.998 Hashing 0.998 0.928
credit-approval log odds, univariate + uncertainty 0.931 Gray 0.930 0.929
credit-g log odds, univariate 0.785 CountTarget 0.791 0.784
dresses-sales log odds, univariate 0.633 GLMM 0.636 0.614
colic log odds, univariate 0.904 Summary 0.917 0.916
churn marginal effects, joint 0.903 CatBoost 0.900 0.902
telco-churn log odds, joint 0.840 CatBoost 0.837 0.839
adult log odds, joint 0.915 CatBoost 0.912 0.914
bank-marketing marginal effects, joint 0.919 Helmert 0.921 0.918

The benchmarks compare every encoder, including on four datasets with thousands of categories per column, where LogitEncoder has the highest AUC by a wider margin.

Getting started

Requirements

Python 3.11 or newer, with scikit-learn 1.8 or newer, statsmodels, and category_encoders.

Installation

To install logit-encode, use pip:

pip install logit-encode

Usage

import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

from logit_encode import LogitEncoder

X = pd.DataFrame({
    'color': ['red', 'blue', 'red', 'green', 'blue', 'red'] * 50,
    'size': ['S', 'M', 'L', 'M', 'S', 'L'] * 50})
y = pd.Series([1, 0, 1, 0, 0, 1] * 50)

# Encode the training data (cross-fitted) and new data.
encoder = LogitEncoder(encoding = 'log_odds')
encoded = encoder.fit_transform(X, y)
new = encoder.transform(pd.DataFrame({'color': ['red'], 'size': ['XL']}))

# Or use it in a pipeline.
pipeline = make_pipeline(
    LogitEncoder(encoding = 'marginal_effect', return_uncertainty = True),
    LogisticRegression())
scores = cross_val_score(pipeline, X, y, scoring = 'roc_auc')

The tutorial explains each option.

Contributing

Contributors are always welcome. Feel free to grab an issue to work on or make a suggested improvement. If you wish to contribute, please read the Contribution Guide and Code of Conduct.

Similar Projects

  • category_encoders has more than 20 encoders, including target, weight of evidence, and generalized linear mixed model (GLMMEncoder) encoders. LogitEncoder follows its interface.
  • scikit-learn's TargetEncoder cross-fits shrunken category means, as LogitEncoder cross-fits logit models.

Citation

If you use logit-encode in your work, please cite it. GitHub's "Cite this repository" button uses the same information, from CITATION.cff.

Yung, Corey Rayburn. 2026. logit-encode: Encoding Categorical Features with Logit Models (version 0.1.1). Computer software. https://github.com/WithPrecedent/logit-encode.

@software{yung_logit_encode_2026,
  author = {Yung, Corey Rayburn},
  title = {{logit-encode}: Encoding Categorical Features with Logit Models},
  year = {2026},
  version = {0.1.1},
  license = {Apache-2.0},
  url = {https://github.com/WithPrecedent/logit-encode}
}

Acknowledgments

The benchmarks use datasets from OpenML.

License

Use of this repository is authorized under the Apache Software License 2.0.