Skip to content

DOC Document approximate stratification in StratifiedShuffleSplit - #33728

Open
RudrenduPaul wants to merge 4 commits into
scikit-learn:mainfrom
RudrenduPaul:doc/stratified-shuffle-split-approximate-mode-note
Open

RudrenduPaul wants to merge 4 commits into
scikit-learn:mainfrom
RudrenduPaul:doc/stratified-shuffle-split-approximate-mode-note

Conversation

@RudrenduPaul

@RudrenduPaul RudrenduPaul commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #28994.

Adds a .. note:: to the StratifiedShuffleSplit class docstring explaining that per-class sample allocation uses an approximation of the multivariate hypergeometric distribution (via _approximate_mode). This approximation can be off by one sample per class.

Context

As reported in #28994 and confirmed by @glemaitre, when a class is heavily underrepresented relative to the total dataset size (e.g., 2 minority samples out of 50,000), StratifiedShuffleSplit may allocate zero samples from that class to either the train or test split. This happens even though both n_train and n_test satisfy the existing >= n_classes validation check.

Concretely, with 2 minority samples out of 50,000 total:

  • _approximate_mode([2, 49998], n_train, rng) assigns 1 to train
  • _approximate_mode([1, 49999], n_test, rng) where 1/50000 * n_test < 0.5, so the minority class gets 0 in test

This behavior is surprising to users who expect the stratification guarantee to hold.

What changed

Added a .. note:: block to the StratifiedShuffleSplit class docstring explaining:

  • The per-class allocation is approximate (can be off by ±1)
  • Heavily underrepresented classes may receive 0 samples in a split
  • Users should consider StratifiedKFold for such cases, or ensure sufficient minority class membership

Checklist

  • I have read the contributing guidelines
  • The change is a documentation-only addition to an existing class
  • No code logic was modified

AI Assistance Disclosure (required per AGENTS.md)
This pull request includes code written with the assistance of AI (Claude Code).
All changes have been read, understood, and verified by the human contributor (Rudrendu Paul).

RudrenduPaul added a commit to RudrenduPaul/scikit-learn that referenced this pull request Apr 12, 2026

@ArturoAmorQ ArturoAmorQ left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @RudrenduPaul. Here's a batch of comments.

For extra context: Train is allocated first from class_counts, and test is allocated from class_counts_remaining. So in the edge case where a class has very few samples, the train split consumes them all, leaving none for the test set. See :

for _ in range(self.n_splits):
# if there are ties in the class-counts, we want
# to make sure to break them anew in each iteration
n_i = _approximate_mode(class_counts, n_train, rng)
class_counts_remaining = class_counts - n_i
t_i = _approximate_mode(class_counts_remaining, n_test, rng)

Comment on lines +1 to +5
- :class:`model_selection.StratifiedShuffleSplit` now documents that
per-class sample allocation uses an approximation of the multivariate
hypergeometric distribution, which can be off by one sample per class.
Heavily underrepresented classes may receive zero samples in a split.
By :user:`Rudrendu Paul <RudrenduPaul>`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need a change log for a documentation change. Please revert.

Comment thread sklearn/model_selection/_split.py Outdated
Comment on lines +2259 to +2270
.. note::

The per-class allocation of samples to train and test splits is based
on an approximation of the multivariate hypergeometric distribution.
This approximation can be off by one sample per class. As a result,
when a class is heavily underrepresented relative to the total dataset
size, it may receive zero samples in either the train or test split
even though both ``n_train`` and ``n_test`` are greater than or equal
to the number of classes. In such cases, consider using
:class:`StratifiedKFold` instead, or ensure that the least populated
class has sufficiently many members relative to the split sizes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Less is more

Suggested change
.. note::
The per-class allocation of samples to train and test splits is based
on an approximation of the multivariate hypergeometric distribution.
This approximation can be off by one sample per class. As a result,
when a class is heavily underrepresented relative to the total dataset
size, it may receive zero samples in either the train or test split
even though both ``n_train`` and ``n_test`` are greater than or equal
to the number of classes. In such cases, consider using
:class:`StratifiedKFold` instead, or ensure that the least populated
class has sufficiently many members relative to the split sizes.

Comment thread sklearn/model_selection/_split.py Resolved
@RudrenduPaul

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @ArturoAmorQ! All four points make sense:

  1. I'll revert the changelog file — agreed, doc-only changes don't need one.
  2. I'll drop that section per your Less is more suggestion.
  3. I'll re-anchor the edge-case mention to follow the stratification definition, using your suggested wording verbatim.
  4. Thanks for the pointer to lines 2380–2385 — train-first allocation from class_counts (with test drawing from class_counts_remaining) is the right mechanism to ground the explanation in. I'll fold that into the prose.

Will push an update shortly.

