Skip to content

FIX lbfgs on implicitly centered and scaled columns in linear models - #38

Draft
cakedev0 wants to merge 2 commits into
mainfrom
lbfgs-center-scale
Draft

cakedev0 wants to merge 2 commits into
mainfrom
lbfgs-center-scale

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 23, 2026 •

Copy link
Copy Markdown
Owner

Reference Issues/PRs

Towards scikit-learn#35029. Draft on my fork, to discuss before opening it upstream.

What does this implement/fix? Explain your changes.

lbfgs in LogisticRegression, PoissonRegressor, GammaRegressor and TweedieRegressor (and the lbfgs fallback of the Newton solvers) now runs on implicitly centered and scaled columns. L-BFGS optimizes over v = s * coef and c = intercept + coef @ m, with m the column means (only with an intercept) and s = max(1, std). X is never copied, sparse X stays sparse, and the penalty stays on coef, so the problem and its minimizer don't change, whatever the values of m and s. It's a wrapper around LinearModelLoss.loss_gradient (_LBFGSReparametrization in _linear_loss.py). For dense X, m and s are estimated on at most 10k evenly spaced rows: on all rows, it cost ~3 loss/gradient evaluations (see Benchmarks). For sparse X, it's one call to mean_variance_axis. Then each evaluation costs O(n_classes * n_features) more.

