Skip to content

ENH add L1/enet capable solvers newton-cd and newton-cd-gram to LogisticRegression - #33160

Closed
lorentzenchr wants to merge 10 commits into
scikit-learn:mainfrom
lorentzenchr:logistic_lasso_newton
Closed

lorentzenchr wants to merge 10 commits into
scikit-learn:mainfrom
lorentzenchr:logistic_lasso_newton

Conversation

@lorentzenchr

@lorentzenchr lorentzenchr commented Jan 30, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Contributes to #16637.

What does this implement/fix? Explain your changes.

This PR implements two proximal Newton solvers relying on the available coordinate descent solvers:

  • "newton-cd-gram" uses enet_coordinate_descent_gram
    Good for n_samples >> n_features
  • "newton-cd" uses the other CD-solvers and a special new one for the multinomial case (n_classes >= 3).
    Good for L1 penalties in combination with n_features >> n_samples.

These solvers work for all GLMs, but this PR only makes them available in LogisticRegression.

Why 2 new solvers?

  • They will add L1 penalties to PoissonRegressor etc.
  • For LogisticRegression, there is room for high precision solvers:
    • Currently, the only L1 solver for multiclass is saga.
    • Currently, the only enet solver (L1 + L2 penalty) is saga.
  • Originally, I wanted to combine both into a single one with automatic selection when to use which. This decision, however, is very tricky. So I went with having both options user facing.

AI usage disclosure

No AI usage.

Any other comments?

If we deem these 2 solvers a good addition, we might consider to retire liblinear.

Some further remarks:

  • The development of these 2 solvers took about one year!
  • If you ever develop optimization routines, line search is your friend, better not touch it because of failing tests.

TODO

  • remove python CD multinomial (keep Cython version)
  • Improve doc on solver choice
  • Add changelog
  • Maybe: support float32 in Cython multinomial CD
  • Maybe: openmp thread parallelism for multinomial CD
  • Maybe: try different inner tolerance

Split in multiple smaller PRs:

@lorentzenchr

lorentzenchr commented Jan 30, 2026 •

Copy link
Copy Markdown
Member Author

Benchmarks (only tables, no plots)

C=1 always

L2-penalty on make_regression

python benchmarks/bench_logreg.py --penalty L2 --data make_classification

Summary:

  • For n_samples >> n_features, lbfgs is hard to beat, newton-cd-gram is on par with newton-cholesky.
  • For n_features >> n_samples, newton-cg and lbfgs are fastest, newton-cg shines for larger n_classes.
Details
python benchmarks/bench_logreg.py --penalty L2 --data make_classification
Start simple benchmarks for logistic regression.
dataset from make_classification, tol=1e-5

L2 logistic regression

n_samples=100_000 n_features=10 n_classes=2 l1_ratio=0 tol=1e-05 fit_intercept=False
           saga iterations=    19 in  0.490 seconds at objective= 0.445639712407 converged=True
 newton-cd-gram iterations=     5 in  0.065 seconds at objective= 0.445639776493 converged=True
      newton-cd iterations=     5 in  0.091 seconds at objective= 0.445639776493 converged=True
      liblinear iterations=     6 in  0.151 seconds at objective= 0.445639712400 converged=True
      newton-cg iterations=     5 in  0.071 seconds at objective= 0.445639712480 converged=True
newton-cholesky iterations=     5 in  0.052 seconds at objective= 0.445639712400 converged=True
          lbfgs iterations=    10 in  0.044 seconds at objective= 0.445639712531 converged=True

n_samples=100_000 n_features=10 n_classes=3 l1_ratio=0 tol=1e-05 fit_intercept=False
           saga iterations=    22 in  0.891 seconds at objective= 0.744555623663 converged=True
 newton-cd-gram iterations=     5 in  0.195 seconds at objective= 0.744556718684 converged=True
      newton-cd iterations=     5 in 28.314 seconds at objective= 0.744556574717 converged=True
      newton-cg iterations=     6 in  0.256 seconds at objective= 0.744555623660 converged=True
