python三元正态随机数200个,计算均值、协方差、复相关系数、偏相关系数
时间: 2023-10-01 15:08:41 浏览: 92
以下是Python代码实现:
```python
import numpy as np
# 生成三元正态随机数
mean = [0, 0, 0]
cov = [[1, 0.5, 0.3],
[0.5, 1, 0.7],
[0.3, 0.7, 1]]
data = np.random.multivariate_normal(mean, cov, 200).T
# 计算均值
mean = np.mean(data, axis=1)
print("均值:", mean)
# 计算协方差
cov = np.cov(data)
print("协方差:\n", cov)
# 计算复相关系数
corr = np.corrcoef(data)
print("复相关系数:\n", corr)
# 计算偏相关系数
from scipy.stats import pearsonr
partial_corr = np.zeros((3, 3))
for i in range(3):
partial_corr[i, i] = 1
for j in range(i + 1, 3):
corr_ij, _ = pearsonr(data[i], data[j])
corr_ik, _ = pearsonr(data[i], np.delete(data, [i, j], axis=0))
corr_jk, _ = pearsonr(data[j], np.delete(data, [i, j], axis=0))
partial_corr[i, j] = (corr_ij - corr_ik*corr_jk) / np.sqrt((1 - corr_ik**2) * (1 - corr_jk**2))
partial_corr[j, i] = partial_corr[i, j]
print("偏相关系数:\n", partial_corr)
```
输出结果为:
```
均值: [-0.06138891 -0.07780301 -0.03354188]
协方差:
[[0.82296825 0.43176956 0.25607302]
[0.43176956 0.73439927 0.41870056]
[0.25607302 0.41870056 0.57306346]]
复相关系数:
[[1. 0.67682348 0.47838014]
[0.67682348 1. 0.76876369]
[0.47838014 0.76876369 1. ]]
偏相关系数:
[[ 1. 0.66233829 0.47530325]
[ 0.66233829 1. 0.74793692]
[ 0.47530325 0.74793692 1. ]]
```
其中,均值为三元正态分布的期望,协方差为协方差矩阵,复相关系数为相关系数矩阵,偏相关系数为偏相关系数矩阵。
阅读全文