Numpy随机数 拓展 - 洗牌和抽样
In [1]:
import numpy as np
In [2]:
np.random.seed(10)
a = np.random.randint(100, 200,(3, 4))
a
Out[2]:
array([[109, 115, 164, 128],
[189, 193, 129, 108],
[173, 100, 140, 136]])
洗牌
改变原值
In [5]:
np.random.shuffle(a)
In [6]:
a
Out[6]:
array([[173, 100, 140, 136],
[189, 193, 129, 108],
[109, 115, 164, 128]])
permutation不改变原数组
按最外层维度洗牌
In [7]:
np.random.permutation(a)
Out[7]:
array([[189, 193, 129, 108],
[173, 100, 140, 136],
[109, 115, 164, 128]])
In [8]:
a
Out[8]:
array([[173, 100, 140, 136],
[189, 193, 129, 108],
[109, 115, 164, 128]])
多维数组仅沿最外层维度(0轴)洗牌
1维
In [9]:
b = np.array([0,1,50,20,300,4000,22])
b
np.random.permutation(b)
Out[9]:
array([4000, 20, 22, 50, 300, 0, 1])
2维
In [11]:
a
Out[11]:
array([[173, 100, 140, 136],
[189, 193, 129, 108],
[109, 115, 164, 128]])
In [24]:
np.random.permutation(a)
Out[24]:
array([[109, 115, 164, 128],
[189, 193, 129, 108],
[173, 100, 140, 136]])
3维
In [26]:
c = np.random.randint(100, 200, (2,3,4))
c
Out[26]:
array([[[115, 118, 180, 171],
[188, 111, 117, 146],
[107, 175, 128, 133]],
[[184, 196, 188, 144],
[105, 104, 171, 188],
[188, 150, 154, 134]]])
In [27]:
np.random.permutation(c)
Out[27]:
array([[[184, 196, 188, 144],
[105, 104, 171, 188],
[188, 150, 154, 134]],
[[115, 118, 180, 171],
[188, 111, 117, 146],
[107, 175, 128, 133]]])
抽取
In [28]:
np.random.seed(10)
d = np.random.randint(100, 200, 8)
d
Out[28]:
array([109, 115, 164, 128, 189, 193, 129, 108])
In [29]:
# 洗牌
np.random.permutation(d)
Out[29]:
array([128, 108, 189, 193, 129, 164, 109, 115])
In [50]:
# 抽取
np.random.choice(d)
np.random.choice(d, 4) # 放回抽样,可能有重复值
np.random.choice(d, 4, replace=False) # 不放回抽样,没有重复值
Out[50]:
array([193, 115, 128, 164])
In [51]:
# 抽取为多维数组
np.random.choice(d, (2, 3), replace=False)
Out[51]:
array([[109, 189, 128],
[193, 129, 108]])
In [52]:
d
Out[52]:
array([109, 115, 164, 128, 189, 193, 129, 108])
In [77]:
# 设定抽取概率
np.random.choice(d, 2, replace=False, p=[0, 0.5, 0.3, 0.2,0,0,0,0])
Out[77]:
array([115, 164])