newton-cholesky iterations=     5 in  0.192 seconds at objective= 0.744555623658 converged=True
          lbfgs iterations=    13 in  0.121 seconds at objective= 0.744555623763 converged=True

n_samples=100_000 n_features=10 n_classes=10 l1_ratio=0 tol=1e-05 fit_intercept=False
           saga iterations=    22 in  1.534 seconds at objective= 2.052023374908 converged=True
 newton-cd-gram iterations=     3 in  0.871 seconds at objective= 2.052025965278 converged=True
      newton-cd was excluded
      newton-cg iterations=     6 in  0.620 seconds at objective= 2.052023374908 converged=True
newton-cholesky iterations=     3 in  0.858 seconds at objective= 2.052023374981 converged=True
          lbfgs iterations=    17 in  0.331 seconds at objective= 2.052023375591 converged=True


n_samples=100_000 n_features=10 n_classes=2 l1_ratio=0 tol=1e-05 fit_intercept=True
           saga iterations=    19 in  0.544 seconds at objective= 0.443020174365 converged=True
 newton-cd-gram iterations=     5 in  0.080 seconds at objective= 0.443020193793 converged=True
      newton-cd iterations=     5 in  0.119 seconds at objective= 0.443020193793 converged=True
      liblinear iterations=     6 in  0.217 seconds at objective= 0.443020174404 converged=True
      newton-cg iterations=     5 in  0.088 seconds at objective= 0.443020174362 converged=True
newton-cholesky iterations=     5 in  0.058 seconds at objective= 0.443020174359 converged=True
          lbfgs iterations=    11 in  0.050 seconds at objective= 0.443020174473 converged=True

n_samples=100_000 n_features=10 n_classes=3 l1_ratio=0 tol=1e-05 fit_intercept=True
           saga iterations=    22 in  0.992 seconds at objective= 0.730294216659 converged=True
 newton-cd-gram iterations=     5 in  0.224 seconds at objective= 0.730295384741 converged=True
      newton-cd iterations=     5 in 84.494 seconds at objective= 0.730295307419 converged=True
      newton-cg iterations=     6 in  0.359 seconds at objective= 0.730294217064 converged=True
newton-cholesky iterations=     5 in  0.222 seconds at objective= 0.730294216655 converged=True
          lbfgs iterations=    18 in  0.228 seconds at objective= 0.730294217872 converged=True

n_samples=100_000 n_features=10 n_classes=10 l1_ratio=0 tol=1e-05 fit_intercept=True
           saga iterations=    21 in  1.438 seconds at objective= 2.035051790796 converged=True
 newton-cd-gram iterations=     4 in  1.349 seconds at objective= 2.035054608162 converged=True
      newton-cd was excluded
      newton-cg iterations=     6 in  0.723 seconds at objective= 2.035051791340 converged=True
newton-cholesky iterations=     4 in  1.286 seconds at objective= 2.035051790796 converged=True
          lbfgs iterations=    27 in  0.658 seconds at objective= 2.035051791438 converged=True


n_samples=100 n_features=1_000 n_classes=2 l1_ratio=0 tol=1e-05 fit_intercept=False
           saga iterations= 9_445 in  6.393 seconds at objective= 0.000747622189 converged=True
 newton-cd-gram iterations=    11 in  2.375 seconds at objective= 0.000690211934 converged=True
      newton-cd iterations=    11 in  0.432 seconds at objective= 0.000690211934 converged=True
      liblinear iterations=    10 in  0.011 seconds at objective= 0.000690226070 converged=True
      newton-cg iterations=    11 in  0.010 seconds at objective= 0.000690224564 converged=True
newton-cholesky iterations=    11 in  0.318 seconds at objective= 0.000690211937 converged=True
          lbfgs iterations=    34 in  0.010 seconds at objective= 0.000690242068 converged=True

