多元正态计算不产生标准正态变量

2024-07-05 12:58:40 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能更像是一个数学问题而不是numpy,所以我不确定,这可能需要发布在交叉验证上

问题描述

我正在使用numpy函数np.random.multivariate_normal()生成随机的相关数据。我想有5个相关变量,每个分布标准正态。我相信我的协方差矩阵是正确指定的,对角线等于1.0,内部值是我想要的相关性。生成的数据始终具有正确的平均值0,但标准偏差是不可预测的

可复制示例

以下是一个可复制的代码示例:

# rho = randomizer.config.customers.correlation
rho = np.array([
       [  1.0 , -0.2 ,  0.7 ,  0.1 ,  0.1 ],
       [ -0.2 ,  1.0 ,  0.7 ,  0.5 ,  0.2 ],
       [  0.7 ,  0.7 ,  1.0 ,  0.6 ,  0.5 ],
       [  0.1 ,  0.5 ,  0.6 ,  1.0 ,  0.3 ],
       [  0.1 ,  0.2 ,  0.5 ,  0.3 ,  1.0 ]
])
# rho = np.identity(5)
mu = np.repeat(0, 5)


standard_deviations = []
for i in range(10000):
    np.random.seed()
    sd = np.std(np.random.multivariate_normal(mu, rho, size=1000)[:, 0])
    standard_deviations.append(sd)
    
plt.show(plt.hist(standard_deviations, edgecolor="black", bins=40))

这将生成以下绘图:

enter image description here

标准偏差明显大于协方差/相关矩阵中规定的1.0

有没有一个明显的解释让我错过了?我注意到,如果我使用单位矩阵而不是相关矩阵,问题就会消失:

rho = np.identity(5)
mu = np.repeat(0, 5)


standard_deviations = []
for i in range(10000):
    np.random.seed()
    sd = np.std(np.random.multivariate_normal(mu, rho, size=1000)[:, 0])
    standard_deviations.append(sd)
    
plt.show(plt.hist(standard_deviations, edgecolor="black", bins=40))

enter image description here

非常感谢您的帮助


Tags: 数据numpy示例nppltrandomsdstandard