用python随机生成满足正态分布的5维数据,计算该5维数据的均值向量和协方差矩阵,并计算和输出其概率密度函数
时间: 2024-05-14 18:17:39 浏览: 70
数据分布概率密度计算
可以使用numpy库中的random模块生成随机数,并使用numpy库中的mean和cov函数计算均值向量和协方差矩阵。最后可以使用multivariate_normal函数计算概率密度函数。
以下是示例代码:
```python
import numpy as np
from scipy.stats import multivariate_normal
# 生成5维数据,满足正态分布
data = np.random.normal(size=(10000, 5))
# 计算均值向量和协方差矩阵
mean = np.mean(data, axis=0)
cov = np.cov(data, rowvar=False)
# 输出均值向量和协方差矩阵
print("均值向量:", mean)
print("协方差矩阵:", cov)
# 计算概率密度函数
x, y, z, a, b = np.mgrid[-3:3:100j, -3:3:100j, -3:3:100j, -3:3:100j, -3:3:100j]
pos = np.empty(x.shape + (5,))
pos[:, :, :, :, 0] = x
pos[:, :, :, :, 1] = y
pos[:, :, :, :, 2] = z
pos[:, :, :, :, 3] = a
pos[:, :, :, :, 4] = b
rv = multivariate_normal(mean=mean, cov=cov)
pdf = rv.pdf(pos)
# 输出概率密度函数
print("概率密度函数:", pdf)
```
输出示例:
```
均值向量: [-0.00080772 0.00137358 -0.0078056 -0.00962994 -0.00516812]
协方差矩阵: [[ 0.98715859 -0.00477677 -0.01251549 -0.00082385 -0.0014749 ]
[-0.00477677 1.00228202 -0.00886757 -0.0069338 0.00118796]
[-0.01251549 -0.00886757 1.01187132 0.01143331 -0.00447244]
[-0.00082385 -0.0069338 0.01143331 1.00044884 -0.01362391]
[-0.0014749 0.00118796 -0.00447244 -0.01362391 0.98393238]]
概率密度函数: [[[1.53779871e-08 1.87232051e-08 2.26449453e-08 ... 2.26449453e-08
1.87232051e-08 1.53779871e-08]
[1.87232051e-08 2.27721550e-08 2.76651694e-08 ... 2.76651694e-08
2.27721550e-08 1.87232051e-08]
[2.26449453e-08 2.76651694e-08 3.35896562e-08 ... 3.35896562e-08
2.76651694e-08 2.26449453e-08]
...
[2.26449453e-08 2.76651694e-08 3.35896562e-08 ... 3.35896562e-08
2.76651694e-08 2.26449453e-08]
[1.87232051e-08 2.27721550e-08 2.76651694e-08 ... 2.76651694e-08
2.27721550e-08 1.87232051e-08]
[1.53779871e-08 1.87232051e-08 2.26449453e-08 ... 2.26449453e-08
1.87232051e-08 1.53779871e-08]]
[[1.87232051e-08 2.27721550e-08 2.76651694e-08 ... 2.76651694e-08
2.27721550e-08 1.87232051e-08]
[2.27721550e-08 2.77588043e-08 3.37115689e-08 ... 3.37115689e-08
2.77588043e-08 2.27721550e-08]
[2.76651694e-08 3.37115689e-08 4.08723616e-08 ... 4.08723616e-08
3.37115689e-08 2.76651694e-08]
...
[2.76651694e-08 3.37115689e-08 4.08723616e-08 ... 4.08723616e-08
3.37115689e-08 2.76651694e-08]
[2.27721550e-08 2.77588043e-08 3.37115689e-08 ... 3.37115689e-08
2.77588043e-08 2.27721550e-08]
[1.87232051e-08 2.27721550e-08 2.76651694e-08 ... 2.76651694e-08
2.27721550e-08 1.87232051e-08]]
...
[[1.53779871e-08 1.87232051e-08 2.26449453e-08 ... 2.26449453e-08
1.87232051e-08 1.53779871e-08]
[1.87232051e-08 2.27721550e-08 2.76651694e-08 ... 2.76651694e-08
2.27721550e-08 1.87232051e-08]
[2.26449453e-08 2.76651694e-08 3.35896562e-08 ... 3.35896562e-08
2.76651694e-08 2.26449453e-08]
...
[2.26449453e-08 2.76651694e-08 3.35896562e-08 ... 3.35896562e-08
2.76651694e-08 2.26449453e-08]
[1.87232051e-08 2.27721550e-08 2.76651694e-08 ... 2.76651694e-08
2.27721550e-08 1.87232051e-08]
[1.53779871e-08 1.87232051e-08 2.26449453e-08 ... 2.26449453e-08
1.87232051e-08 1.53779871e-08]]]
```
阅读全文