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



我的目标是使用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)

您可以用以下方法避免另一个答案中的矩阵转置:

N, D = (5, 3)
tmp = np.random.rand(N, D)
tmp_centered = tmp - np.mean(tmp, axis=0)
cov = np.einsum('ji,jk->ik', tmp_centered , tmp_centered) / (N-1)

最新更新