Skip to content

TMP: test showcasing the failure mode of newton-cholesky solver in GLMs - #35023

Closed
cakedev0 wants to merge 1 commit into
scikit-learn:mainfrom
cakedev0:failing-test-intercept-trick
Closed

cakedev0 wants to merge 1 commit into
scikit-learn:mainfrom
cakedev0:failing-test-intercept-trick

Conversation

@cakedev0

Copy link
Copy Markdown
Member

NOT FOR REVIEW

Reference Issues/PRs

Emanated from numerical stability discussions in #34793

AI usage disclosure

I used AI assistance for:

  • Test/benchmark generation

@lorentzenchr

Copy link
Copy Markdown
Member

I am not convinced by this test, at all. Was it AI generated?

To name one reason alone (there are more): Same penalty for different X means a different optimisation problem.

@cakedev0

Copy link
Copy Markdown
Member Author

Same penalty for different X means a different optimisation problem

Well in that case I believe it's the same optimization problem in the sense of being mathematically equivalent. And with f64 precision, they do get the same solution.

But maybe you meant it's not the same optimization landscape or something like that? Still, one could expect that a solver avoids silently returning a solution off by several order of magnitude (well ideally, I do get it's not an easy-to-meet expectation!).

@lorentzenchr

Copy link
Copy Markdown
Member

I don’t see a compelling reason why the compared coefficients should match.

@cakedev0

Copy link
Copy Markdown
Member Author

Well because it's the same argmin? 😅 Sorry, I don't get what doesn't convince you.

