Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,7 +1181,9 @@ def partition_dataset(

Args:
data: input dataset to split, expect a list of data.
ratios: a list of ratio number to split the dataset, like [8, 1, 1].
ratios: relative partition sizes, e.g., [8, 1, 1]. If the rounded sizes fall short of the dataset
length, add one item to the partitions rounded down the most. If they exceed it, take one item
back from the partitions rounded up the most. Earlier partitions get the extra item on ties.
num_partitions: expected number of the partitions to evenly split, only works when `ratios` not specified.
shuffle: whether to shuffle the original dataset before splitting.
seed: random seed to shuffle the dataset, only works when `shuffle` is True.
Expand Down Expand Up @@ -1217,9 +1219,21 @@ def partition_dataset(
if ratios:
next_idx = 0
rsum = sum(ratios)
for r in ratios:
exact = [r / rsum * data_len for r in ratios]
sizes = [int(e + 0.5) for e in exact]
remainder = data_len - sum(sizes)
if remainder:
# A stable sort lets earlier partitions gain an item first and later partitions lose one first.
by_error = sorted(range(len(sizes)), key=lambda i: sizes[i] - exact[i])
if remainder > 0:
to_adjust, step = by_error[:remainder], 1
else:
to_adjust, step = by_error[remainder:], -1
for i in to_adjust:
sizes[i] += step
for size in sizes:
start_idx = next_idx
next_idx = min(start_idx + int(r / rsum * data_len + 0.5), data_len)
next_idx = min(start_idx + size, data_len)
datasets.append([data[i] for i in indices[start_idx:next_idx]])
return datasets

Expand Down
52 changes: 52 additions & 0 deletions tests/data/test_partition_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@
[[2, 4, 5], [1, 3]],
]

# rounding each partition size on its own leaves one item over in these cases
TEST_CASES_ROUNDING = [
[{"data": list(range(1, 11)), "ratios": [1, 1, 1]}, [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]],
[{"data": list(range(1, 14)), "ratios": [0.8, 0.1, 0.1]}, [list(range(1, 12)), [12], [13]]],
]


class TestPartitionDataset(unittest.TestCase):

Expand All @@ -125,6 +131,52 @@ class TestPartitionDataset(unittest.TestCase):
def test_value(self, input_param, result):
self.assertListEqual(partition_dataset(**input_param), result)

@parameterized.expand(TEST_CASES_ROUNDING)
def test_ratios_rounding(self, input_param, result):
"""Items left over after rounding go to the partitions that were rounded down the most.

Args:
input_param: keyword arguments for ``partition_dataset``.
result: the expected partitions.
"""
self.assertListEqual(partition_dataset(**input_param), result)

@parameterized.expand([(52, [3, 1, 3, 8], [10, 4, 10, 28]), (80, [9, 9, 3, 9, 2], [23, 23, 7, 22, 5])])
def test_ratios_rounding_sizes(self, data_len, ratios, expected_sizes):
"""When rounding gives too few or too many items, adjust the partitions with the largest errors.

Args:
data_len: number of items to partition.
ratios: the partition ratios.
expected_sizes: partition sizes after correcting the rounded total.
"""
partitions = partition_dataset(range(data_len), ratios=ratios)
self.assertListEqual([len(part) for part in partitions], expected_sizes)

@parameterized.expand(
[(63, [0.8, 0.1, 0.1]), (303, [0.7, 0.15, 0.15]), (32, [1, 1, 1, 1, 1]), (80, [0, 9, 9, 3, 9, 2, 0])]
)
def test_ratios_assign_every_item(self, max_len, ratios):
"""Check coverage and rounding across dataset lengths, including splits with a zero ratio.

Args:
max_len: largest number of items to partition.
ratios: the partition ratios.
"""
total_ratio = sum(ratios)
for data_len in range(max_len + 1):
with self.subTest(data_len=data_len):
data = list(range(data_len))
partitions = partition_dataset(data, ratios=ratios, shuffle=True, seed=0)
self.assertListEqual(sorted(i for part in partitions for i in part), data)
sizes = [len(part) for part in partitions]
exact = [r / total_ratio * data_len for r in ratios]
for size, share in zip(sizes, exact, strict=True):
self.assertLess(abs(size - share), 1)
rounded = [int(share + 0.5) for share in exact]
if sum(rounded) == data_len:
self.assertListEqual(sizes, rounded)


if __name__ == "__main__":
unittest.main()
Loading