使用 numpy.random.choice随机采样

使用 numpy.random.choice随机采样:

说明

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

示例:

>>> np.random.choice(5, 3)
array([0, 3, 4])

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

>>> np.random.choice(5, 3, replace=False)
array([3,1,0])

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

>>> 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'],

 

1、按照指定概率采样:

#按照分布采样
def randomExample():
    d1=np.array([0.2,0.3,0.5])

    index=[]
    for num in range(100000):
        r = random.uniform(0, 1)
        for i in range(1,4):
           if r < sum(d1[0:i]):
               index.append(i-1)
               break
    print(index)
    print(sum(np.array(index)==0))
    print(sum(np.array(index)==1))
    print(sum(np.array(index)==2))

结果为:

  # [1,2,2,1,2,1,1,1,2,2,1,2,0,2,1,0,2,1,...
  # 20143
  # 29934
  # 49923

 

2、可以从一个int数字或1维array里随机选取内容,并将选取结果放入n维array中返回。

def randomByPro():
    arr=np.random.choice(5, 3, p=[0.1, 0, 0.3, 0, 0.6])
    print(arr)

结果为:

# array([3, 3, 0])

 

posted on 2018-04-24 17:16  CuriousZero  阅读(2435)  评论(0编辑  收藏  举报

导航