KUHN · credit_data + glmnet logistic: R vs Python, line-matched

Identical section banners and shared descriptions in both scripts; ochre DIFF comments (Python side only, R holds a blank #) explain what changes; red = mlfeatures gap. R: roc_auc 0.844 / acc 0.806 · Python ran: 0.830 / 0.794. The whole recipe ported 1:1, step_other included.

R: tidymodels

# Setup --------------------------------------------------------------------
# Load the modeling stack.

library(tidymodels)











# Data + split -------------------------------------------------------------
# credit_data: 4,454 x 14 with NAs in several features, which makes it
# the imputation example.
#
#
#

data(credit_data, package = "modeldata")

set.seed(55)
credit_split <- initial_split(credit_data, strata = Status)
credit_train <- training(credit_split)
credit_test  <- testing(credit_split)

# Recipe -------------------------------------------------------------------
# impute -> collapse rare levels -> dummy -> filter -> normalize.
#
#
#
#

credit_rec <-
  recipe(Status ~ ., data = credit_train) %>%
  step_impute_median(all_numeric_predictors()) %>%
  step_impute_mode(all_nominal_predictors()) %>%
  step_other(all_nominal_predictors(), threshold = 0.05,
             other = "infrequent") %>%  # dodges the "other" collision
  step_dummy(all_nominal_predictors()) %>%
  step_zv(all_predictors()) %>%
  step_normalize(all_numeric_predictors())


# Model + penalty tuning ---------------------------------------------------
# Lasso-penalized logistic; tune the penalty on stratified 5-fold CV.
#
#
#
#
#

glmnet_spec <-
  logistic_reg(penalty = tune(), mixture = 1) %>%
  set_engine("glmnet")

credit_wflow <- workflow(credit_rec, glmnet_spec)

set.seed(4943)
credit_folds <- vfold_cv(credit_train, v = 5, strata = Status)
penalty_grid <- grid_regular(penalty(range = c(-5, -1)),
                             levels = 20)
credit_res <- tune_grid(credit_wflow, resamples = credit_folds,
                        grid = penalty_grid,
                        metrics = metric_set(roc_auc))




# Finalize + proof + metrics -----------------------------------------------
# Refit the best penalty; transform the training head; score the test set.

credit_best <- select_best(credit_res, metric = "roc_auc")
final_res <- credit_wflow %>%
  finalize_workflow(credit_best) %>%
  last_fit(credit_split, metrics = metric_set(roc_auc, accuracy))

prep(credit_rec, training = credit_train) %>%
  bake(new_data = NULL) %>% head()
collect_metrics(final_res)  # run: roc_auc 0.844, accuracy 0.806


Python: mlfeatures + sklearn

# Setup --------------------------------------------------------------------
# Load the modeling stack.

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 -------------------------------------------------------------
# credit_data: 4,454 x 14 with NAs in several features, which makes it
# the imputation example.
# DIFF: credit ships in mlfeatures.data (exported from modeldata::credit_data).
# DIFF: sklearn wants a numeric target; Status maps to bad=1. R scores the
# first factor level ("bad"): same event, made explicit here.

from mlfeatures.data import credit
credit = credit.with_columns(
    (pl.col("Status") == "bad").cast(pl.Int8).alias("Status"))
credit_train, credit_test = train_test_split(
    credit, train_size=0.75, stratify=credit["Status"],
    random_state=55)

# Recipe -------------------------------------------------------------------
# impute -> collapse rare levels -> dummy -> filter -> normalize.
# DIFF: StepOther = step_other. credit_data's Home column already HAS a
# level named "other", so the pooled level is "infrequent"; StepOther
# warns if that name collides with an existing level.
# DIFF: everything else ports 1:1.

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 + penalty tuning ---------------------------------------------------
# Lasso-penalized logistic; tune the penalty on stratified 5-fold CV.
# DIFF: sklearn 1.8+ speaks glmnet: l1_ratio IS mixture (1.0 = lasso).
# DIFF: the glmnet mapping is C = 1/(n*lambda), NOT 1/lambda; glmnet
# minimizes MEAN loss + lambda*penalty, sklearn C*TOTAL loss + penalty.
# Using 1/lambda is an easy mistake; the giveaway is the best C pinning to
# the edge of the grid.

pipe = Pipeline([
    ("recipe", RecipeTransformer(credit_rec)),
    ("model", LogisticRegression(l1_ratio=1.0, solver="liblinear",
                                 max_iter=5000)),
])

X_train = credit_train.drop("Status")
y_train = credit_train["Status"]

lambdas = np.logspace(-5, -1, 20)
param_grid = {"model__C": 1 / (credit_train.height * lambdas)}
cv = StratifiedKFold(n_splits=5, shuffle=True,
                     random_state=4943)
search = GridSearchCV(pipe, param_grid, cv=cv,
                      scoring="roc_auc", refit=True)
search.fit(X_train, y_train)

# Finalize + proof + metrics -----------------------------------------------
# Refit the best penalty; transform the training head; score the test set.

# refit already happened (refit=True)
fitted = credit_rec.fit(credit_train)
fitted.transform(credit_train).head()

X_test = credit_test.drop("Status")
y_test = credit_test["Status"]
prob = search.predict_proba(X_test)[:, 1]
print(roc_auc_score(y_test, prob),
      accuracy_score(y_test, search.predict(X_test)))
# ran: roc_auc 0.829, accuracy 0.796 (R: 0.844 / 0.806)