python卡方检验计算pvalue值_用观察值和期望值进行卡方检验,并对

你有一个contingency table。要对此数据执行χ2测试,可以使用^{}:In [31]: from scipy.stats import chi2_contingency

In [32]: obs = np.array([[25, 75], [100, 100]])

In [33]: obs

Out[33]:

array([[ 25, 75],

[100, 100]])

In [34]: chi2, p, dof, expected = chi2_contingency(obs)

In [35]: p

Out[35]: 5.9148695289823149e-05

列联表是2x2,所以可以使用Fisher's exact test。这在scipy中实现为^{}:

^{pr2}$

scipy没有更多的列联表。看起来下一个版本的^{}将有更多的工具来分析列联表,但这现在没有帮助。在

不难编写一些代码来计算比例差及其95%置信区间。有一种方法:# Include this if you are using Python 2.7. Or tweak the code in the

# function to ensure that division uses floating point.

from __future__ import division

def diffprop(obs):

"""

`obs` must be a 2x2 numpy array.

Returns:

delta

The difference in proportions

ci

The Wald 95% confidence interval for delta

corrected_ci

Yates continuity correction for the 95% confidence interval of delta.

"""

n1, n2 = obs.sum(axis=1)

prop1 = obs[0,0] / n1

prop2 = obs[1,0] / n2

delta = prop1 - prop2

# Wald 95% confidence interval for delta

se = np.sqrt(prop1*(1 - prop1)/n1 + prop2*(1 - prop2)/n2)

ci = (delta - 1.96*se, delta + 1.96*se)

# Yates continuity correction for confidence interval of delta

correction = 0.5*(1/n1 + 1/n2)

corrected_ci = (ci[0] - correction, ci[1] + correction)

return delta, ci, corrected_ci

例如In [22]: obs

Out[22]:

array([[ 25, 75],

[100, 100]])

In [23]: diffprop(obs)

Out[23]:

(-0.25,

(-0.35956733089748971, -0.14043266910251032),

(-0.36706733089748972, -0.13293266910251031))

返回的第一个值是比例差delta。接下来的两对是delta的Wald 95%置信区间和Yates连续性修正的Wald 95%置信区间。在

如果不喜欢这些负值,可以先反转行:In [24]: diffprop(obs[::-1])

Out[24]:

(0.25,

(0.14043266910251032, 0.35956733089748971),

(0.13293266910251031, 0.36706733089748972))

为了进行比较,以下是R中的类似计算:> obs

[,1] [,2]

[1,] 25 75

[2,] 100 100

> prop.test(obs, correct=FALSE)

2-sample test for equality of proportions without continuity

correction

data: obs

X-squared = 17.1429, df = 1, p-value = 3.467e-05

alternative hypothesis: two.sided

95 percent confidence interval:

-0.3595653 -0.1404347

sample estimates:

prop 1 prop 2

0.25 0.50

> prop.test(obs, correct=TRUE)

2-sample test for equality of proportions with continuity correction

data: obs

X-squared = 16.1297, df = 1, p-value = 5.915e-05

alternative hypothesis: two.sided

95 percent confidence interval:

-0.3670653 -0.1329347

sample estimates:

prop 1 prop 2

0.25 0.50

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值