Skip to main content

Credit + regularized logistic: the imputation example

glmnet rejects NAs and factors outright, so every stage materializes: impute, encode, filter, normalize. It is the fullest chain of the six. Ported from recipes ‘Simple example’ vignette + Max Kuhn’s applied-ML workshop pattern (reconstructed; see the side-by-side for provenance).

Compare with R: side-by-side R ↔︎ Python · R original: test roc_auc 0.844, accuracy 0.806.

THE IMPUTATION EXAMPLE, and (after concrete-KNN) the second-most portable:
the whole impute/other/dummy/zv/normalize recipe ports 1:1.

PARITY NOTES:
 - step_other(threshold = 0.05, other = "infrequent") -> StepOther(...,
   threshold=0.05, other_level="infrequent"). credit_data's Home column
   already HAS a level named "other", which is why the R run pools into
   "infrequent"; StepOther warns if the pooled-level name collides with an
   existing level.
 - Model mapping: logistic_reg(penalty = tune(), mixture = 1) + glmnet ->
   LogisticRegression(l1_ratio=1.0, solver="liblinear") with C = 1/(n*lambda):
   glmnet minimizes MEAN loss + lambda*penalty; sklearn minimizes
   C*TOTAL loss + penalty. (A first draft used C = 1/lambda: off by a
   factor of n; the giveaway was best-C pinning to the grid edge.)
 - roc_auc event level pinned: Status maps to bad=1 (R scores "bad", the
   first factor level).

Docs version loads the dataset from mlfeatures.data; the research originals export these datasets from R’s modeldata at first run.

Specify

The order of the steps matters here. Missing values are imputed first (median for numeric columns, mode for nominal ones), since later steps cannot handle nulls. Rare levels are then pooled, the nominal columns dummy-encoded, any constant columns dropped, and the numeric columns normalized so the lasso penalty treats them equally. The penalty strength is tuned over a grid.

import numpy as np
import polars as pl
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
from sklearn.pipeline import Pipeline

from mlfeatures import (Recipe, RecipeTransformer, StepDropZeroVariance, StepDummy,
                   StepImputeMedian, StepImputeMode, StepNormalize, StepOther)
from mlfeatures import Selectors as s

# ── Data + split

from mlfeatures.data import credit  # 4,454 x 14, NAs
credit = credit.with_columns(
    (pl.col("Status") == "bad").cast(pl.Int8).alias("Status")  # event = bad
)

credit_train, credit_test = train_test_split(
    credit, train_size=0.75, stratify=credit["Status"],
    random_state=55
)

# ── Recipe: impute -> other -> dummy -> filter -> normalize

credit_rec = (
    Recipe(data=credit_train, target="Status")
    .add(StepImputeMedian(s.numeric_features()))
    .add(StepImputeMode(s.nominal_features()))
    .add(StepOther(s.nominal_features(), threshold=0.05, other_level="infrequent"))
    .add(StepDummy(s.nominal_features()))
    .add(StepDropZeroVariance(s.features()))
    .add(StepNormalize(s.numeric_features()))
)

# ── Model + workflow + penalty tuning

pipe = Pipeline([
    ("recipe", RecipeTransformer(credit_rec)),
    # sklearn 1.8+ adopted glmnet's own vocabulary: l1_ratio IS mixture
    # (mixture = 1 -> l1_ratio = 1.0, pure lasso)
    ("model", LogisticRegression(l1_ratio=1.0, solver="liblinear",
                                 max_iter=5000)),
])

# glmnet grid: lambda 10^-5 .. 10^-1  ->  sklearn C = 1/(n_train * lambda)
lambdas = np.logspace(-5, -1, 20)
param_grid = {"model__C": 1.0 / (credit_train.height * lambdas)}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=4943)

Fit

Each fold re-estimates the imputation values, pooled levels, and scaling from its own training portion.

X_train = credit_train.drop("Status")
y_train = credit_train["Status"]
search = GridSearchCV(pipe, param_grid, cv=cv, scoring="roc_auc", refit=True)
search.fit(X_train, y_train)
fitted = credit_rec.fit(credit_train)     # the recipe alone

Report

The transformed head has no nulls and no string columns left. The best penalty is chosen by cross-validated ROC AUC, then scored on the holdout set.

print(f"--- best C: {search.best_params_['model__C']:.3g} "
      f"(cv roc_auc {search.best_score_:.3f}) ---")
print("\n--- transformed training head (imputed, encoded, scaled) ---")
print(fitted.transform(credit_train).head())

# ── Holdout metrics

X_test = credit_test.drop("Status")
y_test = credit_test["Status"]
prob = search.predict_proba(X_test)[:, 1]
print(f"\ntest roc_auc: {roc_auc_score(y_test, prob):.3f}   "
      f"accuracy: {accuracy_score(y_test, search.predict(X_test)):.3f}")
# R run result for comparison: test roc_auc 0.844, accuracy 0.806
--- best C: 1.01 (cv roc_auc 0.833) ---

--- transformed training head (imputed, encoded, scaled) ---
shape: (5, 21)
┌────────┬───────────┬───────────┬──────────┬───┬────────────┬────────────┬────────────┬───────────┐
│ Status ┆ Seniority ┆ Time      ┆ Age      ┆ … ┆ Records_ye ┆ Job_freela ┆ Job_infreq ┆ Job_parti │
│ ---    ┆ ---       ┆ ---       ┆ ---      ┆   ┆ s          ┆ nce        ┆ uent       ┆ me        │
│ i8     ┆ f64       ┆ f64       ┆ f64      ┆   ┆ ---        ┆ ---        ┆ ---        ┆ ---       │
│        ┆           ┆           ┆          ┆   ┆ f64        ┆ f64        ┆ f64        ┆ f64       │
╞════════╪═══════════╪═══════════╪══════════╪═══╪════════════╪════════════╪════════════╪═══════════╡
│ 1      ┆ -0.857996 ┆ -0.721186 ┆ -1.2978  ┆ … ┆ -0.451637  ┆ -0.542203  ┆ -0.204412  ┆ 2.989615  │
│ 0      ┆ -0.857996 ┆ 0.924143  ┆ -0.29832 ┆ … ┆ 2.213502   ┆ -0.542203  ┆ -0.204412  ┆ -0.334391 │
│ 1      ┆ -0.615878 ┆ -1.543851 ┆ 0.882882 ┆ … ┆ -0.451637  ┆ -0.542203  ┆ -0.204412  ┆ -0.334391 │
│ 0      ┆ 1.68424   ┆ -0.721186 ┆ 1.155468 ┆ … ┆ -0.451637  ┆ 1.843776   ┆ -0.204412  ┆ -0.334391 │
│ 0      ┆ 0.71577   ┆ 0.924143  ┆ 0.337712 ┆ … ┆ -0.451637  ┆ -0.542203  ┆ -0.204412  ┆ -0.334391 │
└────────┴───────────┴───────────┴──────────┴───┴────────────┴────────────┴────────────┴───────────┘

test roc_auc: 0.830   accuracy: 0.794