[numpy系列教程] numpy.random.choice 从给定的数组中生成随机数
1、numpy官方函数说明
numpy.random.choice(a, size=None, replace=True, p=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 a was np.arange(n)
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
replace : boolean, optional
Whether the sample is with or without replacement
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.
Returns:
samples : 1-D ndarray, shape (size,)
The generated random samples
2、参数意义解释与实例演示
numpy.random.choice(a, size=None, replace=True, p=None)
a: 1-D array-like or int
a可以为一个一维的数组或者是一个int值。如果a是一个一维数组,那么就从这个一维数组中随机挑选出指定数量的元素组合成一个新的样本数组。如果a是一个int数,那么就是从np.arange(n)这个一维矩阵中随机挑选出指定数量的元素组合成一个新的样本数组。size: int or tuple of ints, optional
size是一个可选参数,如果不设置,那么该函数就会从a中返回一个值作为选出的样本。如果size被设置成一个int类型的值,那么生成的生成的数组的长度即为size。如果size被设置成一个元素为int值的元组,那么生成的样本数组的shape即为size。
# size = None(不设置)
>>> np.random.choice([1, 3, 6, 2])
2
# 将size设置为一个int值
>>> np.random.choice([1, 3, 6, 2], 3)
array([6, 3, 6])
# 将size设置为一个元组
>>> np.random.choice([1, 3, 6, 2], (2, 3))
array([[3, 2, 3],
[3, 6, 6]])
- replace : boolean, optional
replace同样也是一个可选参数,该参数的值是一个bool类型的值,默认为True,如果replace被设置为True,即表示生成的样本数组中可以有重复的元素;如果replace被设置为False,即表示生成的样本数组中不会出现重复的元素。
# replace不设置任何值,默认为True
>>> np.random.choice([1, 3, 6, 2], 3)
array([1, 6, 1]) # 这种情况下可能出现重复的元素
# replace被设置为False
# 在这种模式下,生成的样本数组中的元素不会出现重复元素
>>> np.random.choice([1, 3, 6, 2], 3, replace = False)
array([1, 2, 3])
>>> np.random.choice([1, 3, 6, 2], 3, replace = False)
array([2, 3, 6])
>>> np.random.choice([1, 3, 6, 2], 3, replace = False)
array([2, 1, 3])
>>> np.random.choice([1, 3, 6, 2], 3, replace = False)
array([6, 2, 1])
- p : 1-D array-like, optional
p同样也是一个可选参数,该参数是一个一维数组,与a有着同样的shape,p中的所有元素之和为1,每个元素表示其对应的a中的元素出现的概率,也就是说,如果p中的某个元素较大,那么a中该位置对应的元素出现的概率就较大。
# p中元素的个数与a中元素个数不相同
# a and p must have same size
>>> np.random.choice([1, 3, 6, 2], 3, p = [0.1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 1137, in mtrand.RandomState.choice
ValueError: a and p must have same size
# p中的元素之和不为1的时候
>>> np.random.choice([1, 3, 6, 2], 3, p = [0.1, 0.2, 0.5, 0.4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "mtrand.pyx", line 1141, in mtrand.RandomState.choice
ValueError: probabilities do not sum to 1
# p值设置正确
>>> np.random.choice([1, 3, 6, 2], 3, p = [0.1, 0.2, 0.4, 0.3])
array([1, 2, 2])
有问题请留言,觉得好请点赞哇!
参考:
numpy官方教程请看这里