Sampling with Replacement and without Replacement in Python
Code
To perform sampling with replacement/replacement in Python, one can use the np.random.choice() function of numpy.
random.choice(a, size=None, replace=True, p=None)
- a: 1-dimensional array or integer
- Represents the set from which to sample. If a is an integer, sampling is done from 
np.arange(a). 
 - Represents the set from which to sample. If a is an integer, sampling is done from 
 - size: An integer or a tuple of integers
- Represents the size of the output sample.
 
 - replace: Boolean
- T for sampling with replacement, F for sampling without replacement.
 
 - p: 1-dimensional array
- Represents the probabilities of each element being picked. Default is 
None. 
 - Represents the probabilities of each element being picked. Default is 
 
(23.10.04) There is no straightforward way to do this in PyTorch.
>>> np.random.choice(5, 5, replace=False)
array([3, 1, 0, 2, 4])
>>> np.random.choice(5, 5, replace=True)
array([0, 2, 0, 2, 2])
Environment
- OS: Windows11
 - Version: Python 3.11.5, numpy==1.26.0
 
