我正在尝试深入理解
stats.pearsonr
的内部机制。我想将 r, p = stats.pearsonr(x, y)
写成独立的代码(见下文)。我已经成功复制了 r
的计算过程,但是 p 值的计算需要使用 scipy.special.betainc
。我在 https://github.com/scipy/scipy/tree/master/scipy/special 中查找,但并未找到 betainc
(我猜测它可能是一些底层的 C 代码)。请问您知道在哪里可以找到该函数的源代码吗?import numpy as np
x = np.random.rand(100)
y = np.random.rand(100)
n = len(x)
mx = x.mean()
my = y.mean()
xm, ym = x - mx, y - my
r_num = np.add.reduce(xm * ym)
r_den = np.sqrt(np.sum(xm*xm, 0) * np.sum(ym*ym, 0))
r = r_num / r_den
r = max(min(r, 1.0), -1.0)
df = n - 2
if abs(r) == 1.0:
p = 0.0
else:
t_squared = r**2 * (df / ((1.0 - r) * (1.0 + r)))
# Now code https://github.com/scipy/scipy/blob/14142ff70d84a6ce74044a27919c850e893648f7/scipy/stats/stats.py#L3020
_x = df/(df+t_squared)
_x = np.asarray(_x)
_x = np.where(_x < 1.0, _x, 1.0)
_a = 0.5*df
_b = 0.5
# Code special.betainc(_a, _b, _x)