以下摘自官方文档
numpy.random.choice(a, size=None, replace=True, p=None)
Generates a radnom sample from a given 1-D array
译:从给定的一维数组(a)中随机采样
- a : 可以为一维数组或整数;若为整数,则相当于 np.arange(a)
- size : 随机采样的个数
- replace : 采样结果是否允许重复
- p : 给被采样的一维数组赋予被采样的概率
# 从 np.arange(5) 中产生 3 个随机样本
In [3]: np.random.choice(5, 3)
Out[3]: array([2, 4, 2])
# replace = False : 采样结果不允许重复
In [6]: np.random.choice(5, 3, replace=False)
Out[6]: array([3, 4, 0])
# p=[0.1, 0, 0.3, 0.6, 0] : 给被采样数组赋被采样概率
# 由于 p[1] = p[4] = 0 , 故不会被采样
In [12]: np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
Out[12]: array([2, 3, 3], dtype=int64)
In [13]: np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
Out[13]: array([0, 3, 3], dtype=int64)
In [15]: np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
Out[15]: array([2, 0, 3])