我如何才能摆脱循环,使我的相关矩阵函数更有效

2024-04-19 19:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个函数,计算相关矩阵和预期的工作,但我试图使它更有效,摆脱循环,但我有困难这样做。我的职责如下:

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()等内置函数执行此计算的更有效方法是什么。你知道吗


Tags: of函数infordefnprangenum
1条回答
网友
1楼 · 发布于 2024-04-19 19:13:07

一旦你有了协方差矩阵,你只需要乘以对角线逆平方根的乘积。使用代码的位作为起点:

covarianceMatrix = np.cov(X)
tmp = 1.0 / np.sqrt(np.diag(covarianceMatrix))

corr = covarianceMatrix.copy()
corr *= tmp[:, None]
corr *= tmp[None, :]

如果您有复杂的值,则会有点困难,您可能应该通过以下方式在-1和1之间剪裁:

np.clip(corr, -1, 1, out=corr)

相关问题 更多 >