@ArturoAmorQ ArturoAmorQ left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks. But I rather wait for @glemaitre or someone else to confirm my suggested wording, because the "±1 counts" refers to the rounding in _approximate_mode itself, but the resulting difference between train and test counts for that class can be larger.
From the example in #28994, 2 samples of class 0 and a train/test ratio of 80/20, the proportional allocation gives 1.6 samples to train, which rounds up to 2, consuming both samples.

@AnneBeyer AnneBeyer added the Waiting for Second Reviewer First reviewer is done, need a second one! label Jul 22, 2026

@PranavAchar01 PranavAchar01 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documenting this is worthwhile, thanks. I went looking for the behaviour to check the wording and found it is sharper than the note suggests, which I think makes it more useful to state directly.

The note says the count "can differ by one, which ... may result in no samples of that class in the test set". In practice a class gets zero test samples exactly when

n_samples_in_class * test_size < 0.5

and when that holds it happens on every split, not occasionally. Sweeping it (200 majority samples, 30 seeds each):

 n_minor  test_size   n*ts     observed
       2        0.1   0.20     zero on all seeds
       2        0.2   0.40     zero on all seeds
       2       0.25   0.50     never zero
       3        0.1   0.30     zero on all seeds
       3        0.2   0.60     never zero
       4        0.1   0.40     zero on all seeds
       4        0.2   0.80     never zero

The predicted and observed columns agreed on every combination I tried.

That also explains the report in #28994 exactly: with two samples in the minority class and the usual test_size=0.2, 2 * 0.2 = 0.4 < 0.5, so the test set never receives one and you need a third sample. Which is the issue's title.

So a reader hitting this can check the condition directly rather than discovering it empirically. Something like:

A class receives no samples in the test set when its number of samples
multiplied by test_size rounds to zero, that is when it is below 0.5.
For example a class with two samples and test_size=0.2 will never appear
in the test set.

Also a small wording point on the current text: "the per-class sample count between train and test splits can differ by one" reads as though train and test counts are being compared to each other, where I think the intent is that each split's per-class count can differ by one from the exact proportional allocation.

Only a suggestion, and "may" is not wrong, but since the underlying behaviour is deterministic it seems a shame not to give the reader the actual condition.

@RudrenduPaul

Copy link
Copy Markdown
Contributor Author

Thanks both for the detailed review!

@PranavAchar01 I independently verified your condition against the actual _approximate_mode/StratifiedShuffleSplit implementation (both by tracing the rounding logic and by running the split 50x across several (n_minority, test_size) combinations). The n_samples_in_class * test_size < 0.5 threshold matches observed behavior exactly in every case I tried (deterministic — 100% of seeds on one side of the threshold, 0% on the other), so I've folded it into the docstring with a short worked example.

@ArturoAmorQ your point about the wording is also correct: since class_counts_remaining sums exactly to n_test in the full-allocation case, the test-side _approximate_mode call is just a deterministic pass-through of class_counts - n_i, so all the actual rounding uncertainty lives in the train-side allocation. That means the "±1" guarantee is per-split-vs-its-own-proportional-allocation, not train-count-vs-test-count — the old wording could be read as the latter, which is misleading (as your own #28994 example shows: 2 samples, 80/20 split → train gets 2, test gets 0, a difference of 2, not 1).

Changes pushed in ec84acaa84:

  • Replaced the ambiguous "differ by one" sentence with: each split's per-class count can differ by at most one from that split's own proportional allocation (not from the other split's count), plus the exact zero-test-sample condition and a 2-sample/test_size=0.2 worked example.
  • The changelog entry (33728.enhancement.rst) was already reverted per @ArturoAmorQ's request in a prior commit, and it's confirmed absent from the current diff.

Ran the full Stratified* test suite (97 passed) plus the docstring doctest locally against this branch, no regressions.

Over to @glemaitre for a final look at the wording.

…Split

Add a note to the StratifiedShuffleSplit class docstring explaining that
per-class sample allocation uses an approximation of the multivariate
hypergeometric distribution. This approximation can be off by one sample
per class, which means that a heavily underrepresented class may receive
zero samples in either split even when n_train and n_test both satisfy
the n_classes requirement. Addresses scikit-learn#28994.

Built by Rudrendu Paul, developed with Claude Code
Per @ArturoAmorQ review: remove changelog file (not needed for docs),
shorten the approximation note, and move it after the stratification
introduction.

Built by Rudrendu Paul, developed with Claude Code
Give the exact deterministic condition (n_samples_in_class * test_size
< 0.5) with a worked example, and correct the wording so it compares
each split's count to its own proportional allocation rather than
train to test directly.
@RudrenduPaul
RudrenduPaul force-pushed the doc/stratified-shuffle-split-approximate-mode-note branch from ec84aca to d3b5427 Compare August 9, 2026 06:07

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

StratifiedShuffleSplit requires three copies of a lower class, rather than 2

4 participants