Skip to content

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

Open
cakedev0/scikit-learn
#38

Description

@cakedev0

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

Describe the bug and give evidence about its user-facing impact

scikit-learn's linear models split into two families with very different handling of un-centered features:

  • LinearRegression, Ridge, Lasso, ElasticNet go through _preprocess_data, which centers X and y (explicitly for dense data, algebraically for sparse) before solving, then reconstructs the intercept afterward. Centering is a pure reparametrization here: for any fixed coef, shifting X by a constant only shifts the intercept, and the L1/L2 penalty doesn't touch the intercept, so the optimal coef is mathematically invariant to any additive shift of the features. Ridge/Lasso exploit this to shield users from poor numerical stability on high mean to variance ratio features.
  • LogisticRegression, PoissonRegressor, GammaRegressor, TweedieRegressor (the LinearModelLoss + NewtonSolver/lbfgs/newton-cg/newton-cholesky family) do not do this. The intercept is just another free parameter solved jointly with the coefficients directly on the raw X. There is no _preprocess_data-equivalent step.

The same invariance holds mathematically for this second family too (same argument: additive shift + unpenalized intercept), but because nothing centers the data first, the solvers can lose that invariance numerically. Concretely:

  • newton-cholesky builds its Hessian from the raw [X, 1] design. Eliminating the intercept column during Cholesky factorization implicitly computes X.T @ X - n * mean(X) * mean(X).T which can yield catastrophic-cancellation-prone quantity. The scipy solver normally fires a warning or an error in this case, so at least, it's visible for users something is wrong.
  • lbfgs doesn't have a cancellation problem in this sense, but its gradient-norm convergence check can be satisfied prematurely on badly-offset data, silently stopping far from the true optimum, with no warning at all.

User-facing impact: any real dataset with a feature that's far from zero-mean relative to its variance (a year, a timestamp, an age, a physical measurement with an offset unit) can silently produce badly wrong coef_/intercept_ for these estimators, without any indication something went wrong.

I stumbled on this while investigating numerical-stability discussions in #34793 (Ridge's cholesky centering trick).

Steps/Code to Reproduce

Sweep used to generate the plot below:

Details
import warnings
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import (
    LinearRegression, LogisticRegression, Ridge,
    TweedieRegressor, PoissonRegressor, ElasticNet,
)


def relative_error_vs_mean_variance_ratio(
    linear_estimator, dtype="float32", random_seed=0, max_ratio=1e5
):
    rng = np.random.RandomState(random_seed)
    n_samples, n_features = 5000, 5
    X = rng.normal(size=(n_samples, n_features))
    true_coef = rng.normal(size=n_features)
    proba = 1 / (1 + np.exp(-(X @ true_coef)))
    y = (rng.uniform(size=n_samples) < proba).astype(int)
    X, y = X.astype(dtype), y.astype(dtype)
    linear_estimator.fit(X, y)
    ref = linear_estimator.coef_.copy()
    assert np.linalg.norm(ref) > 0.1  # we want coefs that aren't too small

    ratios = np.logspace(0, np.log10(max_ratio), num=30)
    errors, has_warnings = [], []
    for offset in ratios:
        with warnings.catch_warnings(record=True) as caught:
            linear_estimator.fit((X + offset).astype(dtype), y)
        shifted = linear_estimator.coef_.copy()
        errors.append(np.linalg.norm(shifted - ref) / np.linalg.norm(ref))
        has_warnings.append(bool(caught))

    return ratios, np.array(errors), np.array(has_warnings)


models = [
    Ridge(solver="cholesky", alpha=1 / 5000),
    Ridge(solver="lbfgs", positive=True, alpha=1 / 5000),
    ElasticNet(alpha=1 / 5000),
    LinearRegression(),
    # GLMs:
    LogisticRegression(solver="lbfgs"),
    LogisticRegression(solver="newton-cholesky"),
    TweedieRegressor(solver="lbfgs", alpha=1 / 5000),
    TweedieRegressor(solver="newton-cholesky", alpha=1 / 5000),
    PoissonRegressor(solver="lbfgs", alpha=1 / 5000),
    PoissonRegressor(solver="newton-cholesky", alpha=1 / 5000),
]

dtypes = ["float32", "float64"]
n_cols = 2
n_rows = -(-len(models) // n_cols)  # ceil division
fig, axes = plt.subplots(
    n_rows, n_cols, figsize=(5 * n_cols, 3 * n_rows), sharex=True, sharey=True
)
axes = axes.ravel()

for ax, model in zip(axes, models):
    results = [relative_error_vs_mean_variance_ratio(model, dtype=dtype) for dtype in dtypes]
    for (ratios, errors, has_warnings), dtype in zip(results, dtypes):
        line, = ax.plot(ratios, errors, label=dtype)
        ax.scatter(
            ratios[has_warnings], errors[has_warnings], marker="x", s=10,
            color=line.get_color(),
        )
    ax.set_ylim(0, 1.02)
    ax.set_xscale("log")
    ax.set_title(str(model), fontsize=9)
    ax.tick_params(axis="x", which="both", labelbottom=True)
    ax.set_xlabel("mean/variance ratio")

for ax in axes[len(models):]:
    ax.axis("off")
for ax in axes[::n_cols]:
    ax.set_ylabel("relative error")

axes[0].legend()
fig.tight_layout()

Expected Results

Fitting on X + offset should not change coef_ (more than floating point noise) or at the very least should not change coef_ without a warning.

Actual Results

The grid below (generated by the reproducer snippet) sweeps the feature mean/variance ratio (X + ratio, unit-variance X) from 1 to 1e5, one subplot per estimator, and plots the relative error of coef_ against the ratio=0 reference, for both float32 and float64, with × marking points where a warning was raised:

Image
  • Ridge, LinearRegression, ElasticNet (top two rows, the _preprocess_data family): error stays ~0 across the entire range, in both dtypes. A blip only appears in float32 at the extreme end (ratio ≥1e4), never in float64.
  • LogisticRegression, TweedieRegressor, PoissonRegressor (bottom three rows, the GLM family), with either solver (lbfgs or newton-cholesky): garbage coefficients starting at a ratio as low as ~20-100 in float32 and ~300-5000 in float64.

Versions

System:
    python: 3.14.6 (main, Jun 23 2026, 15:18:23) [Clang 22.1.3 ]
executable: /home/arthur/scikit-learn/sklearn-env/bin/python
   machine: Linux-6.17.0-1032-oem-x86_64-with-glibc2.39

Python dependencies:
      sklearn: 1.10.dev0
          pip: None
   setuptools: None
        numpy: 2.5.3
        scipy: 1.18.1
       Cython: 3.3.0
       pandas: 3.0.5
   matplotlib: 3.11.1
       joblib: 1.6.0
threadpoolctl: 3.6.0
     narwhals: 2.26.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 14
         prefix: libscipy_openblas
       filepath: /home/arthur/scikit-learn/sklearn-env/lib/python3.14/site-packages/numpy.libs/libscipy_openblas64_-f48b354e.so
        version: 0.3.34.106.0
threading_layer: pthreads
   architecture: Haswell

       user_api: blas
   internal_api: openblas
    num_threads: 14
         prefix: libscipy_openblas
       filepath: /home/arthur/scikit-learn/sklearn-env/lib/python3.14/site-packages/scipy.libs/libscipy_openblas-5f890258.so
        version: 0.3.31.dev
threading_layer: pthreads
   architecture: Haswell

       user_api: openmp
   internal_api: openmp
    num_threads: 14
         prefix: libgomp
       filepath: /usr/lib/x86_64-linux-gnu/libgomp.so.1.0.0
        version: None

Interest in fixing the bug

Yes. I'm about to open a PR with a proposed fixed: detecting high mean/variance ratio and explicitly recentering if needed.

Activity

  1. ogrisel commented on Sep 25, 2026

    @ogrisel
    Member

    @cakedev0 The linked image is missing from the description:

    Image
  2. cakedev0 commented on Sep 25, 2026

    @cakedev0
    MemberAuthor

    Weird, it was displayed when I created the issue.

    Re uploaded it ✅

  3. ogrisel commented on Sep 25, 2026

    @ogrisel
    Member

    A quick fix would to compute the mean feature value before fitting (possibly on a random subset of the rows) to warn the user and them to approximately center the data in a pipeline or use a different feature engineering that does not lead to severely off centered data (e.g. one hot encoding, splines...).

  4. cakedev0 commented on Sep 25, 2026

    @cakedev0
    MemberAuthor

    Compute the mean AND the variance. High mean is ok for high variance.

    But IMO, once we have computed that, we can as well re-center the data ourselves ^^

  5. ogrisel commented on Sep 25, 2026

    @ogrisel
    Member

    But IMO, once we have computed that, we can as well re-center the data ourselves ^^

    It depends: explicit centering allocates a lot of memory and that might be a problem for some users, so better let them in control.

  6. lorentzenchr commented on Sep 25, 2026

    @lorentzenchr
    Member

    Very interesting findings.
    For me the big question is: Do we want to fix this? And if so, how?

    • No user has complained so far.
    • Huge mean X and a tiny "signal" (variance) on top seems like random X.
    • More of a problem for float32 X.
    • How do other libraries compare here (R glm, R glmnet, statsmodels, H2O, skglm, celer)?

    Issues when fixing it:

    • Centering destroys sparsity of X (if X is a sparse array).
    • Centering doubles memory (X might be huge, it is basically the only object we should avoid to copy).

    Given all that, I lean towards warnings where we don't have one yet - if it is cheap enough.

  7. cakedev0 commented on Sep 25, 2026

    @cakedev0
    MemberAuthor

    How do other libraries compare here (R glm, R glmnet, statsmodels, H2O, skglm, celer)?

    That's a very good question!

    Claude ran the same kind of sweep on all of them: one dataset (n=5000, 5 standard-normal features, a logistic target and a Poisson target), adding an offset to every feature from 1 to 1e6. For each library, it compared coef to that same library's fit at offset 0. it also read the docs and the sources to check whether they center.

    Versions: R 4.5.3, glmnet 5.0, statsmodels 0.15.0, H2O 3.46.0.12, skglm 0.5, celer 0.7.4, and sklearn 1.9.1 as the baseline.

    Summary

    Library Centers X? Solver Behavior with a large offset
    R glm No IRLS; each step is a Householder QR of the weighted design, and X'WX is never formed Robust: rel. err. ~1e-11 at offset 1e6
    R glmnet Yes, whenever intercept=TRUE, even with standardize=FALSE. For sparse X the centering is done implicitly inside the CD updates. Coordinate descent on the centered data Robust: ~1e-11 at 1e6
    statsmodels GLM (IRLS, the default) No IRLS with lstsq (SVD) on the weighted design Robust: ~1e-11 at 1e6
    statsmodels GLM(method="lbfgs") No L-BFGS, but warm-started with 3 IRLS iterations (max_start_irls=3) Stays at the tolerance level (~4e-4) across the whole range, thanks to the IRLS warm start
    statsmodels Logit / Poisson (newton, the default) No Newton with an explicit Hessian and np.linalg.solve Breaks at ~1e4 (Poisson) / ~3e4 (Logit), with a ConvergenceWarning
    statsmodels Logit(method="bfgs") No BFGS Breaks at ~100-300, with a ConvergenceWarning
    H2O GLM, standardize=True (the default) Yes IRLSM (Cholesky of the Gram matrix) or L-BFGS Robust for both solvers
    H2O GLM, standardize=False No IRLSM Degrades gradually, roughly like offset² · eps: 2e-3 at 5.6e5
    H2O GLM, standardize=False No L-BFGS Garbage from offset ~30 (binomial) / ~18 (Poisson). Only one warning was raised over the whole sweep ("Reached maximum number of iterations 20!")
    skglm (sparse logistic regression, Lasso, Poisson with ProxNewton) No; the intercept is one more coordinate with its own 1-D update CD / prox-Newton coef stays at the tolerance level, but fit time grows ~offset².
    celer Lasso Yes, because it subclasses sklearn's Lasso and reuses _preprocess_data CD with working sets Identical to sklearn's Lasso
    celer LogisticRegression Not applicable fit_intercept=True raises NotImplementedError, so the problem can't occur

    Documentation: no library mentions a numerical need to center.

    • glmnet documents standardize but not the centering that happens regardless of it.
    • H2O "highly recommends" standardize=True, but the reason it gives is penalty scale, not conditioning.
    • statsmodels only prints the generic "condition number is large" note, and only in the OLS summary.
    • R glm, skglm and celer say nothing about it.

    Takeaways

    1 - The libraries that are robust get there in one of two ways:

    • they center X internally (glmnet always, H2O by default, celer through sklearn);
    • or they use IRLS with an orthogonal factorization of the weighted design (R glm, statsmodels GLM), which never forms X'WX.

    2 - Other approaches degrade like sklearn does:

    • statsmodels Logit/Poisson and bfgs, H2O standardize=False + L-BFGS, and skglm, where the damage shows up as run time rather than accuracy.
    • statsmodels at least raises a ConvergenceWarning. H2O L-BFGS and skglm are essentially silent.

    3 - In float64, sklearn's lbfgs (broken from offset ~100-200) is in the same range as the worst of these (statsmodels bfgs, H2O L-BFGS without standardization). It's much worse than R glm, glmnet, statsmodels' default GLM, or H2O's default.

  8. lorentzenchr commented on Sep 26, 2026

    @lorentzenchr
    Member

    Insightful analysis, indeed!

    What we can do:

    1. Improve our use guide by mentioning mean centering (and hint at using splines) and scaling in (penalized) linear model very early on.
    2. Add a test in (maybe in linear_model/tests/test_common.py) with many xfails.
    3. Don't change anything for
      • sparse X as centering destroys sparsity
      • *CV classes like RidgeCV and LassoCV that already centered X. Because the centered X is reused many times, centering seems worth it w.r.t. memory and computation time.
    4. If we find a cheap detection method:
      • Emit a warning (were we don't have one yet)
      • Some algorithms can be extended to center implicitly, e.g. CD see ENH add sample_weight and fit_intercept to Cython enet_coordinate_descent #31375 (for a single alpha might be worth it), computing a centered gram/hessian in batches might also be worth a try
      • Think about further improvements. (I don't think we need a new parameter for mean centering as this can be accomplished with a Pipeline)
  9. moved this to Issue in progress in Labson Sep 28, 2026
  10. cakedev0 commented on Sep 29, 2026

    @cakedev0
    MemberAuthor

    [another related finding, posting here as it might help and I don't want to forget about it]

    I noticed that in float64, newton-cholesky doesn't fail because the Hessian solve is inaccurate. It fails because of the conditioning check. scipy.linalg.solve(..., assume_a="sym") raises a LinAlgWarning when rcond < eps. We turn that warning into an error and fall back to lbfgs, and lbfgs is what returns the garbage coefficients.

    That rcond is computed for the full [X, 1] Hessian, whose condition number grows like offset⁴. The actual error on coef stays tiny. If I keep the exact same solve call but simply ignore the warning (float64, tol=1e-10, relative error of coef vs the fit at offset 0):

    offset 1e3 1e4 1e5 1e6
    main 2e-11 0.71 0.71 0.71
    LinAlgWarning ignored 5e-11 5e-11 5e-11 1e-9

    A check that takes the intercept into account might push the float64 breakdown point much further, without centering. I haven't looked at float32.

  11. lorentzenchr commented on Sep 29, 2026

    @lorentzenchr
    Member

    scipy.linalg.solve does not provide to set a limit rcond (e.g. as lstsq) when to raise a LinAlgWarning. Is there a way to distinguish this warning from others?

  12. cakedev0 commented on Oct 8, 2026

    @cakedev0
    MemberAuthor

    How do other libraries compare here (R glm, R glmnet, statsmodels, H2O, skglm, celer)?

    I asked myself a follow-up question: do those libraires have a test enforcing it?

    Agent answer: no.

    The one partial exception is statsmodels, through the Longley dataset, and only for the linear/Gaussian case.

    This means the robust libraries get there by design (R glm and statsmodels GLM use QR or least squares, glmnet always centers, H2O standardizes by default), not because tests enforce it.

  13. lorentzenchr commented on Oct 31, 2026

    @lorentzenchr
    Member

    Note that once we had a normalize parameter in some linear models. In #3020 (comment) it was decided to deprecate and remove it.
    The recommended way is to use make_pipeline(StandardScaler(), MyLinearModel()).

  14. added a commit that references this issue on Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions