随机数组特地单独列一章节。因为numpy的随机数组方法多,而且看着都很像,容易混淆。
1.numpy.random.rand
创建指定大小的数组,数组数值取值范围为[0,1)。
np.random.rand(2,2)
array([[0.25901893, 0.40045757],
[0.33556201, 0.94164229]])
np.random.rand(10)
array([0.26765928, 0.0254993 , 0.71390332, 0.81739998, 0.60081098,
0.01739044, 0.65042077, 0.91331127, 0.21106773, 0.46124952])
2.numpy.random.randn
创建指定大小的数组,数组数值随机取于标准正态分布。
np.random.randn()
2.360354447141876
np.random.randn(2,3)
array([[-1.6020136 , 0.74563276, 3.43046135],
[-0.25806533, -0.24976319, 1.59458803]])
3.numpy.random.randint
numpy.random.
randint
(low, high=None, size=None, dtype='l')
创建指定大小的数组,数组数值随机取于[low,high)之间。high为空时则取[0,low)。需要用到size属性指定数组大小。
np.random.randint(2)
输出0或者1
np.random.randint(2,5)
输出2,3,4中的某一个值
np.random.randint(2,5,size=(3,3,3))
array([[[2, 2, 3],
[2, 3, 3],
[4, 3, 2]],
[[2, 2, 2],
[4, 2, 4],
[4, 2, 2]],
[[4, 3, 2],
[3, 4, 3],
[3, 2, 4]]])
4.numpy.random.choice
numpy.random.
choice
(a, size=None, replace=True, p=None)
a:指定的一维数组或者整数。如果是整数,则该方法等同于np.arange(a)
size:数组大小
replace:生成的数组中元素是否可以重复。默认为True,即可以重复
p:一维数组中每个元素出现的概率
np.random.choice(5, 3)
array([1, 1, 3])#会出现重复的值
np.random.choice(5, 3, replace=False)
array([4, 0, 3])#不会出现重复的值
np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 2, 0])#指定概率后,元素就只会出现0,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', 'piglet', 'Christopher', 'pooh', 'pooh'], dtype='<U11')
5.numpy.random.shuffle
数组乱序
arr = np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.random.shuffle(arr)
array([5, 1, 7, 6, 2, 3, 4, 9, 8, 0])
6.numpy.random.seed
随机数种子。例如设置为8,生成随机数组如下。再次生成随机数组值肯定会变。这时候我们想找回刚刚的数组,只要再设置随机数种子为8,再生成随机数组,我们发现值又回到刚刚的数组的值了。
np.random.seed(8)
np.random.rand(3)
array([0.8734294 , 0.96854066, 0.86919454])