Skip to content

Stop float error in split ratios from changing split sizes - #1507

Open
AxelNoun wants to merge 3 commits into
sunlabuiuc:masterfrom
AxelNoun:fix/split-ratio-float-truncation
Open

AxelNoun wants to merge 3 commits into
sunlabuiuc:masterfrom
AxelNoun:fix/split-ratio-float-truncation

Conversation

@AxelNoun

@AxelNoun AxelNoun commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Contributor: Axel Coiffard-Donaty (@AxelNoun)

Contribution Type: Bug fix

Description:

Fixes #1506.

The ratio splitters cut at int(n * (ratios[0] + ratios[1])). 0.7 + 0.1 is 0.7999999999999999 in floating point, so [0.7, 0.1, 0.2] on 10 patients gave 7/0/3 instead of 7/1/2: an empty validation part. For those ratios the sizes were wrong for 68 of the sizes n = 1..500.

The fix adds a private helper, _cut_index(n, fraction), which takes the product as an integer when it is within a relative 1e-12 of one and otherwise truncates, and uses it in every splitter that cuts by ratios (split_by_visit, split_by_patient, split_by_sample, the conformal and TUH variants, PatientSplit). Sizes without float error are unchanged for ratios written with d decimals as long as n * 10**d < 10**12 (7 decimals up to 100,000 items); above that bound a product within 1e-12 relative of an integer is rounded to it.

Effect on existing splits:

  • For the affected sizes, the shuffle is unchanged and one cut moves by one, so one item moves between two adjacent parts. Other sizes give the same partition as before.
  • Split.to_dict is the processed-cache key and "must change whenever the parts would". PatientSplit.to_dict now carries the name of the cut rule, so caches built with the old sizes are rebuilt, not reused. This rebuilds every PatientSplit cache once, including the unaffected ones; I can drop this part if you prefer to keep the keys.

Files to Review:

  • pyhealth/datasets/splitter.py: _cut_index, its 22 call sites, and PatientSplit.to_dict.
  • docs/api/datasets/pyhealth.datasets.splitter.rst: the fit_split example with its cuts entry.
  • tests/core/test_split_ratio_rounding.py (new): _cut_index against exact rational arithmetic for 7 ratio sets and n = 0..500; sizes of every ratio splitter and of PatientSplit on the failing cases; unchanged sizes where there is no float error; the cache description; the single item that moves.

Testing:

  • pytest tests/core/test_split_ratio_rounding.py: 13 passed. With the old formula in _cut_index, the size tests fail.
  • The 9 test files that use a ratio splitter pass on Linux.
  • python tools/check_pr_rules.py: passed.

Out of scope: the same int(len * ratio) cut in pyhealth/medcode/pretrained_embeddings/kg_emb/datasets/splitter.py and pyhealth/models/medlink/utils.py.

The ratio splitters cut at int(n * (ratios[0] + ratios[1])). In floating
point 0.7 + 0.1 is 0.7999999999999999, so with ratios [0.7, 0.1, 0.2]
the second cut came one item early whenever n * 0.8 is a whole number:
10 patients gave an empty validation part. Round the product to 6
decimals before truncating, in every splitter that cuts by ratios.
Split.to_dict is the processed-cache key and has to change whenever the
parts would. The float fix moves one patient between adjacent parts for
some sizes, so PatientSplit.to_dict now carries the name of the cut
rule: caches built with the old sizes get another key and are rebuilt
instead of being reused.
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.04% (50005 / 57452 lines)

