sklearn.utils.gen_batches

sklearn.utils.gen_batches(n, batch_size, *, min_batch_size=0)[source]

Generator to create slices containing batch_size elements from 0 to n.

The last slice may contain less than batch_size elements, when batch_size does not divide n.

Parameters:
nint

Size of the sequence.

batch_sizeint

Number of elements in each batch.

min_batch_sizeint, default=0

Minimum number of elements in each batch.

Yields:
slice of batch_size elements

See also

gen_even_slices

Generator to create n_packs slices going up to n.

Examples

>>> from sklearn.utils import gen_batches
>>> list(gen_batches(7, 3))
[slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)]
>>> list(gen_batches(6, 3))
[slice(0, 3, None), slice(3, 6, None)]
>>> list(gen_batches(2, 3))
[slice(0, 2, None)]
>>> list(gen_batches(7, 3, min_batch_size=0))
[slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)]
>>> list(gen_batches(7, 3, min_batch_size=2))
[slice(0, 3, None), slice(3, 7, None)]