n_samples=100 n_features=1_000 n_classes=3 l1_ratio=0 tol=1e-05 fit_intercept=False
           saga iterations= 9_190 in 13.731 seconds at objective= 0.000632550161 converged=True
 newton-cd-gram iterations=    11 in 34.571 seconds at objective= 0.000553831760 converged=True
      newton-cd iterations=    11 in  2.173 seconds at objective= 0.000553831759 converged=True
      newton-cg iterations=    12 in  0.022 seconds at objective= 0.000553831766 converged=True
newton-cholesky iterations=    11 in  4.965 seconds at objective= 0.000553831752 converged=True
          lbfgs iterations=    46 in  0.029 seconds at objective= 0.000553841371 converged=True

n_samples=100 n_features=1_000 n_classes=10 l1_ratio=0 tol=1e-05 fit_intercept=False
           saga iterations= 7_708 in 20.505 seconds at objective= 0.000909330645 converged=True
 newton-cd-gram was excluded
      newton-cd iterations=     5 in  1.887 seconds at objective= 0.000832141978 converged=True
      newton-cg iterations=    11 in  0.033 seconds at objective= 0.000832141822 converged=True
newton-cholesky iterations=     5 in 45.428 seconds at objective= 0.000832141978 converged=True
          lbfgs iterations=    44 in  0.055 seconds at objective= 0.000832145567 converged=True


n_samples=100 n_features=1_000 n_classes=2 l1_ratio=0 tol=1e-05 fit_intercept=True
           saga iterations= 9_445 in  6.186 seconds at objective= 0.000747612698 converged=True
 newton-cd-gram iterations=    11 in  1.925 seconds at objective= 0.000685774795 converged=True
      newton-cd iterations=    11 in  0.371 seconds at objective= 0.000685774795 converged=True
      liblinear iterations=    10 in  0.011 seconds at objective= 0.000690216557 converged=True
      newton-cg iterations=    12 in  0.016 seconds at objective= 0.000685824433 converged=True
newton-cholesky iterations=    11 in  0.340 seconds at objective= 0.000685774799 converged=True
          lbfgs iterations=    34 in  0.010 seconds at objective= 0.000690216298 converged=True

n_samples=100 n_features=1_000 n_classes=3 l1_ratio=0 tol=1e-05 fit_intercept=True
           saga iterations= 9_190 in 12.648 seconds at objective= 0.000632542776 converged=True
 newton-cd-gram iterations=    11 in 33.489 seconds at objective= 0.000550538389 converged=True
      newton-cd iterations=    11 in  6.177 seconds at objective= 0.000550538387 converged=True
      newton-cg iterations=    13 in  0.036 seconds at objective= 0.000550540803 converged=True
newton-cholesky iterations=    11 in  5.381 seconds at objective= 0.000550538380 converged=True
          lbfgs iterations=    55 in  0.033 seconds at objective= 0.000553805757 converged=True

n_samples=100 n_features=1_000 n_classes=10 l1_ratio=0 tol=1e-05 fit_intercept=True
           saga iterations= 7_708 in 20.183 seconds at objective= 0.000909330486 converged=True
 newton-cd-gram was excluded
      newton-cd iterations=     5 in 13.085 seconds at objective= 0.000831703632 converged=True
      newton-cg iterations=    11 in  0.043 seconds at objective= 0.000831718214 converged=True
newton-cholesky iterations=     5 in 48.599 seconds at objective= 0.000831703633 converged=True
          lbfgs iterations=    44 in  0.054 seconds at objective= 0.000832143671 converged=True

L1-penalty on make_regression

