Loading

numpy随机数

numpy.random

函数 功能描述 返回值
np.random.rand(d0,d1,…,dn) 元素在[0,1)区间均匀分布的数组 浮点数
np.random.uniform(low,hige, size) 元素在[low,hige)区间均匀分布的数组 浮点数
numpy.random.randint(low,hige, size) 元素在[low,hige)区间均匀分布的数组 整数
np.random.randn(d0,d1,…,dn) 产生标准正态分布的数组 浮点数
np.random.normal(loc, scale, size) 产生正态分布的数组 浮点数
# 创建2*3的随机数组,每个数字都是在[0,1)之间的浮点数
>>> np.random.rand(2,3)
array([[0.63781021, 0.56879887, 0.01676   ],
       [0.69158309, 0.80349676, 0.7012152 ]])

#参数为空的时候返回一个数字
>>> np.random.rand()
0.2780463068554154

#创建3*2的随机数组,每个数字都是在[1,5)之间的浮点数
>>> np.random.uniform(1,5,(3,2))
array([[2.56321923, 3.03023465],
       [1.85914173, 2.16025346],
       [4.64388149, 4.01960314]])
       
#创建3*2的随机数组,每个数字都是在[1,5)之间的整数
>>> np.random.randint(1,5,(3,2))
array([[4, 1],
       [3, 3],
       [4, 4]])

#创建2*3的随机数组,符合标准正态分布
>>> np.random.randn(2,3)
array([[-0.21078328, -0.46365853,  1.17982503],
       [ 0.93104933, -0.14153484,  1.48260646]])

#创建3*2的随机数组,符合正态分布,均值为0,方差为1
>>> np.random.normal(0,1,(3,2))
array([[-1.38009084,  0.23037739],
       [ 0.91970242, -0.86786995],
       [ 0.32031551, -0.11701534]])

设置随机种子

>>> np.random.seed(123)
>>> np.random.rand(2,3)
array([[0.69646919, 0.28613933, 0.22685145],
       [0.55131477, 0.71946897, 0.42310646]])
       
>>> np.random.seed(123)
>>> np.random.rand(2,3)
array([[0.69646919, 0.28613933, 0.22685145],
       [0.55131477, 0.71946897, 0.42310646]])
       
>>> np.random.rand(2,3)
array([[0.9807642 , 0.68482974, 0.4809319 ],
       [0.39211752, 0.34317802, 0.72904971]])

打乱顺序函数 - shuffle()

np.random.shuffle(序列)
对一维数组使用

>>> arr = np.arange(10)
>>> arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.random.shuffle(arr)
>>> arr
array([5, 6, 2, 9, 1, 8, 7, 0, 4, 3])

对多维数组使用

>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> np.random.shuffle(b)
>>> b
array([[ 4,  5,  6,  7],
       [ 0,  1,  2,  3],
       [ 8,  9, 10, 11]])
posted @ 2021-03-26 16:58  克豪  阅读(72)  评论(0)    收藏  举报