使用 numpy.random.choice随机采样

2023-05-18,,

使用 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,...
#
#
#

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])

使用 numpy.random.choice随机采样的相关教程结束。

《使用 numpy.random.choice随机采样.doc》

下载本文的Word格式文档,以方便收藏与打印。