python benchmarks/bench_logreg.py --penalty L1 --data make_classification
It is interesting to look at the identification of the support (#non-zero coefficients).

Summary:

  • For n_samples >> n_features, newton-cd-gram is fastest by an order of magnitude!
  • For n_features >> n_samples, newton-cd is fastest by an order of magnitude. Saga does not converge. For n_classes=2, liblinear is fastest but does not correctly identify the support of the coefficients!
Details
Start simple benchmarks for logistic regression.
dataset from make_classification, tol=1e-5

L1 logistic regression

n_samples=10_000 n_features=10 n_classes=2 l1_ratio=1 tol=1e-05 fit_intercept=False
           saga iterations=    94 in  0.151 seconds at objective= 0.493598632171 1 of 10 coefficients are zero. converged=True
 newton-cd-gram iterations=     4 in  0.007 seconds at objective= 0.493598632186 1 of 10 coefficients are zero. converged=True
      newton-cd iterations=     4 in  0.071 seconds at objective= 0.493598632186 1 of 10 coefficients are zero. converged=True
      liblinear iterations=    18 in  0.841 seconds at objective= 0.493598632193 1 of 10 coefficients are zero. converged=True

n_samples=10_000 n_features=10 n_classes=3 l1_ratio=1 tol=1e-05 fit_intercept=False
           saga iterations=   284 in  0.823 seconds at objective= 0.752265142327 12 of 30 coefficients are zero. converged=True
 newton-cd-gram iterations=     7 in  0.028 seconds at objective= 0.752265142327 12 of 30 coefficients are zero. converged=True
      newton-cd iterations=     6 in  1.839 seconds at objective= 0.752265385013 11 of 30 coefficients are zero. converged=True

n_samples=10_000 n_features=10 n_classes=10 l1_ratio=1 tol=1e-05 fit_intercept=False
           saga iterations=    90 in  0.541 seconds at objective= 2.052843550141 20 of 100 coefficients are zero. converged=True
 newton-cd-gram iterations=     3 in  0.064 seconds at objective= 2.052843550259 20 of 100 coefficients are zero. converged=True
      newton-cd iterations=     3 in  2.041 seconds at objective= 2.052843550281 20 of 100 coefficients are zero. converged=True


n_samples=10_000 n_features=10 n_classes=2 l1_ratio=1 tol=1e-05 fit_intercept=True
           saga iterations=   118 in  0.182 seconds at objective= 0.483371964711 2 of 10 coefficients are zero. converged=True
 newton-cd-gram iterations=     4 in  0.007 seconds at objective= 0.483371964743 2 of 10 coefficients are zero. converged=True
      newton-cd iterations=     4 in  0.102 seconds at objective= 0.483371964743 2 of 10 coefficients are zero. converged=True
      liblinear iterations=    20 in  1.027 seconds at objective= 0.483372014930 2 of 10 coefficients are zero. converged=True

n_samples=10_000 n_features=10 n_classes=3 l1_ratio=1 tol=1e-05 fit_intercept=True
           saga iterations=   256 in  0.713 seconds at objective= 0.746463699001 12 of 30 coefficients are zero. converged=True
 newton-cd-gram iterations=     6 in  0.027 seconds at objective= 0.746463699002 12 of 30 coefficients are zero. converged=True
      newton-cd iterations=     5 in  3.621 seconds at objective= 0.746463699002 12 of 30 coefficients are zero. converged=True

n_samples=10_000 n_features=10 n_classes=10 l1_ratio=1 tol=1e-05 fit_intercept=True
           saga iterations=    94 in  0.603 seconds at objective= 2.037122572899 18 of 100 coefficients are zero. converged=True
 newton-cd-gram iterations=     4 in  0.107 seconds at objective= 2.037122572962 19 of 100 coefficients are zero. converged=True
      newton-cd iterations=     4 in 16.758 seconds at objective= 2.037122572957 18 of 100 coefficients are zero. converged=True


n_samples=100 n_features=1_000 n_classes=2 l1_ratio=1 tol=1e-05 fit_intercept=False
           saga iterations=10_000 in  8.735 seconds at objective= 0.028602745377 857 of 1000 coefficients are zero. converged=False
 newton-cd-gram iterations=     9 in  0.139 seconds at objective= 0.027637570892 922 of 1000 coefficients are zero. converged=True
      newton-cd iterations=     9 in  0.124 seconds at objective= 0.027637570892 922 of 1000 coefficients are zero. converged=True
      liblinear iterations=    16 in  0.007 seconds at objective= 0.027637724430 921 of 1000 coefficients are zero. converged=True

n_samples=100 n_features=1_000 n_classes=3 l1_ratio=1 tol=1e-05 fit_intercept=False
           saga iterations=10_000 in 18.983 seconds at objective= 0.039874689149 2712 of 3000 coefficients are zero. converged=False
 newton-cd-gram iterations=     8 in  1.067 seconds at objective= 0.038025291487 2872 of 3000 coefficients are zero. converged=True
      newton-cd iterations=     8 in  0.456 seconds at objective= 0.038025291522 2873 of 3000 coefficients are zero. converged=True

n_samples=100 n_features=1_000 n_classes=10 l1_ratio=1 tol=1e-05 fit_intercept=False
           saga iterations=10_000 in 42.335 seconds at objective= 0.084736524151 9355 of 10000 coefficients are zero. converged=False
 newton-cd-gram iterations=     7 in 14.178 seconds at objective= 0.082186152799 9668 of 10000 coefficients are zero. converged=True
      newton-cd iterations=     7 in  0.578 seconds at objective= 0.082186152792 9668 of 10000 coefficients are zero. converged=True


n_samples=100 n_features=1_000 n_classes=2 l1_ratio=1 tol=1e-05 fit_intercept=True
           saga iterations=10_000 in  8.678 seconds at objective= 0.028602032434 857 of 1000 coefficients are zero. converged=False
 newton-cd-gram iterations=     9 in  0.172 seconds at objective= 0.027551401346 926 of 1000 coefficients are zero. converged=True
      newton-cd iterations=     9 in  0.138 seconds at objective= 0.027551401346 926 of 1000 coefficients are zero. converged=True
      liblinear iterations=    16 in  0.007 seconds at objective= 0.027637790280 921 of 1000 coefficients are zero. converged=True

n_samples=100 n_features=1_000 n_classes=3 l1_ratio=1 tol=1e-05 fit_intercept=True
           saga iterations=10_000 in 18.468 seconds at objective= 0.039872497547 2712 of 3000 coefficients are zero. converged=False
 newton-cd-gram iterations=     8 in  1.716 seconds at objective= 0.037559529858 2876 of 3000 coefficients are zero. converged=True
      newton-cd iterations=     8 in  0.601 seconds at objective= 0.037559529778 2876 of 3000 coefficients are zero. converged=True

n_samples=100 n_features=1_000 n_classes=10 l1_ratio=1 tol=1e-05 fit_intercept=True
           saga iterations=10_000 in 40.743 seconds at objective= 0.084735943282 9355 of 10000 coefficients are zero. converged=False
 newton-cd-gram iterations=     7 in 19.815 seconds at objective= 0.082083939237 9673 of 10000 coefficients are zero. converged=True
      newton-cd iterations=     7 in  1.316 seconds at objective= 0.082083939236 9673 of 10000 coefficients are zero. converged=True

L1 penalty on 20newsgroup

python benchmarks/bench_logreg.py --penalty L1 --data 20newsgroup

Summary:

  • Saga is faster than newton-cd, but reaches a higher (=worse) objective value and does not correctly identify the support of the coefficients.
Details
Start simple benchmarks for logistic regression.
dataset 20newsgroup, train_samples=4_500, n_features=130_107, n_classes=20, tol=1e-4
           saga iterations=   408 in 50.182 seconds at objective= 1.793818499054 2601427 of 2602140 coefficients are zero. converged=True
      newton-cd iterations=     7 in 95.411 seconds at objective= 1.793812143812 2601431 of 2602140 coefficients are zero. converged=True

@lorentzenchr
lorentzenchr force-pushed the logistic_lasso_newton branch 6 times, most recently from a826b35 to e408c49 Compare January 31, 2026 22:56
@ogrisel

ogrisel commented Feb 2, 2026

Copy link
Copy Markdown
Member

Interesting. Have you tried to check if setting a lower tol value in your benchmark would allow the other l1-penalty capable solvers to recover the correct support or a lower objective value?

@lorentzenchr

Copy link
Copy Markdown
Member Author

Interesting. Have you tried to check if setting a lower tol value in your benchmark would allow the other l1-penalty capable solvers to recover the correct support or a lower objective value?

No, I just set it a bit tighter than the default, tol=1e-5 instead of 1e-4. (Also, I randomly chose C=1 😏)

@lorentzenchr

lorentzenchr commented Feb 6, 2026 •

Copy link
Copy Markdown
Member Author

Benchmark on kick data (binary classification)

L2 penalty C=1, fit_intercept=True, sparse X

X is sparse csr
X_train.shape = (65684, 1076)

image image

Note that liblinear has an issue with fit_intercept=True, but this is a realistic use case with n_samples > n_features.

Details
import warnings
from pathlib import Path
import numpy as np
from scipy import sparse
from sklearn._loss import HalfBinomialLoss
from sklearn.compose import ColumnTransformer
from sklearn.datasets import fetch_openml
from sklearn.impute import SimpleImputer
from sklearn.linear_model._linear_loss import LinearModelLoss
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.exceptions import ConvergenceWarning
from sklearn.model_selection import train_test_split
from time import perf_counter
import pandas as pd


def prepare_data():
    df = fetch_openml(data_id=41162, as_frame=True, parser="auto").frame
    linear_model_preprocessor = ColumnTransformer(
        [
            (
                "passthrough_numeric",
                make_pipeline(SimpleImputer(), StandardScaler()),
                [
                    "MMRAcquisitionAuctionAveragePrice",
                    "MMRAcquisitionAuctionCleanPrice",
                    "MMRCurrentAuctionAveragePrice",
                    "MMRCurrentAuctionCleanPrice",
                    "MMRCurrentRetailAveragePrice",
                    "MMRCurrentRetailCleanPrice",
                    "MMRCurrentRetailAveragePrice",
                    "MMRCurrentRetailCleanPrice",
                    "VehBCost",
                    "VehOdo",
                    "VehYear",
                    "VehicleAge",
                    "WarrantyCost",
                ],
            ),
            (
                "onehot_categorical",
                OneHotEncoder(min_frequency=10),
                [
                    "Auction",
                    "Color",
                    "IsOnlineSale",
                    "Make",
                    "Model",
                    "Nationality",
                    "Size",
                    "SubModel",
                    "Transmission",
                    "Trim",
                    "WheelType",
                ],
            ),
        ],
        remainder="drop",
    )
    y = np.asarray(df["IsBadBuy"] == "1", dtype=float)
    X = linear_model_preprocessor.fit_transform(df)
    return X, y


X, y = prepare_data()
# X = X.toarray()
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=0.9, random_state=0
)
if sparse.issparse(X):
    print(f"X is sparse {X.format}")