Modified file Coverage Lines
pyhealth/autoimprove/__init__.py 100.00% 10 / 10
pyhealth/autoimprove/evaluate.py 93.16% 177 / 190
pyhealth/autoimprove/explain.py 94.21% 293 / 311
pyhealth/autoimprove/improver.py 94.25% 869 / 922
pyhealth/autoimprove/llm.py 97.09% 100 / 103
pyhealth/autoimprove/report.py 96.52% 666 / 690
pyhealth/calib/predictionset/__init__.py 100.00% 10 / 10
pyhealth/calib/predictionset/group_conditional.py 95.04% 115 / 121
pyhealth/datasets/__init__.py 100.00% 84 / 84
pyhealth/datasets/abide.py 97.62% 123 / 126
pyhealth/datasets/ahepa_dementia.py 100.00% 74 / 74
pyhealth/datasets/bciiv2a.py 95.00% 95 / 100
pyhealth/datasets/bcss.py 96.18% 151 / 157
pyhealth/datasets/brain_tumor_mri.py 95.65% 88 / 92
pyhealth/datasets/cardiology.py 98.61% 71 / 72
pyhealth/datasets/cbis_ddsm.py 95.42% 125 / 131
pyhealth/datasets/cdc_covid.py 92.59% 25 / 27
pyhealth/datasets/chapman_shaoxing.py 91.45% 107 / 117
pyhealth/datasets/covid_blues.py 96.08% 147 / 153
pyhealth/datasets/ham10000.py 93.46% 100 / 107
pyhealth/datasets/helsinki_neonatal.py 97.06% 66 / 68
pyhealth/datasets/hmc.py 97.62% 41 / 42
pyhealth/datasets/hup_ieeg.py 96.00% 96 / 100
pyhealth/datasets/isic2019.py 93.94% 124 / 132
pyhealth/datasets/isic2020.py 96.00% 96 / 100
pyhealth/datasets/jichi.py 94.32% 83 / 88
pyhealth/datasets/kits23.py 100.00% 75 / 75
pyhealth/datasets/lndb.py 93.20% 137 / 147
pyhealth/datasets/meds.py 93.67% 74 / 79
pyhealth/datasets/mimic3.py 100.00% 21 / 21
pyhealth/datasets/mimic4.py 95.80% 114 / 119
pyhealth/datasets/nsrr_sleep.py 100.00% 46 / 46
pyhealth/datasets/omop.py 96.88% 31 / 32
pyhealth/datasets/pad_ufes_20.py 95.89% 70 / 73
pyhealth/datasets/pbc.py 96.77% 30 / 31
pyhealth/datasets/ph2.py 95.60% 87 / 91
pyhealth/datasets/splitter.py 97.06% 396 / 408
pyhealth/datasets/tcga_rna_seq.py 92.31% 24 / 26
pyhealth/interpret/__init__.py 100.00% 4 / 4
pyhealth/interpret/uni_acs.py 82.35% 182 / 221
pyhealth/metrics/__init__.py 100.00% 16 / 16
pyhealth/metrics/competing_risks.py 97.22% 70 / 72
pyhealth/metrics/survival.py 94.25% 82 / 87
pyhealth/models/__init__.py 100.00% 99 / 99
pyhealth/models/behrt.py 93.37% 183 / 196
pyhealth/models/bitenet.py 92.96% 251 / 270
pyhealth/models/bulk_rna_bert.py 95.77% 68 / 71
pyhealth/models/chet.py 92.80% 245 / 264
pyhealth/models/clip_stress.py 91.67% 154 / 168
pyhealth/models/clip_stress_layers.py 98.39% 61 / 62
pyhealth/models/clip_stress_utils.py 86.86% 119 / 137
pyhealth/models/clmbr.py 95.70% 289 / 302
pyhealth/models/concare.py 77.09% 286 / 371
pyhealth/models/daft.py 93.64% 221 / 236
pyhealth/models/dearllm.py 93.55% 145 / 155
pyhealth/models/deepsleepnet.py 99.22% 127 / 128
pyhealth/models/delphi.py 95.24% 240 / 252
pyhealth/models/descemb.py 91.32% 284 / 311
pyhealth/models/ecg_jepa.py 100.00% 121 / 121
pyhealth/models/eegnet.py 96.43% 81 / 84
pyhealth/models/ehr_fm.py 91.95% 297 / 323
pyhealth/models/evicare.py 99.68% 313 / 314
pyhealth/models/game.py 86.96% 240 / 276
pyhealth/models/generators/__init__.py 100.00% 8 / 8
pyhealth/models/generators/tardiff.py 99.60% 251 / 252
pyhealth/models/joint_seq_image.py 99.29% 278 / 280
pyhealth/models/maestro.py 95.14% 176 / 185
pyhealth/models/medtok.py 99.51% 202 / 203
pyhealth/models/mira.py 97.12% 337 / 347
pyhealth/models/neural_fine_gray.py 92.59% 125 / 135
pyhealth/models/protoecgnet.py 97.91% 374 / 382
pyhealth/models/query_focused_ehr.py 90.64% 155 / 171
pyhealth/models/rasc.py 98.63% 72 / 73
pyhealth/models/sleepkd.py 98.80% 82 / 83
pyhealth/models/stagenet.py 96.10% 197 / 205
pyhealth/models/stagenet_mha.py 94.33% 266 / 282
pyhealth/models/td_cnn_lstm.py 90.34% 346 / 383
pyhealth/models/text_embedding.py 95.70% 89 / 93
pyhealth/models/time_series_images.py 100.00% 126 / 126
pyhealth/models/udc.py 92.34% 229 / 248
pyhealth/processors/nested_sequence_processor.py 93.75% 165 / 176
pyhealth/processors/stagenet_processor.py 90.20% 184 / 204
pyhealth/processors/utils.py 96.61% 57 / 59
pyhealth/tasks/__init__.py 98.25% 112 / 114
pyhealth/tasks/abide_classification.py 97.83% 45 / 46
pyhealth/tasks/bciiv2a_left_right_imagery.py 100.00% 8 / 8
pyhealth/tasks/bciiv2a_motor_imagery.py 95.45% 63 / 66
pyhealth/tasks/bcss_tile_classification.py 100.00% 24 / 24
pyhealth/tasks/bcss_tissue_segmentation.py 98.11% 52 / 53
pyhealth/tasks/brain_tumor_mri_classification.py 100.00% 13 / 13
pyhealth/tasks/cardiology_detect.py 100.00% 134 / 134
pyhealth/tasks/cbis_ddsm_abnormality_classification.py 100.00% 18 / 18
pyhealth/tasks/cbis_ddsm_classification.py 97.67% 42 / 43
pyhealth/tasks/cbis_ddsm_density_classification.py 91.67% 22 / 24
pyhealth/tasks/cdc_covid_mortality.py 91.55% 65 / 71
pyhealth/tasks/chaos_segmentation.py 97.98% 97 / 99
pyhealth/tasks/chapman_heartlang.py 96.23% 102 / 106
pyhealth/tasks/chapman_shaoxing_classification.py 94.38% 84 / 89
pyhealth/tasks/climb_ecg.py 98.59% 70 / 71
pyhealth/tasks/competing_risks.py 88.46% 46 / 52
pyhealth/tasks/competing_risks_pbc.py 100.00% 56 / 56
pyhealth/tasks/covid_blues_classification.py 100.00% 11 / 11
pyhealth/tasks/covid_blues_severity.py 100.00% 15 / 15
pyhealth/tasks/cpsc2018_heartlang.py 97.98% 97 / 99
pyhealth/tasks/dearllm_mortality.py 98.29% 115 / 117
pyhealth/tasks/delphi_trajectory.py 91.28% 157 / 172
pyhealth/tasks/dementia_classification_ahepa.py 100.00% 93 / 93
pyhealth/tasks/dermoscopy_artifact_views.py 100.00% 130 / 130
pyhealth/tasks/ehr_foundation_model.py 94.12% 112 / 119
pyhealth/tasks/ethos_tasks.py 100.00% 86 / 86
pyhealth/tasks/evicare_diagnosis.py 99.58% 238 / 239
pyhealth/tasks/ham10000_classification.py 96.77% 30 / 31
pyhealth/tasks/isic2019_classification.py 100.00% 36 / 36
pyhealth/tasks/isic2020_melanoma_classification.py 100.00% 12 / 12
pyhealth/tasks/jichi_davis_grading.py 95.83% 23 / 24
pyhealth/tasks/kits23_classification.py 98.61% 71 / 72
pyhealth/tasks/kits23_segmentation.py 97.37% 37 / 38
pyhealth/tasks/length_of_stay_prediction.py 77.30% 109 / 141
pyhealth/tasks/lndb_classification.py 98.36% 60 / 61
pyhealth/tasks/lndb_texture.py 100.00% 26 / 26
pyhealth/tasks/maestro_mortality_mimic4.py 95.00% 38 / 40
pyhealth/tasks/medmod_decompensation_mimic4.py 95.40% 83 / 87
pyhealth/tasks/meds_outcome_tasks.py 100.00% 125 / 125
pyhealth/tasks/mortality_prediction.py 90.29% 400 / 443
pyhealth/tasks/pad_ufes_20_classification.py 96.55% 28 / 29
pyhealth/tasks/ph2_artifact_classification.py 100.00% 41 / 41
pyhealth/tasks/physionet2012_inhospital_mortality.py 94.52% 138 / 146
pyhealth/tasks/physionet2012_mortality.py 96.20% 76 / 79
pyhealth/tasks/ptbxl_heartbeat.py 97.33% 73 / 75
pyhealth/tasks/query_focused_ehr.py 91.88% 147 / 160
pyhealth/tasks/readmission_prediction.py 94.76% 217 / 229
pyhealth/tasks/rsna_pneumonia_classification.py 92.31% 12 / 13
pyhealth/tasks/seizure_detection_helsinki.py 100.00% 149 / 149
pyhealth/tasks/sleep_staging_hmc.py 99.06% 105 / 106
pyhealth/tasks/sleep_staging_isruc.py 100.00% 121 / 121
pyhealth/tasks/sleep_staging_nsrr.py 96.15% 125 / 130
pyhealth/tasks/sleep_staging_v2.py 98.75% 79 / 80
pyhealth/tasks/soz_localization_hup.py 98.96% 190 / 192
pyhealth/tasks/survival_time_to_event.py 95.10% 136 / 143
pyhealth/tasks/tcga_survival_prediction.py 84.21% 48 / 57
pyhealth/tasks/temple_university_EEG_tasks.py 83.24% 154 / 185
pyhealth/tasks/value_set_pair_classification.py 98.95% 188 / 190
pyhealth/tasks/variant_classification.py 89.29% 50 / 56
pyhealth/utils.py 83.70% 77 / 92

