python中numpy-choice函数

来源:互联网 发布:哑铃健身软件 编辑:程序博客网 时间:2024/06/01 08:53

RandomState.choice(a, size=None, replace=True, p=None)

–通过给定的一维数组数据产生随机采样

参数:

a:一维数组或者int型变量,如果是数组,就按照里面的范围来进行采样,如果是单个变量,则采用np.arange(a)的形式

size : int 或者 tuple of ints, 可选参数
决定了输出的shape. 如果给定的是, (m, n, k), 那么 m * n * k 个采样点将会被采样. 默认为零,也就是只有一个采样点会被采样回来。

replace : 布尔参数,可选参数
决定采样中是否有重复值

p :一维数组参数,可选参数
对应着a中每个采样点的概率分布,如果没有标出,则使用标准分布。

返回值:
samples : 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

例子

从 np.arange(5) 中产生一个size为3的随机采样:

>>> np.random.choice(5, 3)array([0, 3, 4])>>> #This is equivalent to np.random.randint(0,5,3)

从 np.arange(5) 中产生一个非标准的 size为 3的随机采样:

>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])array([3, 3, 0])

从 np.arange(5) 产生一个标准分布、size为 3、没有重复替换的随机采样:

>>> np.random.choice(5, 3, replace=False)array([3,1,0])>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]

也可以这样,不必一定是整型数字:

>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],      dtype='|S11')

实际使用中,首先创建一个mask变量,然后通过mask来对需要采样的数据进行采样:

...  mask = np.random.choice(split_size, batch_size)  captions = data['%s_captions' % split][mask]  image_idxs = data['%s_image_idxs' % split][mask]...
原创粉丝点击