else:
    print("X is dense")

print(f"{X_train.shape = }")

results = []
loss_sw = np.full_like(y_train, fill_value=(1. / y_train.shape[0]))
alpha = 1e-4
excluded_solvers = []
for tol in np.logspace(-1, -10, 10):
    for solver in ["lbfgs", "liblinear", "newton-cholesky", "newton-cd", "newton-cd-gram", "newton-cg", "saga"]:
        if solver in excluded_solvers:
            continue
        tic = perf_counter()
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=ConvergenceWarning)
            reg = LogisticRegression(
                solver=solver, C=1 / alpha / X_train.shape[0], tol=tol, max_iter=10_000
            ).fit(X_train, y_train)
        toc = perf_counter()
        train_time = toc - tic
        train_loss = LinearModelLoss(
            base_loss=HalfBinomialLoss(), fit_intercept=reg.fit_intercept
        ).loss(
            coef=np.r_[np.squeeze(reg.coef_), reg.intercept_],
            X=X_train,
            y=y_train,
            l2_reg_strength=alpha,
            sample_weight=loss_sw,
        )
        result = {
            "solver": solver,
            "tol": float(tol),
            "train_loss": float(train_loss),
            "train_time": train_time,
            "train_score": float(reg.score(X_train, y_train)),
            "test_score": float(reg.score(X_test, y_test)),
            "n_iter": int(np.squeeze(reg.n_iter_)),
            "converged": bool(np.squeeze(reg.n_iter_) < np.squeeze(reg.max_iter)),
        }
        print(result)
        results.append(result)
        if train_time > 100:
            excluded_solvers.append(solver)