It fixes two ways lbfgs silently stops far from the optimum:

  • On offset features (BUG: LogisticRegression (and other GLMs) can silently return badly wrong coefficients on off-centered data scikit-learn/scikit-learn#35029). With the sweep of the issue's description (5 standard normal features + an offset), coef_ was 71% to 100% off from offset 1e3 in float64. It's now within 0.03% for LogisticRegression and PoissonRegressor, in 5 or 6 iterations.
  • On a feature with a large scale. The first L-BFGS-B trial step overflows the loss, L-BFGS-B evaluates the starting point again, sees no decrease and returns it with status 0 ("CONVERGENCE: RELATIVE REDUCTION OF F <= FACTR*EPSMCH"), so no warning. With a feature in the thousands, GammaRegressor() returned the intercept-only model after 1 iteration. It now converges in 3 iterations to newton-cholesky's solution:
import numpy as np
from sklearn.linear_model import GammaRegressor

rng = np.random.default_rng(0)
z = rng.uniform(1500, 2000, size=(10_000, 1))  # a feature in the thousands
y = rng.gamma(shape=2, scale=np.exp(11 - z[:, 0] / 500) / 2)  # log(E[y]) = 11 - z / 500
for solver in ["lbfgs", "newton-cholesky"]:
    model = GammaRegressor(solver=solver).fit(z, y)
    print(f"{solver}: n_iter_={model.n_iter_}, coef_={model.coef_[0]:.6f}")
main:   lbfgs: n_iter_=1, coef_=0.000000
        newton-cholesky: n_iter_=4, coef_=-0.002016
branch: lbfgs: n_iter_=3, coef_=-0.002016

I found the second one benchmarking the GLM solvers against glum on real data, with target-encoded columns (in the thousands) of a Gamma model on freMTPL2 claim amounts: lbfgs stopped ~2% above the optimum at any tol.

tol: L-BFGS-B's gtol applies to the gradient with respect to (v, c), which is the gradient with respect to coef divided by s. So gtol = tol / max(s), which keeps max |gradient| <= tol for coef without an intercept. Without that, lbfgs stopped 4x to 10x further from the optimum at the default tol in test_logistic_regression_solvers. With an intercept, the centered gradient is used on purpose: the uncentered one is what's small far from the optimum on offset features.

The price is that the number of iterations depends on the units of the largest column. With 200 one-hot columns and a standard normal column multiplied by 1e4, the problem in (v, c) is the same as without the 1e4, but PoissonRegressor takes 61 iterations instead of 25 (LogisticRegression: 56 instead of 15), because gtol is 1e4 times smaller. With gtol = tol, it takes 13 to 19 iterations and coef_ is as close to the optimum as on the problem without the 1e4, but max |gradient| for coef can then be up to max(s) * tol. I kept the stricter rule, WDYT?

Alternatives

I compared 4 choices of s in a prototype (scipy's L-BFGS-B on the same objective, outside scikit-learn), on 5 real problems (logistic regression on bank_marketing, kick and kddcup09_churn, Poisson and Gamma GLMs on freMTPL2, with spline and one-hot features in [0, 1] and target-encoded columns) and on the sweep of scikit-learn#35029. Iterations to reach tol=1e-8, on one NUMA node of a Xeon 6787P:

plain lbfgs (main) centering only (s = 1) unit variance (s = std) s = sqrt(var + alpha) s = max(1, std) (this PR)
bank_marketing 2,459 936 940 1,014 936
kick 1,184 495 1,031 773 495
kddcup09_churn 561 196 20,000, not converged 428 196
fremtpl2_freq (Poisson) 946 533 676 718 533
fremtpl2_sev (Gamma) 1, silently 2% above the optimum 1, same 1,072 18 24
scikit-learn#35029 offsets, float64 71% to 100% off exact exact exact exact
  • Centering only does most of the work (1.8x to 2.9x fewer iterations) and fixes BUG: LogisticRegression (and other GLMs) can silently return badly wrong coefficients on off-centered data scikit-learn/scikit-learn#35029, but not the large-scale case, which is about scale, not offset.
  • Unit variance is what glum does for all its solvers. It fixes the large-scale case but breaks kddcup09_churn: I think dividing its near-constant columns by a tiny s makes the penalty badly conditioned in v. glum's own lbfgs does the same there (glum 3.4.1 with scipy 1.16): 12,548 iterations and still 1.7e-2 above the optimum. glum's IRLS solvers are fine, as Newton steps don't depend on a diagonal rescaling.
  • sqrt(var + alpha) bounds the penalty's curvature in v by 1. It's safe everywhere and doesn't depend on the units, but up to 2.2x slower than centering where centering is enough.
  • max(1, std) is the same as centering on these 4 problems (all their columns have a std <= 1) and fixes the large-scale case. But the threshold of 1 depends on the units of the features, and I picked it after seeing these problems, so it's partly fitted to them. It does nothing for columns with a small scale. A test on raw numeric features in very different units would tell max(1, std) and sqrt(var + alpha) apart, I haven't run it yet.

This is close to scikit-learn#15583 (lbfgs preconditioned by the std in LogisticRegression, closed). Its counter-examples were MNIST / 255 and low-rank data with 2 columns multiplied by 1e3, where it took more iterations. With s = max(1, std), this PR needs 2.4x to 3.4x fewer iterations on the first at tol=1e-8. On the second, it's mixed: fewer iterations with C=1000 and C=0.001, more with C=1. See Benchmarks.

Other options, not exclusive with this one:

Benchmarks

On a laptop (Intel Core Ultra X7 358H, 16 threads), main and this branch interleaved with idle time in between, median of 3 to 5 fits, default parameters unless said otherwise. The scripts are not in the repo, I can share them.

TLDR:

  • When both converge in a few iterations, the fit time is the same as on main within ~15% either way.
  • Wide sparse multiclass (20newsgroups): each iteration is 4% to 11% slower, as the change of variables is O(n_classes * n_features) per evaluation. With C=100, the branch takes fewer iterations and is 7% to 9% faster overall, with C=1 it is 4% to 7% slower.
  • MNIST / 255: 1.6x to 2.5x faster at the default tol, and 2.4x to 3.4x fewer iterations at tol=1e-8, to the same objective.

Synthetic data where both converge quickly (500k x 100 dense standard normal, 500k x 2000 sparse with density 0.01):

                              main                   this branch
dense float64 LogisticRegr.   256-294 ms (7 iter)    250-253 ms (7 iter)
dense float64 PoissonRegr.    190-229 ms (6 iter)    187-192 ms (6 iter)
dense float32 LogisticRegr.   184-187 ms (7 iter)    181-188 ms (7 iter)
dense float32 PoissonRegr.    106-107 ms (5 iter)    115-121 ms (6 iter)
sparse float64 LogisticRegr.  379-414 ms (12 iter)   402 ms (12 iter)

Computing m and s on all the rows of this dense X took 62-70 ms in float64, and 121-131 ms in float32 because sw @ X cast X to float64. That made these fits ~15% to 2.2x slower, hence the subsample.

LogisticRegression on fetch_20newsgroups_vectorized(subset="train") (11314 x 130107 sparse, 20 classes):

          main                     this branch
C=1       11.1-11.5 s (70 iter)    11.9 s (70 iter)
C=100     28.4-28.9 s (136 iter)   26.4 s (114 iter)

LogisticRegression(max_iter=1000) on the first 20k rows of MNIST / 255 (10 classes), and on the low-rank data of scikit-learn#15583 (1000 x 10000, make_low_rank_matrix with 2 columns multiplied by 1e3):

                     main                  this branch
mnist C=0.01         0.75 s (87 iter)      0.30 s (31 iter)
mnist C=1            1.80 s (208 iter)     0.74-1.12 s (85 iter)
low-rank C=1000      0.07 s (32 iter)      0.07 s (29 iter)
low-rank C=1         0.02 s (10 iter)      0.05 s (17 iter)
low-rank C=0.001     0.02 s (6 iter)       0.02 s (4 iter)

With tol=1e-8, MNIST takes 284 -> 84 iterations (C=0.01) and 812 -> 336 (C=1), and the low-rank data 197 -> 158 (C=1000) and 18 -> 24 (C=1). At the default tol, both stop at a different distance from the optimum: on the low-rank data with C=1000, main stops 1.7% above it and this branch 4.9%; with C=1, main stops 3.6e-4 above it (relative) and this branch 3e-7.

Any other comments?

Tests: a unit test of the change of variables (exact chain rule, dense and sparse, with and without intercept and sample weights), a test of the subsampled mean and variance, and non-regression tests for both cases above. They fail on main and pass here. The rest of sklearn.linear_model and the common checks of these estimators pass, except 2 tests, which I haven't changed:

  • test_logistic_regressioncv_class_weights[42-weight-weight0]: newton-cholesky vs lbfgs differ by 3e-10 on a coefficient of 2e-6 (rtol=1e-4). Two of the fits now stop on L-BFGS-B's "relative reduction of f" (the loss converged to machine precision) instead of on the gradient. On the 4 cases of that test, lbfgs gets closer to the optimum on 2 and further on 2.
  • The common check check_non_transformer_estimators_n_iter for LogisticRegressionCV: on iris, one fit of the regularization path starts from the previous solution, which already meets gtol (max |gradient| 5.65e-5 vs 5.78e-5), so n_iter_ == 0 where the check wants >= 1.

I also changed test_zero_max_iter[lbfgs]: L-BFGS-B takes a first step even with max_iter=0, and that step is now good (score 0.83), so the score < 0.7 check only applies to the other solvers.

Not done yet: benchmarks on a many-core machine (the cost of the change of variables is single-threaded), float32 and the array API path (where the change is skipped), and a changelog entry.

AI usage disclosure

I used Claude Code (Claude Opus 5.5) to investigate, prototype, write the code, tests and this description, and run the experiments. I reviewed the code, the results and this text.

🤖 Generated with Claude Code

cakedev0 and others added 2 commits October 23, 2026 20:48
L-BFGS optimizes over v = s * coef and c = intercept + coef @ m, with m the
column means and s = max(1, std), without copying X. It fixes lbfgs stopping
far from the optimum on offset features (scikit-learngh-35029) and silently returning the
starting point when its first step overflows the loss.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The full pass over dense X cost ~3 loss/gradient evaluations and made a
float64 copy of float32 X. Also update the gradient in place, without
transposed copies for multiclass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: LogisticRegression (and other GLMs) can silently return badly wrong coefficients on off-centered data

1 participant