随机数
numpy中的随机数都在random模块中。
seed()
random.seed(10)
print(random.rand(1,1))
print(random.rand(1,1))
>>>两次结果不相同
random.seed(10)
print(random.rand(1,1))
random.seed(10)
print(random.rand(1,1))
>>>两次结果相同
每次调用产生随机数的函数之前会设置一个随机数种子,相同的随机数种子得到的随机数相同,如果不设置随机数种子,那么程序自动调用系统定时/计时器的值做为种子,这样每次的种子都是不一样的,产生的随机数也不一样。
详见:随机数种子详解
random.rand()
random.rand(d0,d1,d2,…,dn)
产生一个N维矩阵,其中的数在区间[0,1)服从均匀分布。
例:
a = np.random.rand(2,3)
print(a)
>>>[[ 0.3167727 0.84684373 0.46945419]
[ 0.52644551 0.59481931 0.06313488]]
random.randint()
random.randint(low,high,size,dtype)
从[low,high)中产生size个dtype数(默认为int),这些数服从[low,high)中的离散均匀分布。
例:
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.randn()
random.randn(d0,d1,…,dn)
产生一个n维矩阵,其中的数服从标准正态分布。如果想产生服从
N(μ,σ2)
的数,可采用
μ
+
σ
*randn(d0,d1,…dn)。
例:
np.random.randn()
>>> 2.1923875335537315 #不加参数则产生一个标量
#产生一个2*4矩阵并且服从N(3, 6.25):
2.5 * np.random.randn(2, 4) + 3
>>> array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677],
[ 0.39924804, 4.68456316, 4.99394529, 4.84057254]])
有规律的数
np.linspace
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
产生start-stop之间固定间隔的num个数,如果endpoint为true则包含stop,retstep为true则返回这个固定间隔step。
例:
np.linspace(2.0, 3.0, num=5)
>>> array([ 2. , 2.25, 2.5 , 2.75, 3. ])
np.linspace(2.0, 3.0, num=5, endpoint=False)
>>> array([ 2. , 2.2, 2.4, 2.6, 2.8])
np.linspace(2.0, 3.0, num=5, retstep=True)
>>> (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
random.uniform
random.uniform(low,high,size)
生成size大小服从在[low,high)范围内均匀分布的数组
a = np.random.uniform(2,4,(2,4))
random.poisson
random.poisson(lamda,size)
产生服从参数为lamda,大小为size的泊松分布。
random.normal
random.normal(loc,scale,size)
产生均值为loc,标准差为scale,大小为size的正态分布