results = pd.DataFrame.from_records(results)
results.to_csv(Path().resolve() / "bench_logistic_reg.csv")


import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt


results = pd.read_csv(Path().resolve() / "bench_logistic_reg.csv")
results["suboptimality"] = results["train_loss"] - results["train_loss"].min() + 1e-15

fig, ax = plt.subplots(figsize=(8, 6))
for label, group in results.groupby("solver"):
    group.sort_values("tol").plot(x="n_iter", y="suboptimality", loglog=True, marker="o", label=label, ax=ax)
ax.set_ylabel("suboptimality")
ax.set_title("Suboptimality by iterations, sparse X")


fig, ax = plt.subplots(figsize=(8, 6))
for label, group in results.groupby("solver"):
    group.sort_values("tol").plot(x="train_time", y="suboptimality", loglog=True, marker="o", label=label, ax=ax)
ax.set_ylabel("suboptimality")
ax.set_title("Suboptimality by time, sparse X")

L2 penalty C=1, fit_intercept=True, dense X

X is dense
X_train.shape = (65684, 1076)

image image

Code similar to sparse case above, in particular uncomment X = X.toarray().

Note that liblinear always converts to CSR matrix which is beneficial in this case.
If one densifies X by adding X += 1e-16, the liblinear performance curve is more realistic as shown on the following figure:

