我有这个函数,计算相关矩阵和预期的工作,但我试图使它更有效,摆脱循环,但我有困难这样做。我的职责如下:
def correlation(X):
N = X.shape[0] # num of rows
D = X.shape[1] # num of cols
covarianceMatrix = np.cov(X) # start with covariance matrix
# use covarianceMatrix to create size of M
M = np.zeros([covarianceMatrix.shape[0], covarianceMatrix.shape[1]])
for i in range(covarianceMatrix.shape[0]):
for j in range(covarianceMatrix.shape[1]):
corr = covarianceMatrix[i, j] / np.sqrt(np.dot(covarianceMatrix[i, i], covarianceMatrix[j, j]))
M[i,j] = corr
return M
使用numpy而不使用corrcoef()等内置函数执行此计算的更有效方法是什么。你知道吗
一旦你有了协方差矩阵,你只需要乘以对角线逆平方根的乘积。使用代码的位作为起点:
如果您有复杂的值,则会有点困难,您可能应该通过以下方式在-1和1之间剪裁:
np.clip(corr, -1, 1, out=corr)
相关问题 更多 >
编程相关推荐