您如何计算Python中Pearson r的置信区间?

pix*_*tom 5 python statistics scipy pearson

在Python中,我知道如何使用来计算r和相关的p值scipy.stats.pearsonr,但是我无法找到一种计算r的置信区间的方法。怎么做?谢谢你的帮助 :)

ben*_*ylp 7

根据 [1],直接用 Pearson r 计算置信区间是复杂的,因为它不是正态分布的。需要以下步骤:

  1. 将 r 转换为 z',
  2. 计算 z' 置信区间。z' 的抽样分布近似正态分布,标准误差为 1/sqrt(n-3)。
  3. 将置信区间转换回 r。

下面是一些示例代码:

def r_to_z(r):
    return math.log((1 + r) / (1 - r)) / 2.0

def z_to_r(z):
    e = math.exp(2 * z)
    return((e - 1) / (e + 1))

def r_confidence_interval(r, alpha, n):
    z = r_to_z(r)
    se = 1.0 / math.sqrt(n - 3)
    z_crit = stats.norm.ppf(1 - alpha/2)  # 2-tailed z critical value

    lo = z - z_crit * se
    hi = z + z_crit * se

    # Return a sequence
    return (z_to_r(lo), z_to_r(hi))
Run Code Online (Sandbox Code Playgroud)

参考:

  1. http://onlinestatbook.com/2/estimation/correlation_ci.html