Coefficients do match for all linear models for small enough offset/variance ratio. And for Ridge/LinearRegression/Lasso/ElasticNet, they basically always match. So it looks like when they do not match it's some kind of numerical stability artifact.
Maybe we are fine with that though, and we expect people to center their data before feeding them in linear models (in which case we don't need a guard/check of any sort in #34793).

@lorentzenchr lorentzenchr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clearer now?

@cakedev0

Copy link
Copy Markdown
Member Author

Ok clear thanks!

Here is the explanation, I thought it was a common "trick" for linear models, so I thought you would find it obvious (I'm just getting familiar with linear models, and I'm relying on AI to understand things, when it explained this, I thought it looked as a well known fact on linear models):

For any fixed slope β, shifting X by a constant c can be exactly cancelled by shifting the intercept by -c·β:

(X+c)·β + (b - c·β) = X·β + b

Given that the intercept is not penalized (except for liblinear I believe), the penalized objective as a function of β is the same curve for X and X+c, just with the intercept shifted. Same curve, same minimum: the best β can't change, only the best intercept does.

That's why you could expect this test to pass (and it does for many similar cases/models, which is empirically convincing IMO).

@lorentzenchr

lorentzenchr commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Almost:

  • The invariance of the prediction, i.e.X b + b0 with b -> b+c, b0 -> b0 - c does not prove that the argmin of the optimization problem is the same. If you change b - > b+c, the penalty change, too, ||b|| -> ||b+c||. Therefore the Ridge solutions changes!!!
  • Even for OLS (Ridge without penalty), solutions of
    A: argmin_{b,b0} ||y - X b - b0||_2^2
    B: argmin_{b,b0} ||y - (X-Xc) b - b0||_2^2
    don't give the same solution (b, b0). They are off by a constant term and the predictions are the same.

If it's still unclear, let's have a call.

@cakedev0

cakedev0 commented Sep 24, 2026 •

Copy link
Copy Markdown
Member Author

If you change b - > b+c [...]

Well you don't do that. In my formula, the slope β is unchanged.

Edit: ah you meant the intercept, not the slope. Sorry. The intercept is not penalized so there is no ||b|| -> ||b+c|| happening and as you say below, it's the same optimisation problem.

They are off by a constant term

Yes, I agree the intercept changes, but not the slope/coefficients

@lorentzenchr

lorentzenchr commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Changed my mind. You are right for OLS and Ridge. Once the optimization over the intercept is carried out analytically, the same optimisation problem remains, with or without centering X.

To my knowledge, the centering trick does not work for GLMs. And you use LogisticRegression in the test.

@cakedev0

Copy link
Copy Markdown
Member Author

I'm not sure what you mean about the centering trick here. If it's what I do in #34793 indeed I don't think you can do the same thing for LogisticRegression and I'm not trying to say that.

But the identity (X+c)·β + (b - c·β) = X·β + b is purely about the linear predictor η = X·β + b (the logit, before the sigmoid) so the reasoning holds for LogisticRegression (and any other GLM) and the test of this PR should pass. Or at least it could pass if the implementation tried to be robust on ill-centered data, which is maybe not something we need/want. And at the very least, we should not silently return coefficients that are completely off without a warning. I'll create an issue about that.

@lorentzenchr

Copy link
Copy Markdown
Member

test of this PR should pass

I don’t think so. Let’s have a call and have a break from written discussion.

@lorentzenchr

Copy link
Copy Markdown
Member

Again, let's talk (my preferred resolution).

Apart from that, interesting things happen:

import numpy as np
from sklearn._loss import HalfBinomialLoss
from sklearn.linear_model._linear_loss import LinearModelLoss
from sklearn.linear_model import LogisticRegression

rng = np.random.RandomState(0)
n_samples, n_features = 5000, 5
X_centered = rng.normal(size=(n_samples, n_features)) * 1e-5
#X_centered -= X_centered.mean(axis=0)[None, :]
X = X_centered + 3

true_coef = rng.normal(size=n_features)
proba = 1 / (1 + np.exp(-(X_centered @ true_coef)))
y = (rng.uniform(size=n_samples) < proba).astype(int)

lml = LinearModelLoss(base_loss=HalfBinomialLoss(), fit_intercept=True)
def obj(model, X, y):
    n_samples = X.shape[0]
    coef = np.r_[model.coef_[0], model.intercept_]
    l1_reg = model.l1_ratio / (model.C * n_samples)
    l2_reg = (1 - model.l1_ratio) / (model.C * n_samples)
    loss = lml.loss(
        coef, X=X.astype(np.float64), y=y.astype(np.float64),
        l1_reg_strength=l1_reg, l2_reg_strength=l2_reg
    )
    return float(loss)

params = dict(C=1, tol=1e-12, max_iter=20000)
m1 = LogisticRegression(solver="lbfgs", **params).fit(X_centered, y)
m2 = LogisticRegression(solver="lbfgs", **params).fit(X, y)

m3 = LogisticRegression(solver="newton-cholesky", **params).fit(X_centered, y)
m4 = LogisticRegression(solver="newton-cholesky", **params).fit(X, y)

print(m1.coef_)
print(m2.coef_)
print(m3.coef_)
print(m4.coef_)
[[-1.54567015e-05  1.94092809e-04  3.00951230e-04 -6.75034339e-05 3.44338878e-04]]
[[0.00130434 0.00130437 0.00130439 0.00130433 0.00130439]]
[[-1.54548256e-05  1.94069251e-04  3.00914702e-04 -6.74952416e-05 3.44297084e-04]]
[[-1.54548256e-05  1.94069251e-04  3.00914702e-04 -6.74952416e-05 3.44297084e-04]]
print(obj(m1, X_centered, y))
print(obj(m2, X, y))
print(obj(m3, X_centered, y))
print(obj(m4, X, y))
0.693097179701424
0.6930971803799683  <- lbfgs on uncentered X is off
0.6930971797014239
0.6930971797014239

What happens to float32

LogisticRegression(solver="newton-cholesky", **params, verbose=4).fit(X.astype(np.float32), y)
...
sklearn/linear_model/_glm/_newton_solver.py:475: RuntimeWarning: divide by zero encountered in scalar divide
  a = (alpha_old**2 * vec0 - alpha**2 * vec1) / denom
sklearn/linear_model/_glm/_newton_solver.py:476: RuntimeWarning: invalid value encountered in scalar divide
  b = (alpha**3 * vec1 - alpha_old**3 * vec0) / denom
sklearn/linear_model/_glm/_newton_solver.py:489: ConvergenceWarning: Line search of Newton solver NewtonCholeskySolver at iteration #5 did not converge after 21 line search refinement iterations. It will now resort to lbfgs instead.

@cakedev0

Copy link
Copy Markdown
Member Author

Given your answer on issue #35029 (I mostly agree with all your points there), I think we've reached an understanding and I think I can close this PR in favor of #35029.

Happy to chat in a call at some point about issue #35029 for which the direction indeed needs discussion.

@cakedev0 cakedev0 closed this Sep 25, 2026
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