image

L1 penalty C=0.22638, fit_intercept=True

X is sparse csr
X_train.shape = (65684, 1076)
Best C=0.22638034095214465 (found by CV)
Number of zero coefficients = 861 (from 1076 features)

image image
Details
import warnings
from pathlib import Path
import numpy as np
from scipy import sparse
from sklearn._loss import HalfBinomialLoss
from sklearn.compose import ColumnTransformer
from sklearn.datasets import fetch_openml
from sklearn.impute import SimpleImputer
from sklearn.linear_model._linear_loss import LinearModelLoss
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.exceptions import ConvergenceWarning
from sklearn.model_selection import train_test_split
from time import perf_counter
import pandas as pd


def prepare_data():
    df = fetch_openml(data_id=41162, as_frame=True, parser="auto").frame
    linear_model_preprocessor = ColumnTransformer(
        [
            (
                "passthrough_numeric",
                make_pipeline(SimpleImputer(), StandardScaler()),
                [
                    "MMRAcquisitionAuctionAveragePrice",
                    "MMRAcquisitionAuctionCleanPrice",
                    "MMRCurrentAuctionAveragePrice",
                    "MMRCurrentAuctionCleanPrice",
                    "MMRCurrentRetailAveragePrice",
                    "MMRCurrentRetailCleanPrice",
                    "MMRCurrentRetailAveragePrice",
                    "MMRCurrentRetailCleanPrice",
                    "VehBCost",
                    "VehOdo",
                    "VehYear",
                    "VehicleAge",
                    "WarrantyCost",
                ],
            ),
            (
                "onehot_categorical",
                OneHotEncoder(min_frequency=10),
                [
                    "Auction",
                    "Color",
                    "IsOnlineSale",
                    "Make",
                    "Model",
                    "Nationality",
                    "Size",
                    "SubModel",
                    "Transmission",
                    "Trim",
                    "WheelType",
                ],
            ),
        ],
        remainder="drop",
    )
    y = np.asarray(df["IsBadBuy"] == "1", dtype=float)
    X = linear_model_preprocessor.fit_transform(df)
    return X, y


X, y = prepare_data()
# X = X.toarray()
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=0.9, random_state=0
)
if sparse.issparse(X):
    print(f"X is sparse {X.format}")
else:
    print("X is dense")

print(f"{X_train.shape = }")

clf_cv = LogisticRegressionCV(
    solver="newton-cd-gram", Cs=32, l1_ratios=[1], scoring="neg_log_loss", use_legacy_attributes=False,
).fit(X_train, y_train)

print(f"Best C={clf_cv.C_}")
print(f"Number of zero coefficients = {np.sum(clf_cv.coef_ == 0)} (from {X_train.shape[1]} features)")

