random_split#

deeptrack.sources.base.random_split(source: Source, lengths: list[int] | list[float], generator: np.random.Generator | torch.Generator | None = None) list[Subset]#

Randomly split a source into non-overlapping subsets of specified sizes.

This function splits a Source into multiple disjoint `Subset`s either by specifying absolute lengths (integers) or relative proportions (floats).

If all entries in lengths are floats that sum to 1 or less, they are interpreted as fractions and scaled to match the total size of the source. Remaining items (due to rounding) are distributed round-robin to ensure full coverage.

Parameters#

source: Source

The input Source to split.

lengths: list[int] | list[float]

A list of lengths for the resulting splits. If all values are floats summing to 1 (or slightly less), they are treated as proportions.

generator: np.random.Generator | torch.Generator | None, optional

A NumPy random generator used for shuffling. Defaults to None, in which case it is initialized to np.random.default_rng().

Returns#

list[Subset]

A list of Subset instances corresponding to the split parts.

Raises#

ValueError

If the sum of provided lengths does not match the length of the source.

Examples#

>>> from deeptrack.sources import Source, random_split

Create a source:

>>> source = Source(
...     a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
...     b=[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
... )

Split into train (70%) and validation (30%):

>>> train, val, test = random_split(source, [0.4, 0.3, 0.3])
>>> train
Subset(a=[3, 2, 7, 9], b=[13, 12, 17, 19])
>>> val
Subset(a=[5, 6, 1], b=[15, 16, 11])
>>> test
Subset(a=[0, 8, 4], b=[10, 18, 14])

Split into fixed sizes:

>>> train, val, test = random_split(source, [4, 3, 3])
>>> train
Subset(a=[3, 2, 7, 9], b=[13, 12, 17, 19])
>>> val
Subset(a=[5, 6, 1], b=[15, 16, 11])
>>> test
Subset(a=[0, 8, 4], b=[10, 18, 14])