choice#
- class brainstate.random.choice(a, size=None, replace=True, p=None, key=None)#
Generates a random sample from a given 1-D array
- Parameters:
a (1-D array-like or int) – If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if it were
np.arange(a)size (
int|Sequence[int] |integer|Sequence[integer] |None) – Output shape. If the given shape is, e.g.,(m, n, k), thenm * n * ksamples are drawn. Default is None, in which case a single value is returned.replace (boolean, optional) – Whether the sample is with or without replacement. Default is True, meaning that a value of
acan be selected multiple times.p (1-D array-like, optional) – The probabilities associated with each entry in a. If not given, the sample assumes a uniform distribution over all entries in
a.key (
int|Array|ndarray|None) – The key for the random number generator. If not given, the default random number generator is used.
- Returns:
samples – The generated random samples
- Return type:
single item or ndarray
- Raises:
ValueError – If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population size
Notes
Setting user-specified probabilities through
puses a more general but less efficient sampler than the default. The general sampler produces a different sample than the optimized sampler even if each element ofpis 1 / len(a).Sampling random rows from a 2-D array is not possible with this function, but is possible with Generator.choice through its
axiskeyword.Examples
Generate a uniform random sample from np.arange(5) of size 3:
>>> import brainstate >>> result = brainstate.random.choice(5, 3) >>> print(result.shape) # (3,) >>> print((result >= 0).all() and (result < 5).all()) # True
Generate a non-uniform random sample from np.arange(5) of size 3:
>>> result = brainstate.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) >>> print(result.shape) # (3,) >>> print(set(result).issubset({0, 2, 3})) # True (only non-zero prob elements)
Generate a uniform random sample from np.arange(5) of size 3 without replacement:
>>> result = brainstate.random.choice(5, 3, replace=False) >>> print(result.shape) # (3,) >>> print(len(set(result)) == 3) # True (all unique)
Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:
>>> result = brainstate.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]) >>> print(result.shape) # (3,) >>> print(len(set(result)) == 3) # True (all unique)
Any of the above can be repeated with an arbitrary array-like instead of just integers:
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] >>> result = brainstate.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) >>> print(result.shape) # (5,) >>> print(result.dtype.kind) # 'U' (unicode string)