Skip to content

Ridge and RidgeCV has different result even if alpha is the same #26848

Closed

Description

@johnlcf

Describe the bug

(From discussion in #26733)

In one of my dataset, I try to specify only one value in alphas in RidgeCV, and expects RidgeCV should give me the same result as using Ridge with same alpha value. But it would not (see the code and output below). And the RidgeCV result seems abnormal.

I found that the problem is related to some large values we used in sample_weight. I can reproduce it with make_regression.

I guess the large value in sample_weight may caused some overflow in RidgeCV intermediate calculation?
Given that RidgeCV and Ridge are using different solvers under the hood, I think it is not surprise that they may behave differently in this case? I just scaled down the weight and the problem is gone.

Steps/Code to Reproduce

import numpy as np
from sklearn.linear_model import Ridge, RidgeCV
from sklearn.datasets import make_regression

X, y = make_regression(n_features=2)
wgt = np.random.randint(2e5, 2e11, size=100)

print('=== RidgeCV ===')
clf = RidgeCV(alphas=[0.001],fit_intercept=True).fit(
    X=X,
    y=y,
    sample_weight=wgt,
)
print(f'{clf.coef_ = }')
print(f'{clf.intercept_ = }')
print(f'{clf.alpha_ = }')

print('=== Ridge ===')
clf = Ridge(alpha=0.001,fit_intercept=True).fit(
    X=X,
    y=y,
    sample_weight=wgt
)
print(f'{clf.coef_ = }')
print(f'{clf.intercept_ = }')

Expected Results

The output of RidgeCV and Ridge is the same.

Actual Results

=== RidgeCV ===
'clf.coef_ = array([-95.63781897,  31.72140137])'
'clf.intercept_ = 2.6375015138569937'
'clf.alpha_ = 0.001'
=== Ridge ===
'clf.coef_ = array([41.8887401, 33.131992 ])'
'clf.intercept_ = -4.440892098500626e-16'

Versions

I am using scikit-learn 1.2.1 on python 3.8 on Linux.

Activity

  1. added
    Needs Triage
    on Jul 17, 2023
  2. glevv commented on Jul 17, 2023

    @glevv
    Contributor

    If you set cv parameter in RidgeCV, you will get the same results. Smaller range of sample weights also gives identical values. Furthermore, if you set gcv_mode to "eigen" you will also get the same result. Thus bug is somewhere in _RidgeGCV in "svd" mode (both sparse and dense options, wether we fit intercept or not does not make any difference).

  3. glevv commented on Jul 18, 2023

    @glevv
    Contributor

    This is also affecting RidgeClassifier and RidgeClassifierCV, since after _check_gcv_mode call, "svd" solver mode will be returned.

  4. jona-sassenhagen commented on Jul 20, 2023

    @jona-sassenhagen
    Contributor

    I think this is not specific to weights or even exclusive to the svd, but about numerical instability for very large values?

    Try:

    import numpy as np
    
    from sklearn.linear_model._ridge import _RidgeGCV
    
    est = _RidgeGCV(fit_intercept=False)
    
    n = 1000
    y = np.random.randn(n)
    X = np.random.randn(n, 2)
    X[:, 0] += y
    X[:, 0] -= X[:, 0].mean()
    
    sqrt_sw = np.ones(n, dtype=X.dtype)  # no weights
    alpha = 1.
    
    algos = {
        'eigen': (est._eigen_decompose_gram, est._solve_eigen_gram),
        'svd': (est._svd_decompose_design_matrix, est._solve_svd_design_matrix),
    }
    
    for scale in (1e0, 1e1, 1e7, 1e12):
        X_ = X * scale
        for algo, (decompose, solve) in algos.items():
            X_mean, *decomposition = decompose(X_, y, sqrt_sw)
            _, dual_coefs = solve(alpha, y, sqrt_sw, X_mean, *decomposition)
            print(f'Algorithm: {algo}, Scaling: {scale}, Coefs: {(dual_coefs.T @ X_) * scale}')
    

    SVD breaks down faster but eventually eigen also breaks down.

    The workaround would be rescaling the inputs and (if applicable) the weights.

  5. glevv commented on Jul 20, 2023

    @glevv
    Contributor

    I don't think it's reasonable to force scaling on input, but it's possible to give a warning if input range/dispersion is too big. Scaling sample weights is needed but, there should be a consensus on how to do it correctly.

  6. jona-sassenhagen commented on Jul 20, 2023

    @jona-sassenhagen
    Contributor

    I think it might also be possible to rescale internally, transparently.

    Although a warning internally would be the cheap and available option. StandardScaler for example also has such a warning.

  7. jona-sassenhagen commented on Jul 20, 2023

    @jona-sassenhagen
    Contributor

    According to the above simulations, things start breaking down around a scale of 100_000 for a feature.

  8. added
    Needs Investigation
    and removed
    Needs Triage
    on Jul 27, 2023
  9. lorentzenchr commented on Aug 5, 2023

    @lorentzenchr
    Member

    As stated, this bug seems to be caused by the large sample weights. A possible solution could be to rescale the sample weights internally and therefore also the alpha values.

    But before trying this, I would be interested to know where exactly the error happens.

  10. EdenRochmanSharabi commented on Mar 27, 2026

    @EdenRochmanSharabi
    Contributor

    I'm looking into this and working on a fix.

  11. added a commit that references this issue on Mar 27, 2026
    73fcf3a
  12. EdenRochmanSharabi commented on Mar 30, 2026

    @EdenRochmanSharabi
    Contributor

    Looking at this further, I believe the root cause is clear and the fix is straightforward.

    When _RidgeGCV processes sample weights, it calls _rescale_data which computes X_rescaled = sqrt(sample_weight) * X. With weights on the order of 1e11, sqrt(sw) is ~3e5, so the rescaled design matrix has values inflated by that factor. As @jona-sassenhagen demonstrated, the eigendecomposition breaks down around a feature scale of ~100,000.

    PR #33020 improved the numerical formulas significantly (fixing the small-alpha instability in #32459), but the large sample weight case still triggers the same fundamental issue since _rescale_data does not normalize the weights.

    Following @lorentzenchr's suggestion to "rescale the sample weights internally and therefore also the alpha values," I've been testing a fix that normalizes sample_weight to max=1 in _RidgeGCV.fit() before preprocessing, and scales alpha by the original max weight to preserve the optimization problem.

    Mathematically, the Ridge objective min_w sum_i s_i (y_i - x_i'w)^2 + alpha ||w||^2 has the same minimizer if we replace s_i with s_i / sw_max and alpha with alpha / sw_max, since this just divides the entire objective by a positive constant. This means sqrt(sw) stays in [0, 1], so X is never inflated beyond its original scale.

    Would this approach work? Happy to open a PR with a regression test using the reproducer from this issue.

  13. lorentzenchr commented on May 28, 2026

    @lorentzenchr
    Member

    @antoinebaker Did #32459 also fix this issue?

  14. antoinebaker commented on Jun 1, 2026

    @antoinebaker
    Member

    @antoinebaker Did #32459 also fix this issue?

    It seems so, now on main:

    === RidgeCV ===
    clf.coef_ = array([49.9308288 , 26.97170071])
    clf.intercept_ = np.float64(3.0531133177191805e-16)
    clf.alpha_ = 0.001
    === Ridge ===
    clf.coef_ = array([49.9308288 , 26.97170071])
    clf.intercept_ = np.float64(8.881784197001252e-16)
    
  15. lorentzenchr commented on Jun 1, 2026

    @lorentzenchr
    Member

    Great. Let‘s close then.

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