Closed
tatopenn-cell/scikit-learn
#1Labels
BugModerateAnything that requires some knowledge of conventions and best practicesmodule:preprocessing
Description
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]Metadata
Metadata
Assignees
Labels
BugModerateAnything that requires some knowledge of conventions and best practicesmodule:preprocessing
Activity
giorgiop commentedon Oct 27, 2015
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.
while on
masterthe last print is 0.giorgiop commentedon Oct 27, 2015
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_fitmay suffer the same issue. Maybe we could test for overflow for everypartial_fit? #3907jakevdp commentedon Dec 12, 2017
We'd probably want to use something like Welford's algorithm to avoid overflow and precision loss in the case of
partial_fit.agramfort commentedon Jul 16, 2018
Started to take care of this in #11549
jnothman commentedon Jul 16, 2018
Is part of the issue that previously we were using Python ints and now we're using numpy ints?
agramfort commentedon Jul 18, 2018
antonl commentedon May 22, 2024
This has been fixed already. The partial_fit documentation says it's been stabilized https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/preprocessing/_data.py#L879-L889
4 remaining items
ShamikOfficial commentedon Sep 2, 2026
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.
tatopenn-cell commentedon Oct 27, 2026
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
StandardScalerwrapper that uses thepartial_fitAPI, 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 at1.79e301):scikit-learn:inf(RuntimeWarning: overflow in add)Dense-Armor wrapper:1.7976931348623142e+301(Difference againstfit():0.00e+00)2.17e-172.13e-140.00e+00difference.The wrapper never reconstructs the cumulative sum. It simply keeps track of the delta (
d = x - mean) and updatesmean += d / nandm2 += 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.
lorentzenchr commentedon Oct 27, 2026
@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).
tatopenn-cell commentedon Oct 27, 2026
Thanks @lorentzenchr. I am happy to open the PR.
I will prepare a clean patch for
_incremental_mean_and_varthat 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.
FIX: prevent overflow in _incremental_mean_and_var
FIX: prevent overflow in _incremental_mean_and_var (with fallback)
Merge pull request scikit-learn#5602 from tatopenn-cell/fix/standard-…
FIX: prevent overflow in _incremental_mean_and_var
cakedev0 commentedon Oct 28, 2026
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?
lorentzenchr commentedon Oct 28, 2026
I think the original issue is legit. We should not close.
cakedev0 commentedon Oct 29, 2026
Hum, but do you have a counter argument to the fact this doesn't happen in practice? I checked and
StandardScaleralways accumulates statistics in float64* which is the best we can do without going overboard.With the kind of values from the reproducer, even
np.meanandnp.stdoverflows: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
lorentzenchr commentedon Oct 30, 2026
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.