cleverly.learners.random_partition#

cleverly.learners.random_partition(n: int, n_folds: int, *, cluster: ndarray[tuple[Any, ...], dtype[int64]] | None = None, seed: int) → Folds[source]#

Draw an unstratified split of rows, or of whole clusters, from a seed.

The draw reads no outcome, treatment or covariate. The assignment depends on n, the cluster labels and seed alone, so the same inputs give the same split on every supported scikit-learn.

Parameters:
nint

Number of rows to split.

n_foldsint

Folds requested. resolve_n_folds() caps it at n and at the number of clusters, with a warning.

clusterndarray or None, default=None

One cluster code per row. Every row of a cluster lands in the same fold.

seedint

Seed of the draw, in [0, 2**32 - 1].

Returns:
Folds

A checked split whose origin records the generator, the scheme, the requested fold count and the seed.

Raises:
ValueError

If n is below two, the seed is not an integer in range, or fewer than two folds are possible.

See also

make_folds

Builds a split with or without strata, and calls this function for an unstratified split.

FoldOrigin

The record this function attaches to the split.

Notes

The row-level draw shuffles numpy.arange(n) with numpy.random.RandomState(seed). It then cuts the order into K contiguous blocks of n // K rows, and the first n % K blocks take one extra row. This is the split sklearn.model_selection.KFold(K, shuffle=True, random_state=seed) makes.

The grouped draw permutes the sorted distinct cluster labels with numpy.random.RandomState(seed) and cuts the permutation into K parts with numpy.array_split. This is the split sklearn.model_selection.GroupKFold(K, shuffle=True, random_state=seed) makes in scikit-learn 1.6 and later. The number of clusters in two folds differs by at most one, and a cluster’s size does not change where it lands.

Examples

>>> from cleverly.learners import random_partition
>>> folds = random_partition(6, 3, seed=0)
>>> folds.assignment.tolist()
[2, 1, 0, 1, 2, 0]
>>> folds.origin.scheme, folds.origin.seed
('vfold', 0)