快速皮尔逊在1个向量和许多其他向量之间?

2024-04-19 10:44:51 发布

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

我正在寻找一种更有效的方法来计算长度为1000的静态向量与其他长度相同的向量之间的皮尔逊系数

我的天真方法是成对关联:

import numpy as np
from scipy import stats
A = np.random.rand(1,1000)
otherVectors = np.random.rand(700,1000)

for B in otherVectors:
    R,p = stats.pearsonr(A, B)

只是我想问一下,是否有更快的解决方案

非常感谢


1条回答
网友
1楼 · 发布于 2024-04-19 10:44:51

一次全部手动计算

def pearsonr_many(x, ys):
    x_mean = x.mean()
    y_means = ys.mean(axis=1)

    xm, yms = x - x_mean, ys - y_means[:, newaxis]
    r = yms @ xm / np.sqrt(xm @ xm * (yms * yms).sum(axis=1))
    r = r.clip(-1, 1)

    prob = special.betainc(
        len(x) / 2 - 1,
        0.5,
        1 / (1 + r * r / (1 - r * r))
    )

    return r, prob

相关问题 更多 >