results = []
loss_sw = np.full_like(y_train, fill_value=(1. / y_train.shape[0]))
alpha = 1 / clf_cv.C_ / X_train.shape[0]

excluded_solvers = []
for tol in np.logspace(-1, -10, 10):
    for solver in ["liblinear", "newton-cd", "newton-cd-gram", "saga"]:
        if solver in excluded_solvers:
            continue
        tic = perf_counter()
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=ConvergenceWarning)
            reg = LogisticRegression(
                solver=solver,
                C=1 / alpha / X_train.shape[0],
                l1_ratio = 1,
                tol=tol,
                max_iter=10_000,
            ).fit(X_train, y_train)
        toc = perf_counter()
        train_time = toc - tic
        train_loss = LinearModelLoss(
            base_loss=HalfBinomialLoss(), fit_intercept=reg.fit_intercept
        ).loss(
            coef=np.r_[np.squeeze(reg.coef_), reg.intercept_],
            X=X_train,
            y=y_train,
            l1_reg_strength=alpha,
            l2_reg_strength=0,
            sample_weight=loss_sw,
        )
        result = {
            "solver": solver,
            "tol": float(tol),
            "train_loss": float(train_loss),
            "train_time": train_time,
            "train_score": float(reg.score(X_train, y_train)),
            "test_score": float(reg.score(X_test, y_test)),
            "n_iter": int(np.squeeze(reg.n_iter_)),
            "converged": bool(np.squeeze(reg.n_iter_) < np.squeeze(reg.max_iter)),
        }
        print(result)
        results.append(result)
        if train_time > 100:
            excluded_solvers.append(solver)


results = pd.DataFrame.from_records(results)
results.to_csv(Path().resolve() / "bench_logistic_reg_L1.csv")

import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt


results = pd.read_csv(Path().resolve() / "bench_logistic_reg_L1.csv")
results["suboptimality"] = results["train_loss"] - results["train_loss"].min() + 1e-15

fig, ax = plt.subplots(figsize=(8, 6))
for label, group in results.groupby("solver"):
    group.sort_values("tol").plot(x="n_iter", y="suboptimality", loglog=True, marker="o", label=label, ax=ax)
ax.set_ylabel("suboptimality")
ax.set_title("Suboptimality by iterations, sparse X")


fig, ax = plt.subplots(figsize=(8, 6))
for label, group in results.groupby("solver"):
    group.sort_values("tol").plot(x="train_time", y="suboptimality", loglog=True, marker="o", label=label, ax=ax)
ax.set_ylabel("suboptimality")
ax.set_title("Suboptimality by time, sparse X")

@lorentzenchr
lorentzenchr force-pushed the logistic_lasso_newton branch 2 times, most recently from d487f9e to 0841e99 Compare February 18, 2026 18:14
@lorentzenchr
lorentzenchr force-pushed the logistic_lasso_newton branch from 0841e99 to 9fdac8f Compare March 16, 2026 16:28
@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Mar 16, 2026
@scikit-learn scikit-learn deleted a comment from github-actions Bot Mar 16, 2026
@lorentzenchr
lorentzenchr force-pushed the logistic_lasso_newton branch from 9fdac8f to ad047d0 Compare March 16, 2026 16:54
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Mar 16, 2026
@lorentzenchr
lorentzenchr force-pushed the logistic_lasso_newton branch from ad047d0 to 9dbef38 Compare June 8, 2026 12:44
@lorentzenchr
lorentzenchr force-pushed the logistic_lasso_newton branch from 9dbef38 to 4c8d91f Compare June 8, 2026 13:38
@lorentzenchr

Copy link
Copy Markdown
Member Author

@ogrisel @OmarManzoor @virchan This PR is quite large. But the commits are super clean. Would you be able to review if I make 4-5 smaller PRs out of it?

@lorentzenchr

Copy link
Copy Markdown
Member Author

#34681 was merged

@lorentzenchr
lorentzenchr deleted the logistic_lasso_newton branch September 30, 2026 15:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants