Skip to content

FIX: prevent overflow in _incremental_mean_and_var - #35248

Closed
tatopenn-cell wants to merge 1 commit into
scikit-learn:mainfrom
tatopenn-cell:fix/standard-scaler-overflow
Closed

tatopenn-cell wants to merge 1 commit into
scikit-learn:mainfrom
tatopenn-cell:fix/standard-scaler-overflow

Conversation

@tatopenn-cell

Copy link
Copy Markdown

The cumulative-sum formula reconstructs last_sum = last_mean * last_sample_count and new_sum, both of which overflow on long streams with large values. The delta-based update of Chan, Golub and LeVeque (1979) is algebraically equivalent but never reconstructs the sum.

This fixes the mean and the variance in one pass. The previous attempt (#11549) fixed only the mean and left the cross-term of the variance untouched, which is why it was closed as incomplete.

Two non-regression tests:

  • test_incremental_mean_and_var_large_values_no_overflow
  • test_incremental_mean_and_var_constant_values

Fixes #5602.

Reference Issues/PRs

What does this implement/fix? Explain your changes.

Introduce yourself

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

The cumulative-sum formula reconstructs last_sum = last_mean *
last_sample_count and new_sum, both of which overflow on long
streams with large values. The delta-based update of Chan, Golub
and LeVeque (1979) is algebraically equivalent but never
reconstructs the sum.

This fixes the mean and the variance in one pass. The previous
attempt (scikit-learn#11549) fixed only the mean and left the cross-term of the
variance untouched, which is why it was closed as incomplete.

Two non-regression tests:
- test_incremental_mean_and_var_large_values_no_overflow
- test_incremental_mean_and_var_constant_values

Fixes scikit-learn#5602.
@github-actions

Copy link
Copy Markdown

Thank you for opening your first pull request to scikit-learn! 🎉

To help get your contribution reviewed, please make sure that:

  • You have filled out the pull request template.

  • The pull request addresses an existing issue that is ready for contribution (e.g. not tagged as 'Needs Triage', 'Needs Decision', ...). If you are proposing a new feature, please open an issue to discuss it first.

  • There are no other open pull requests already targeting the same issue.

  • You have followed the pull request checklist. In particular, linting and tests should pass.

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Oct 27, 2026
@github-actions

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


ruff check

ruff detected issues. Please run ruff check --fix --output-format=full locally, fix the remaining issues, and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

sklearn/utils/tests/test_extmath.py:1184:14: F821 Undefined name `StandardScaler`
     |
1182 |     batch = rng.uniform(min_f, min_f, size=(500000, 1))
1183 |
1184 |     scaler = StandardScaler(with_std=False).fit(batch)
     |              ^^^^^^^^^^^^^^ F821
1185 |     expected_mean = scaler.mean_
     |

sklearn/utils/tests/test_extmath.py:1187:15: F821 Undefined name `StandardScaler`
     |
1185 |     expected_mean = scaler.mean_
1186 |
1187 |     iscaler = StandardScaler(with_std=False)
     |               ^^^^^^^^^^^^^^ F821
1188 |     for _ in range(100):
1189 |         iscaler = iscaler.partial_fit(batch)
     |

sklearn/utils/tests/test_extmath.py:1198:14: F821 Undefined name `StandardScaler`
     |
1196 |     """Non-regression test: constant data with zero variance."""
1197 |     X = np.ones((1000, 2)) * 42.0
1198 |     scaler = StandardScaler().fit(X)
     |              ^^^^^^^^^^^^^^ F821
1199 |
1200 |     iscaler = StandardScaler()
     |

sklearn/utils/tests/test_extmath.py:1200:15: F821 Undefined name `StandardScaler`
     |
1198 |     scaler = StandardScaler().fit(X)
1199 |
1200 |     iscaler = StandardScaler()
     |               ^^^^^^^^^^^^^^ F821
1201 |     for i in range(0, 1000, 10):
1202 |         iscaler = iscaler.partial_fit(X[i:i + 10])
     |

Found 4 errors.

ruff format

ruff detected issues. Please run ruff format locally and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

--- sklearn/utils/extmath.py
+++ sklearn/utils/extmath.py
@@ -1258,10 +1258,7 @@
             updated_unnormalized_variance = (
                 last_unnormalized_variance
                 + new_unnormalized_variance
-                + delta**2
-                * last_sample_count
-                * new_sample_count
-                / updated_sample_count
+                + delta**2 * last_sample_count * new_sample_count / updated_sample_count
             )
 
             zeros = last_sample_count == 0

--- sklearn/utils/tests/test_extmath.py
+++ sklearn/utils/tests/test_extmath.py
@@ -1199,8 +1199,7 @@
 
     iscaler = StandardScaler()
     for i in range(0, 1000, 10):
-        iscaler = iscaler.partial_fit(X[i:i + 10])
+        iscaler = iscaler.partial_fit(X[i : i + 10])
 
     assert_allclose(iscaler.mean_, scaler.mean_, rtol=1e-12)
     assert_allclose(iscaler.var_, scaler.var_, atol=1e-15)
-

2 files would be reformatted, 961 files already formatted

Generated for commit: d251443. Link to the linter CI: here

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

Labels

CI:Linter failure The linter CI is failing on this PR module:utils size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: StandardScaler partial_fit overflows

1 participant