我的目标是使用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
任何建议如何使这种方法可行的赞赏!
2条答案
按热度按时间cxfofazt1#
根据covariance matrix的定义,可以很容易地解决这个任务,
如果您需要
einsum
无论如何vfwfrxfs2#
你可以用下面的方法来避免另一个答案中的矩阵转置: