WeightedRandomSampler

class paddle.io. WeightedRandomSampler ( weights, num_samples, replacement=True ) [source]

Random sample with given weights (probabilities), sampe index will be in range [0, len(weights) - 1], if replacement is True, index can be sampled multiple times.

Parameters
  • weights (numpy.ndarray|paddle.Tensor|list|tuple) – sequence of weights, should be numpy array, paddle.Tensor, list or tuple

  • num_samples (int) – set sample number to draw from sampler.

  • replacement (bool) – Whether to draw sample with replacements, default True

Returns

a Sampler yield sample index randomly by given weights

Return type

Sampler

Examples

>>> import numpy as np
>>> from paddle.io import WeightedRandomSampler

>>> np.random.seed(2023)
>>> sampler = WeightedRandomSampler(
...     weights=[0.1, 0.3, 0.5, 0.7, 0.2],
...     num_samples=5,
...     replacement=True
... )
>>> for index in sampler:
...     print(index)
2
4
3
1
1