Recipes¶
In a pipeline¶
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.pipeline import make_pipeline
from logit_encode import LogitEncoder
pipeline = make_pipeline(
LogitEncoder(encoding = 'log_odds'),
HistGradientBoostingClassifier())
pipeline.fit(X_train, y_train)
probabilities = pipeline.predict_proba(X_test)[:, 1]
With other transformers¶
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
preprocess = ColumnTransformer([
('categories', LogitEncoder(), ['color', 'size']),
('numbers', StandardScaler(), ['price'])])
preprocess.set_output(transform = 'pandas')
Tuning the encoder¶
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
pipeline = make_pipeline(LogitEncoder(), LogisticRegression())
search = GridSearchCV(
pipeline,
{'logitencoder__encoding': ['log_odds', 'marginal_effect'],
'logitencoder__model': ['univariate', 'joint'],
'logitencoder__C': [0.1, 1.0, 10.0]},
scoring = 'roc_auc')
search.fit(X_train, y_train)
Interpretable encodings¶
To report the categories' effects rather than to feed a classifier, fit without cross-fitting and, for unbiased (but unshrunken) estimates, without a penalty:
encoder = LogitEncoder(
encoding = 'marginal_effect',
model = 'joint',
C = None,
cv = None).fit(X, y)
With statsmodels¶
The statsmodels backend builds a dense design matrix, so keep it to columns with up to a few thousand categories.
Lasso shrinkage¶
An L1 penalty sets weak categories' coefficients to 0, merging them with the reference category: