Repository navigation
Description
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,ElasticNetgo through_preprocess_data, which centersXandy(explicitly for dense data, algebraically for sparse) before solving, then reconstructs the intercept afterward. Centering is a pure reparametrization here: for any fixedcoef, shiftingXby a constant only shifts the intercept, and the L1/L2 penalty doesn't touch the intercept, so the optimalcoefis 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(theLinearModelLoss+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 rawX. 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-choleskybuilds its Hessian from the raw[X, 1]design. Eliminating the intercept column during Cholesky factorization implicitly computesX.T @ X - n * mean(X) * mean(X).Twhich 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.lbfgsdoesn'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:
Ridge,LinearRegression,ElasticNet(top two rows, the_preprocess_datafamily): 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: NoneInterest 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
ogrisel commentedon Sep 25, 2026
@cakedev0 The linked image is missing from the description:
cakedev0 commentedon Sep 25, 2026
Weird, it was displayed when I created the issue.
Re uploaded it ✅
ogrisel commentedon Sep 25, 2026
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...).
cakedev0 commentedon Sep 25, 2026
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 ^^
ogrisel commentedon Sep 25, 2026
It depends: explicit centering allocates a lot of memory and that might be a problem for some users, so better let them in control.
lorentzenchr commentedon Sep 25, 2026
Very interesting findings.
For me the big question is: Do we want to fix this? And if so, how?
Issues when fixing it:
Given all that, I lean towards warnings where we don't have one yet - if it is cheap enough.
cakedev0 commentedon Sep 25, 2026
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
coefto 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
glmglmnetintercept=TRUE, even withstandardize=FALSE. For sparse X the centering is done implicitly inside the CD updates.GLM(IRLS, the default)lstsq(SVD) on the weighted designGLM(method="lbfgs")max_start_irls=3)Logit/Poisson(newton, the default)np.linalg.solveConvergenceWarningLogit(method="bfgs")ConvergenceWarningstandardize=True(the default)standardize=Falsestandardize=FalseLasso, Poisson with ProxNewton)coefstays at the tolerance level, but fit time grows ~offset².LassoLassoand reuses_preprocess_dataLassoLogisticRegressionfit_intercept=TrueraisesNotImplementedError, so the problem can't occurDocumentation: no library mentions a numerical need to center.
standardizebut not the centering that happens regardless of it.standardize=True, but the reason it gives is penalty scale, not conditioning.glm, skglm and celer say nothing about it.Takeaways
1 - The libraries that are robust get there in one of two ways:
glm, statsmodelsGLM), which never forms X'WX.2 - Other approaches degrade like sklearn does:
standardize=False+ L-BFGS, and skglm, where the damage shows up as run time rather than accuracy.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 Rglm, glmnet, statsmodels' defaultGLM, or H2O's default.lorentzenchr commentedon Sep 26, 2026
Insightful analysis, indeed!
What we can do:
cakedev0 commentedon Sep 29, 2026
[another related finding, posting here as it might help and I don't want to forget about it]
I noticed that in float64,
newton-choleskydoesn't fail because the Hessian solve is inaccurate. It fails because of the conditioning check.scipy.linalg.solve(..., assume_a="sym")raises aLinAlgWarningwhen 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 oncoefstays tiny. If I keep the exact samesolvecall but simply ignore the warning (float64,tol=1e-10, relative error ofcoefvs the fit at offset 0):LinAlgWarningignoredA check that takes the intercept into account might push the float64 breakdown point much further, without centering. I haven't looked at float32.
lorentzenchr commentedon Sep 29, 2026
scipy.linalg.solvedoes not provide to set a limitrcond(e.g. aslstsq) when to raise a LinAlgWarning. Is there a way to distinguish this warning from others?cakedev0 commentedon Oct 8, 2026
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
glmand statsmodelsGLMuse QR or least squares, glmnet always centers, H2O standardizes by default), not because tests enforce it.lorentzenchr commentedon Oct 31, 2026
Note that once we had a
normalizeparameter 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()).sync: 2026-11-02