One - One Code All

Blog Content

numpy正态分布normal与多元正态分布multivariate_normal

Python 统计学-科学计算   2011-11-21 21:27:38

numpy正态分布normal与多元正态分布multivariate_normal


多元正态分布:

numpy.random.multivariate_normal(依据均值和协方差生成数据,提醒:计算协方差别忘了转置)


 >>> import numpy as np

>>> A1_mean = [1, 1]

>>> A1_cov = [[2, .99], [1, 1]]
>>> A1 = np.random.multivariate_normal(A1_mean, A1_cov, 10) #依据指定的均值和协方差生成数据

>>> A1
array([[-1.72475813,     0.33681971],
         [ 0.78643798,      0.76700529],
         [ 0.61538183,      -0.75786666],
         [ 2.85758498,      2.55947038],
         [ 1.78292279,      0.75539859],
         [ 1.51245811,      2.2377212 ],
         [ 1.86063512,      0.89370386],
         [ 0.40500526,      0.83009172],
         [ 1.39342622,     1.66581794],
         [-1.75143864,     -0.39855419]])

>>> np.mean(A1) #求全体数的均值
0.83136316789824638

>>> np.mean(A1,axis=0)  #按列求均值(每列为一组),和预设有点差距
array([ 0.77376555, 0.88896078])

>>> np.mean(A1,axis=1)#按行求均值(每行为一组)
array([-0.69396921, 0.77672163, -0.07124242, 2.70852768, 1.26916069,1.87508966, 1.37716949, 0.61754849, 1.52962208, -1.07499641])

>>> np.cov(A1.T)  #转置后求协方差,和预设的差不多
>>> np.cov(A1.T)  #转置后求协方差,和预设的差不多
array([[ 2.2502378 ,      1.08232076],
         [ 1.08232076,     1.10267326]])

 

>> np.cov(A1).shape #没有转置,就是10*10的矩阵了
(10, 10)

>>> np.cov(A1)



后续补充:


正态分布:

numpy.random.normal(loc=0.0, scale=1.0, size=None) 依据均值和标准差生成数据


参数的意义为:

loc:float
    此概率分布的均值(对应着整个分布的中心centre)
scale:float
    此概率分布的标准差(对应于分布的宽度,scale越大越矮胖,scale越小,越瘦高)
size:int or tuple of ints
    输出的shape,默认为None,只输出一个值


我们更经常会用到的np.random.randn(size)所谓标准正态分布(μ=0,σ=1),对应于np.random.normal(loc=0, scale=1, size)。

采样(sampling)

# 从某一分布(由均值和标准差标识)中获得样本
mu, sigma = 0, .1
s = np.random.normal(loc=mu, scale=sigma, size=1000)


官网参考:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal

https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multivariate_normal.html#numpy.random.multivariate_normal 


上一篇:从np.random.normal()到正态分布的拟合
下一篇:python中pandas的series用法

The minute you think of giving up, think of the reason why you held on so long.