Workflow run · 30a49a9

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot 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.

Previous review

Reviewed commit 7f7178b

Comment thread pyhealth/datasets/splitter.py Outdated
return {"kind": "patient", "ratios": list(self.ratios), "seed": int(self.seed)}
"""JSON-serialisable description, used in cache keys and metadata.

``cuts`` names the rule that turns ratios into part sizes. Before the

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 30a49a9. The docstring now says only that cuts names the rule that turns ratios into part sizes, so a change of rule changes the cache key. The history note and the link to the private helper are gone.

Comment thread pyhealth/datasets/splitter.py Outdated
Returns:
The index of the cut, between 0 and ``n``.
"""
return int(round(n * fraction, 6))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 30a49a9. _cut_index now takes n * fraction as an integer only when it is within a relative 1e-12 of one, and otherwise rounds down, so _cut_index(2, 0.4999999) is 0 again. The float error of these products is about 1e-15 relative at most. A ratio written with d decimals is never snapped while n * 10**d < 10**12: a new test builds, for three sizes, the 7-decimal ratio that puts n * ratio exactly 1e-7 below an integer and checks it rounds down. The exact-arithmetic test now also covers two 7-decimal ratio sets and sizes up to 10**9 + 7. Both new tests fail with the 6-decimal rounding.

@github-actions github-actions Bot 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.

Previous review

AI Review

suggestion: need change
decision: human review

Thank you for this fix, Axel. Replacing the truncating cut with _cut_index stops floating-point error from emptying a split part. Your tests check the result against exact rational arithmetic, which is a strong way to show it works. Coverage meets the bar: splitter.py is at 97.02% (bar 80%) and the whole repository is at 84.48% (bar 60%).

This touches shared code, so a maintainer will need to review it and it can't be approved automatically. PatientSplit.to_dict is the processed-cache key used by BaseDataset.set_task, and the new cuts key changes it for every PatientSplit cache. The public split_by_* splitters are shared utilities, and their returned part sizes change for the affected sizes. You offered to drop the to_dict part. Whether to keep it is the maintainer's call.

To get this merged:

  • Update docs/api/datasets/pyhealth.datasets.splitter.rst (around line 27). It shows the fit_split description as {'kind': 'patient', 'ratios': ..., 'seed': 42}. That no longer matches the code, which now also returns a cuts entry.

Optional suggestions:

  • The same int(len * ratio) pattern remains in pyhealth/medcode/pretrained_embeddings/kg_emb/datasets/splitter.py and pyhealth/models/medlink/utils.py. You could fix those too, or say in the description that they are out of scope.

Reviewed commit 7f7178b

Rounding n * fraction to 6 decimals also rounded up ratios written with
more decimals: _cut_index(2, 0.4999999) gave 1. A product is now taken as
an integer only when it is within a relative 1e-12 of it, far above the
float error and below the distance of any ratio with d decimals while
n * 10**d < 10**12. Other products are rounded down.

The PatientSplit.to_dict docstring describes the cuts entry without a
history note or a link to a private helper, and the splitter API page
shows the description with its cuts entry.
Comment thread pyhealth/datasets/splitter.py Outdated
return {"kind": "patient", "ratios": list(self.ratios), "seed": int(self.seed)}
"""JSON-serialisable description, used in cache keys and metadata.

``cuts`` names the rule that turns ratios into part sizes. Before the

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 30a49a9. The docstring now says only that cuts names the rule that turns ratios into part sizes, so a change of rule changes the cache key. The history note and the link to the private helper are gone.

Comment thread pyhealth/datasets/splitter.py Outdated
Returns:
The index of the cut, between 0 and ``n``.
"""
return int(round(n * fraction, 6))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 30a49a9. _cut_index now takes n * fraction as an integer only when it is within a relative 1e-12 of one, and otherwise rounds down, so _cut_index(2, 0.4999999) is 0 again. The float error of these products is about 1e-15 relative at most. A ratio written with d decimals is never snapped while n * 10**d < 10**12: a new test builds, for three sizes, the 7-decimal ratio that puts n * ratio exactly 1e-7 below an integer and checks it rounds down. The exact-arithmetic test now also covers two 7-decimal ratio sets and sizes up to 10**9 + 7. Both new tests fail with the 6-decimal rounding.

@AxelNoun

Copy link
Copy Markdown
Contributor Author

Pushed 30a49a9 for the review:

  • docs/api/datasets/pyhealth.datasets.splitter.rst shows the fit_split description with its cuts entry, as PatientSplit(ratios=(0.7, 0.1, 0.2), seed=42).to_dict() prints it.
  • The two inline points are answered in their threads.
  • The same int(len * ratio) cut in kg_emb/datasets/splitter.py and medlink/utils.py is left out of this PR; the description now says so.

I updated the description to match: the new rule, the docs file, and 13 tests instead of 10. The 9 test files that use a ratio splitter pass on Linux.

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot 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.

Reviewed commit 30a49a9

# integer. The float error of a sum of a few ratios times n is about 1e-15
# relative at most. A ratio written with d decimals puts n * fraction at
# least 10**-d away from any integer it does not reach, so it is never
# snapped while n * 10**d < 10**12.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[low] Unchanged-sizes claim does not hold for large n with many-decimal ratios

The comment says a ratio with d decimals is never snapped while n * 10d < 1012, and the PR description says sizes without float error are unchanged, including ratios with more than 6 decimals. That is only true below that bound. Example: n = 1999999 with ratio 0.2000001. The exact product is 399999.9999999, so the decimal-exact cut is 399999. The snap tolerance is 1e-12 * 4e5 = 4e-7, which is larger than the 1e-7 distance to 400000, so _cut_index returns 400000. Fix: state the n * 10**d limit in the PR description, or, if decimal-exact sizes are wanted, compute the cut with Fraction(str(ratio)) instead of float snapping.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right, the claim only holds below that bound; the description now states it (n * 10**d < 10**12, so 7 decimals up to 100,000 items). I kept float snapping rather than Fraction(str(ratio)): a ratio such as 1/3 prints as 0.3333333333333333, so the decimal reading would cut [1/3, 1/3, 1/3] on 3 patients into 0/1/2, where snapping gives 1/1/1. I also kept _CUT_RULE as a sentence, so that the cache metadata says what the rule is.

@github-actions github-actions Bot 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.

AI Review

suggestion: approve
decision: human review

Thank you for this fix, Axel. It stops floating-point error in the split ratios from changing split sizes, such as the empty validation part for [0.7, 0.1, 0.2] on 10 patients. The _cut_index helper is small and well documented. The new tests compare it against exact rational arithmetic and cover every ratio splitter and PatientSplit. From the diff, the change looks correct and ready to merge on its merits.

Coverage meets the bar. pyhealth/datasets/splitter.py is at 97.06% (bar: 80%), and the whole repository is at 87.04% (bar: 60%).

This can't be approved automatically because it touches shared code. PatientSplit and the ratio splitters in splitter.py are used by BaseDataset.set_task. The change also adds a cuts key to PatientSplit.to_dict, which feeds the processed-cache key. As a result, part sizes change for the affected inputs, and every PatientSplit cache will be rebuilt once. A maintainer should confirm both effects are acceptable. You already offered to drop the cache-key change, and that choice is theirs to make.

Optional suggestions:

  • The description says sizes are unchanged "including ratios with more than 6 decimals". The code comment limits this to n·10^d < 10^12, so at very large n a ratio such as 0.2000001 can differ from exact arithmetic. Stating that bound in the description would make it accurate.
  • The _CUT_RULE string is long. A short version tag would be easier to read in cache metadata.

Reviewed commit 30a49a9

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

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ratio splitters lose an item to floating-point error: [0.7, 0.1, 0.2] on 10 patients gives an empty validation part

2 participants