繁体   English   中英

使用 numpy.einsum 计算数据的协方差矩阵

[英]Use numpy.einsum to calculate the covariance matrix of data

我的目标是使用numpy.einsum计算一组数据的协方差矩阵。

example_data = np.array([0.2, 0.3], [0.1, 0.2]])

以下是我试过的代码:

import numpy as np

d = example_data[0].shape[1]
mu = np.mean(example_data, axis=0)
data = np.reshape(example_data,(len(example_data),d,1))
mu = np.tile(mu,len(example_data))
mu = np.reshape(mu,(len(example_data),d,1))
d_to_mean = data-mu 

covariance_matrix = np.einsum('ijk,kji->ij', d_to_mean, np.transpose(d_to_mean)) 
#I don't know how to set the subscripts correctly

任何如何使这种方法可行的建议表示赞赏!

根据协方差矩阵的定义,任务可以很容易地解决

tmp = np.random.rand(5,3) # 5 corresponds to 5 observations, 3 corresponds to 3 variables
tmp_mean = np.mean(tmp,axis=0)[:,None]
tmp_centered = tmp.T - tmp_mean
cov = (tmp_centered @ tmp_centered.T) / (5-1)

如果你仍然需要einsum

cov_ein = np.einsum('ij,jk->ik',tmp_centered,tmp_centered.T) / (5-1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM