Skip to content

BUG: StandardScaler partial_fit overflows #5602

Closed
tatopenn-cell/scikit-learn
#1

Description

@giorgiop

The recent implementation of partial_fit for StandardScaler can overflow. A use case there is to transform indefinitely long stream of data, but that is problematic with the current implementation. The reason is that to compute the running mean, we keep track of the sample sum.

Here the code to reproduce the behavior. To simulate long stream of data would take long time; instead, I use samples with very large norm but the effect is the same. The same batch is presented to the transformer many times. The mean should be same.

from sklearn.preprocessing import StandardScaler
import numpy as np

rng = np.random.RandomState(0)

def gen_1d_uniform_batch(min_, max_, n):
    return rng.uniform(min_, max_, size=(n, 1))

max_f = np.finfo(np.float64).max / 1e5
min_f = max_f / 1e2
stream_dim = 100
batch_dim = 500000
print("mean overflow: batch vs online on %d repetitions" % stream_dim)

X = gen_1d_uniform_batch(min_=min_f, max_=min_f, n=batch_dim)

scaler = StandardScaler(with_std=False).fit(X)
print(scaler.mean_)
[  1.79769313e+301]

iscaler = StandardScaler(with_std=False)
batch = gen_1d_uniform_batch(min_=min_f, max_=min_f, n=batch_dim)
for _ in range(stream_dim):
    iscaler = iscaler.partial_fit(batch)
RuntimeWarning: overflow encountered in add
  updated_mean = (last_sum + new_sum) / updated_sample_count

print(iscaler.mean_)
[ inf]

Activity

  1. giorgiop commented on Oct 27, 2015

    @giorgiop
    ContributorAuthor

    A simple workaround is to keep track of the sample mean itself, instead of the sample sum. Here a gist. However, there is caveat: the computation of the sample variance is less numerically accurate.

    from sklearn.preprocessing.data import StandardScaler
    import numpy as np
    
    rng = np.random.RandomState(0)
    
    def gen_1d_uniform_batch(min_, max_, n):
        return rng.uniform(min_, max_, size=(n, 1))
    
    max_f = 1e15
    min_f = max_f / 1e3
    stream_dim = 10000
    batch_dim = 1000
    print("var divergence: batch vs online on %d repetitions" % stream_dim)
    
    X = gen_1d_uniform_batch(min_=min_f, max_=min_f, n=batch_dim)
    
    scaler = StandardScaler().fit(X)
    iscaler = StandardScaler()
    
    batch = gen_1d_uniform_batch(min_=min_f, max_=min_f, n=batch_dim)
    for _ in range(stream_dim):
        iscaler = iscaler.partial_fit(batch)
    
    print(scaler.var_)
    [  0.]
    print(iscaler.var_)
    [  1.11203573e-05]
    

    while on master the last print is 0.

  2. giorgiop commented on Oct 27, 2015

    @giorgiop
    ContributorAuthor

    Notice that while in the first code snippet I use large numbers to simulate the online stream, in the second case the lenght of the stream does not matter. It is the absolute value of the mean itself that is problematic. Indeed, if you run the second script with smaller max_f, everything is smooth. This is the offending step, which should trigger a potential catastrophic cancellation.

    I think this means that we want this change in the code, but I would like to hear other opinions first. Maybe @jakevdp ?

    I have no idea if other estimators with partial_fit may suffer the same issue. Maybe we could test for overflow for every partial_fit? #3907

  3. jakevdp commented on Dec 12, 2017

    @jakevdp
    Member

    We'd probably want to use something like Welford's algorithm to avoid overflow and precision loss in the case of partial_fit.

  4. added
    Moderate
    on Dec 13, 2017
  5. agramfort commented on Jul 16, 2018

    @agramfort
    Member

    Started to take care of this in #11549

  6. jnothman commented on Jul 16, 2018

    @jnothman
    Member

    Is part of the issue that previously we were using Python ints and now we're using numpy ints?

  7. agramfort commented on Jul 18, 2018

    @agramfort
    Member
  8. antonl commented on May 22, 2024

    @antonl
  9. 4 remaining items

  10. ShamikOfficial commented on Sep 2, 2026

    @ShamikOfficial

    Opened #34874 — falls back to a delta-based mean/variance update when the accumulated sum overflows. Tested with 100 partial_fit batches of 2**1020 values.

  11. tatopenn-cell commented on Oct 27, 2026

    @tatopenn-cell

    I have been following this issue for a while, as I maintain a backend library for real-time telemetry (Dense-Armor), and I can confirm the problem is still present on main.

    @EdenRochmanSharabi, the Chan, Golub, and LeVeque formulation you proposed is mathematically correct. To help move this forward, I built a minimal drop-in StandardScaler wrapper that uses the partial_fit API, but delegates the update to the parallel Welford accumulator we use in production.

    Here are the results on the original reproducer (stream_dim=100, batch_dim=500000, values at 1.79e301):

    1. Extreme Values (Overflow test)
    • scikit-learn: inf (RuntimeWarning: overflow in add)
    • Dense-Armor wrapper: 1.7976931348623142e+301 (Difference against fit(): 0.00e+00)
    1. Normal Streaming Data (1000 batches of 10 samples)
    • Difference in mean: 2.17e-17
    • Difference in variance: 2.13e-14
    • Constant data (variance=0) and scale fallback to 1.0: 0.00e+00 difference.

    The wrapper never reconstructs the cumulative sum. It simply keeps track of the delta (d = x - mean) and updates mean += d / n and m2 += d**2 * (n_old * n_new) / n_total.

    Given there are currently two open PRs (#34664 and #34874) addressing this, I am happy to share the exact wrapper code and the test suite, or help review the existing PRs so this can finally be merged. Let me know if it's useful.

  12. lorentzenchr commented on Oct 27, 2026

    @lorentzenchr
    Member

    @tatopenn-cell We are still open for a high quality PR fixing this issue, with a human-in-the-loop to communicate with (here on github).

  13. tatopenn-cell commented on Oct 27, 2026

    @tatopenn-cell

    Thanks @lorentzenchr. I am happy to open the PR.

    I will prepare a clean patch for _incremental_mean_and_var that uses the parallel Welford / Chan-Golub-LeVeque formulation, including a test suite that covers the original reproducer and the constant-input case.

    I will open the PR in the next few hours and tag you for review.

  14. added 4 commits that reference this issue on Oct 27, 2026
    226f342
    7c58e11
    f4f6bca
    1c62f9c
  15. cakedev0 commented on Oct 28, 2026

    @cakedev0
    Member

    I'd propose to close this as won't fix. The sum overflows only when |mean| × n_samples > 1.8e308: even with 1e15 samples, a feature would need a mean above 1e293. In 11 years, nobody reported hitting this on real data, but the issue has now attracted 4 PRs (#11549, #34664, #34874, #35250).

    A complete fix would also need to cover the variance (the default with_std=True), which makes it a non-trivial change to maintain for a case that doesn't happen in practice.

    WDYT @lorentzenchr?

  16. lorentzenchr commented on Oct 28, 2026

    @lorentzenchr
    Member

    I think the original issue is legit. We should not close.

  17. cakedev0 commented on Oct 29, 2026

    @cakedev0
    Member

    Hum, but do you have a counter argument to the fact this doesn't happen in practice? I checked and StandardScaler always accumulates statistics in float64* which is the best we can do without going overboard.

    With the kind of values from the reproducer, even np.mean and np.std overflows:

    np.mean([1e303] * 500000), np.std([1e155, -1e155]) returns (np.float64(inf), np.float64(inf)).


    *Well, except for float32 sparse input, and this one might be worth fixing as it's also relatively easy to fix, contrary to the float64 case. I opened the PR: #35260

  18. lorentzenchr commented on Oct 30, 2026

    @lorentzenchr
    Member

    You are right. The reproducer is hard to read (and does not execute). If we protect the float64 overfllow, we only gain about a factor of 2. Then it will overflow not matter what we do.
    So let's close.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugModeratemodule:preprocessing

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions