Repository navigation
Conversation
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.
Test CoverageTotal: 87.04% (50005 / 57452 lines)
|
|
/review |
| 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 |
There was a problem hiding this comment.
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.
| Returns: | ||
| The index of the cut, between 0 and ``n``. | ||
| """ | ||
| return int(round(n * fraction, 6)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 thefit_splitdescription as{'kind': 'patient', 'ratios': ..., 'seed': 42}. That no longer matches the code, which now also returns acutsentry.
Optional suggestions:
- The same
int(len * ratio)pattern remains inpyhealth/medcode/pretrained_embeddings/kg_emb/datasets/splitter.pyandpyhealth/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.
| 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 |
There was a problem hiding this comment.
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.
| Returns: | ||
| The index of the cut, between 0 and ``n``. | ||
| """ | ||
| return int(round(n * fraction, 6)) |
There was a problem hiding this comment.
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.
|
Pushed 30a49a9 for the review:
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. |
|
/review |
| # 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. |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_RULEstring is long. A short version tag would be easier to read in cache metadata.
Reviewed commit 30a49a9
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.1is0.7999999999999999in 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 sizesn = 1..500.The fix adds a private helper,
_cut_index(n, fraction), which takes the product as an integer when it is within a relative1e-12of 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 withddecimals as long asn * 10**d < 10**12(7 decimals up to 100,000 items); above that bound a product within1e-12relative of an integer is rounded to it.Effect on existing splits:
Split.to_dictis the processed-cache key and "must change whenever the parts would".PatientSplit.to_dictnow carries the name of the cut rule, so caches built with the old sizes are rebuilt, not reused. This rebuilds everyPatientSplitcache 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, andPatientSplit.to_dict.docs/api/datasets/pyhealth.datasets.splitter.rst: thefit_splitexample with itscutsentry.tests/core/test_split_ratio_rounding.py(new):_cut_indexagainst exact rational arithmetic for 7 ratio sets andn = 0..500; sizes of every ratio splitter and ofPatientSpliton 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.python tools/check_pr_rules.py: passed.Out of scope: the same
int(len * ratio)cut inpyhealth/medcode/pretrained_embeddings/kg_emb/datasets/splitter.pyandpyhealth/models/medlink/utils.py.