2015-05-22 80 views
3

有没有一种方法可以在Python中找到r置信区间?使用等效于Python中cor.test的R's

cor.test(m, h) 

    Pearson's product-moment correlation 

data: m and h 
t = 0.8974, df = 4, p-value = 0.4202 
alternative hypothesis: true correlation is not equal to 0 
95 percent confidence interval: 
-0.6022868 0.9164582 
sample estimates: 
     cor 
0.4093729 

在Python我可以计算出R(COR):

在R I可以做类似

r,p = scipy.stats.pearsonr(df.age, df.pets) 

但是,这并不返回将R置信区间。

回答

5

下面就来计算置信内部

首先得到的相关值(皮尔逊)

In [85]: from scipy import stats 

In [86]: corr = stats.pearsonr(df['col1'], df['col2']) 

In [87]: corr 
Out[87]: (0.551178607008175, 0.0) 

使用Fisher变换得到ž

In [88]: z = np.arctanh(corr[0]) 

In [89]: z 
Out[89]: 0.62007264620685021 

一个方式,Σ值即标准错误

In [90]: sigma = (1/((len(df.index)-3)**0.5)) 

In [91]: sigma 
Out[91]: 0.013840913308956662 

获取正常的95%区间的概率密度函数的正常连续型随机变量适用two-sided条件公式

In [92]: cint = z + np.array([-1, 1]) * sigma * stats.norm.ppf((1+0.95)/2) 

最后以双曲正切获得间隔值的95%

In [93]: np.tanh(cint) 
Out[93]: array([ 0.53201034, 0.56978224]) 
+0

谢谢你,解决它。我想知道为什么(如果)statsmodels和/或scipy还没有提供这个。 – ComposedTreatment

+0

那么,我也很惊讶,或者我没有足够好地搜索堆栈。 – Zero