天天看点

Numpy中array的基本操作(4)

Random里面常用的一些随机数函数

官方文档地址: https://docs.scipy.org/doc/numpy-1.16.0/reference/routines.random.html

下面的代码是pyhon3.6 numpyt1.16.0

import numpy as np
np.random.seed(666)

1.rand(d0, d1, d2, ... ,dn) 这个函数返回的数据在[0,1)之间,具有均匀分布的特点
rand等价于uniform([low, high ,size])这个函数 也就是low=0,high=1时 里面的参数代表的是 生成array的dim(维度)
x = np.random.rand(3)
y = np.random.uniform(0,1,3)
x,y
output: 
(array([0.70043712, 0.84418664, 0.67651434]),
 array([0.72785806, 0.95145796, 0.0127032 ]))
x = np.random.rand(2, 3)
y = np.random.uniform(0,1,(2,3))

x,y
output:
(array([[0.192892  , 0.70084475, 0.29322811],
        [0.77447945, 0.00510884, 0.11285765]]),
 array([[0.11095367, 0.24766823, 0.0232363 ],
        [0.72732115, 0.34003494, 0.19750316]])

2.randn(d0, d1, d2, ..., dn)
这个函数返回的数据 具有 标准正态分布的特点,也就是均值为0,方差为1
randn等价于 normal([loc, scale, size]) 这个函数, 也就是loc=0, scale=1时

x = np.random.randn(3)
y = np.random.normal(0,1,3)
x,y
output:
(array([-0.18842439, -0.04148929, -0.98479191]),
 array([-1.35228176,  0.19432385,  0.26723935]))

x = np.random.randn(2,3)
y = np.random.normal(0,1,(2,3))
x,y
output: 
(array([[-0.4264737 ,  1.44773506, -0.1963061 ],
        [ 1.51814514,  0.07722188, -0.06399132]]),
 array([[ 0.94592341,  1.20409101, -0.45124074],
        [-1.58744651, -1.86885548,  0.10037737]]))

3.randint([low, high, size, dtype])
这个函数生成的是随机整数  从low开始 不包含high
如果只传入一个参数T  那就生成从0到T的随机整数
size代表的是生成数据的shape 下面是例子

np.random.randint(1,10,size=5)#size=5  就生成了有五个数据的一维向量
output: array([1, 5, 7, 8, 9])

np.random.randint(1,10,size = (2,3))#size=(2,3)  就生成了一个 2行3列 的二维数组
output: array([[3, 9, 2],
       [1, 9, 3]])

4.random(size) 这个函数可以生成[0.0, 1.0)之间的随机数  
np.random.random(5)
output: array([0.03643288, 0.72687158, 0.00390984, 0.050294  , 0.99199232])
np.random.random((2,3))
output: array([[0.2122575 , 0.94737066, 0.45154055],
       [0.99879467, 0.64750149, 0.70224071]])

5.choice[a,  size] 这个函数意思是从a中随机选取数组
其中a可以是个数字   也可以是个数组

#当参数a为数字时 相当于先执行了一下 x = np.arange[a] 然后再从x里面 随机挑选数字
np.random.choice(5,2)
#上面的式子就 等价于 下面两个式子
#x = np.arange(5)
#np.random.choice(x, 2)
output: array([2, 1])

#当参数为数组时  下面这个例子  就相当于选出2行3列 其中每个元素 都来自于这个数组的随机值
np.random.choice([1, 2, 3, 4, 5], size=(2,3))
output: array([[5, 4, 4],
       [2, 4, 3]])
       
6.shuffle(x)  
这个函数用于将数组x随机排列
x = np.arange(5)
np.random.shuffle(x)
x
output:array([4, 0, 3, 1, 2])
#如果数组是多维的 2维为例子 
#那么 这个函数 只会在第一维度进行打散  也就是行 打乱顺序, 每一行里面的元素 并不会打散
x= np.arange(10).reshape(2,5)
np.random.shuffle(x)
x
output:
array([[5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4]])

7.permutation(x)
这个函数跟shuffle类似,也是用于打散数组
于shuffle不同的是 这个函数不会改变原来的数组 而会重新生成一个array
#以二维数组为例子
x = np.arange(12).reshape(3,4)
y = np.random.permutation(x)
x,y
output:(array([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]]),
 array([[ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [ 0,  1,  2,  3]]))
           

具体参考连接:https://www.bilibili.com/video/BV1U7411x76j?t=110&p=7