python中numpy-choice函数


文章转到:https://oldpan.me/archives/python-numpy-choice

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)
  • 1
  • 2
  • 3

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

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

从 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]
  • 1
  • 2
  • 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')
  • 1
  • 2
  • 3
  • 4

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

...
  mask = np.random.choice(split_size, batch_size)
  captions = data['%s_captions' % split][mask]
  image_idxs = data['%s_image_idxs' % split][mask]
...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值