numpy中的random主要是用来产生随机数的一个模块。
模块使用中的常见问题:
1、randn()和rand()的区别:
- numpy.random.randn(d0, d1, …, dn)是从标准正态分布(0均值1方差)中返回一个或多个样本值。
- numpy.random.rand(d0, d1, …, dn)是从[0, 1)随机采样。(或者叫均匀分布采样)
import numpy as np
arr1 = np.random.randn(2,4)
print(arr1)
print('******************************************************************')
arr2 = np.random.rand(2,4)
print(arr2)
结果:
[[-1.03021018 0.5197033 0.52117459 -0.70102661]
[ 0.98268569 1.21940697 -1.095241 -0.38161758]]
******************************************************************
[[ 0.19947349 0.05282713 0.56704222 0.45479972]
[ 0.28827103 0.1643551 0.30486786 0.56386943]]
2、permutation(x)和shuffle(x)的区别:
- 功能相同:对原来的数组进行重新洗牌(即随机打乱原来的元素顺序)
- 两者区别:peumutation(x)不会修改X的顺序。
shuffle直接在原来的数组上进行操作,改变原来数组的顺序,无返回值;而permutation不直接在原来的数组上进行操作,而是返回一个新的打乱顺序的数组,并不改变原来的数组。
random模块详解:
详情可见:https://docs.scipy.org/doc/numpy/reference/routines.random.html
1、简单的随机数据
rand(d0, d1, ..., dn) |
随机值 >>> np.random.rand(3,2) array([[ 0.14022471, 0.96360618], #random [ 0.37601032, 0.25528411], #random [ 0.49313049, 0.94909878]]) #random |
randn(d0, d1, ..., dn) |
返回一个样本,具有标准正态分布。 Notes For random samples from sigma * np.random.randn(...) + mu Examples >>> np.random.randn() 2.1923875335537315 #random Two-by-four array of samples from N(3, 6.25): >>> 2.5 * np.random.randn(2, 4) + 3 array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random |
randint(low[, high, size]) |
返回随机的整数,位于半开区间 [low, high)。 >>> np.random.randint(2, size=10) array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) >>> np.random.randint(1, size=10) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) Generate a 2 x 4 array of ints between 0 and 4, inclusive: >>> np.random.randint(5, size=(2, 4)) array([[4, 0, 2, 1], [3, 2, 2, 0]]) |
random_integers(low[, high, size]) |
返回随机的整数,位于闭区间 [low, high]。 Notes To sample from N evenly spaced floating-point numbers between a and b, use: a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.) Examples >>> np.random.random_integers(5) 4 >>> type(np.random.random_integers(5)) <type ‘int‘> >>> np.random.random_integers(5, size=(3.,2.)) array([[5, 4], [3, 3], [4, 5]]) Choose five random numbers from the set of five evenly-spaced numbers betwee |