Skip to content

Fix StandardScaler for columns far from zero and constant columns - #549

Merged
Mec-iS merged 4 commits into
smartcorelib:mainfrom
bardrop-oss:fix-standard-scaler-constant-column
Nov 23, 2026
Merged

Mec-iS merged 4 commits into
smartcorelib:mainfrom
bardrop-oss:fix-standard-scaler-constant-column

Conversation

@bardrop

@bardrop bardrop commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #548

Checklist

  • My branch is up-to-date with main branch.
  • Everything works and tested on latest stable Rust.
  • Coverage and Linting have been applied (linting only, I did not run coverage locally)

Current behaviour

variance computes sum(x^2) / n - mean^2. For values far from zero (for example Unix timestamps) the result is wrong, 0 or negative. StandardScaler then returns values near 1e307. RidgeRegression, Lasso and ElasticNet return "Cannot rescale constant column".

StandardScaler replaces a zero standard deviation by f64::MIN_POSITIVE. For f32 this becomes 0, so a constant column becomes NaN. For f64, new values in that column become very large.

New expected behaviour

variance (and so std_dev) uses Welford's algorithm, in one pass and without allocation. The variance of a constant column is exactly 0.

StandardScaler divides a column with zero variance by 1, as scikit-learn does.

Change logs

Fixed

  • linalg: numerically stable variance and std_dev for ArrayView1 and ArrayView2.
  • preprocessing: StandardScaler for constant columns.

Eight tests fail before the change. Two of them are the old ensure_std_valid tests, which expected f64::MIN_POSITIVE. One GaussianNB test compared variances with assert_eq!; its values changed in the last digit and are now exactly 2/3 and 2/9. cargo test --all-features, clippy and fmt pass.

@bardrop
bardrop requested a review from Mec-iS as a code owner November 23, 2026 09:07
@Mec-iS

Mec-iS commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Thanks for fixing the timestamp and constant-column cases. I reviewed c757d66 and have one requested change before merge, plus two non-blocking suggestions.

  1. Blocking — variance can still be zero for a nonconstant column (src/linalg/basic/arrays.rs, both variance implementations). I replayed the update in binary64: [1e16, 1e16 + 2] gives population variance 2.0, and reversing the inputs gives 0.0; the correct result is 1.0 in both orders. Both inputs are representable, but the running mean rounds away the spread. The zero result sends StandardScaler down its constant-column path. Could you subtract the first observation as a fixed offset before applying Welford’s update, and add regression tests for both orders in ArrayView1 and both axes in ArrayView2? This keeps the calculation one-pass without adding scratch storage.
  2. Non-blocking — f32 scale can still round to zero (src/preprocessing/numerical.rs). For a column containing 0.0f32 and the smallest positive f32 subnormal, the scale is positive in f64 but rounds to zero when cast to f32 before division. This is pre-existing. A follow-up could normalize in f64 before casting the result back to T.
  3. Non-blocking — use a tolerance in the GaussianNB variance test (src/naive_bayes/gaussian.rs). Compare against 2.0 / 3.0 and 2.0 / 9.0 within a tight tolerance rather than pinning the last bit of the new recurrence.

I verified the variance counterexample separately; I did not run the Rust suite locally.

@Mec-iS

Mec-iS commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

@bardrop please take a look to the review ^

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.47368% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.27%. Comparing base (9eaae9e) to head (0c13c67).
⚠️ Report is 231 commits behind head on main.

Files with missing lines Patch % Lines
src/linalg/basic/arrays.rs 88.88% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main     #549       +/-   ##
===========================================
+ Coverage   43.97%   87.27%   +43.30%     
===========================================
  Files          85      100       +15     
  Lines        7281     9999     +2718     
===========================================
+ Hits         3202     8727     +5525     
+ Misses       4079     1272     -2807     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bardrop

bardrop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, good catch. Fixed in the last commit:

  1. Both variance implementations now subtract the first value before Welford's update. [1e16, 1e16 + 2] gives 1.0 in both orders. Tests cover ArrayView1 and both axes of ArrayView2.
  2. Agree, I can do that as a follow-up. In this PR a scale that rounds to zero in f32 becomes 1, so such a column is only centered.
  3. The GaussianNB test now compares against 2/3 and 2/9 with a 1e-15 tolerance.

cargo test --lib (714 pass), cargo fmt --check and clippy are clean.

@bardrop

bardrop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

CI caught a test I missed because I only ran the default features: lazy_fit_matches_eager_for_normalization_and_penalty_options with lazy-normalization. Only the n=3, p=5, ratio=1 normalized case is close to its limit. The eager/lazy difference there is 8.1e-7 on main, 6.2e-8 on the first commit and 1.5e-6 now, against a limit of 1e-6. All other cases stay below 1e-9. With more columns than rows and no L2 penalty the solver reacts to the last bit of the scales, so I set that f64 tolerance to 1e-5. --all-features passes now.

@Mec-iS

Mec-iS commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Re-reviewed through c59ce37. The earlier blocker is resolved: subtracting the first value before Welford's update fixes the 1e16 / 1e16 + 2 case in both input orders, and the new tests cover ArrayView1 and both ArrayView2 axes. The GaussianNB tolerance change also looks good.

No new merge blocker from me. One non-blocking suggestion on the ElasticNet test: the lazy/eager scales already come from the same std_dev(0) path, so the 1e-6 -> 1e-5 widening looks like solver sensitivity. Consider limiting the wider tolerance to the sensitive p > n case, or recording the observed difference, so a real lazy/eager regression is not hidden elsewhere.

I did not see check runs for the latest head when I looked, so please confirm CI is green before merge. The f32 subnormal-scale case remains a possible follow-up.

@bardrop

bardrop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the re-review. The wider tolerance now applies only to the normalized p > n, ratio 1 case, with the observed 1.5e-6 difference noted in a comment. Every other case is back to 1e-6. cargo test --lib --all-features gives 827 passed. The workflow runs on this PR may need your approval to start, so I can't confirm CI from here.

@bardrop

bardrop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

All checks are green on 0c13c67 now, including the windows, wasm32 and i686 jobs.

@Mec-iS

Mec-iS commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Thanks

@Mec-iS
Mec-iS merged commit 2cb1c6f into smartcorelib:main Nov 23, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

StandardScaler: wrong output for columns far from zero and for constant columns

2 participants