Skip to main 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.

Metadata

Release files for logit-encode 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for logit-encode 0.1.1
File Size Uploaded Provenance Actions
logit_encode-0.1.1.tar.gz 780.8 kB Without provenance Details for logit_encode-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for logit-encode 0.1.1
File Interpreter ABI Platform Actions
logit_encode-0.1.1-py3-none-any.whl Python 3 none any Details for logit_encode-0.1.1-py3-none-any.whl

Total release size: 816.9 kB

Release files / logit_encode-0.1.1.tar.gz

Download URL logit_encode-0.1.1.tar.gz
Size 780.8 kB
Tags Source
SHA-256 checksum
How to use checksums
05e55d1aa547bba3fb79f16021b7d28678e9ff8b6c2dcd676dfb6c5f905e4fb9
BLAKE2b-256 checksum
How to use checksums
79ed9dac59ecd74f50fc972860a5cf5f2415103017e9ee8c7b85168ec297c274
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / logit_encode-0.1.1-py3-none-any.whl

Download URL logit_encode-0.1.1-py3-none-any.whl
Size 36.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8c459a54a8fa989747908a7135a9ea3dba9aec578df36ba9404946dfd12ec655
BLAKE2b-256 checksum
How to use checksums
419a620dc05072aba5e2af323bf244aedcceaef5cb2eb746f8d0da659a7602f9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for logit-encode 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page