进行2个样本t检验

时间:2014-03-24 13:55:19

标签: python numpy statistics

我有样本1和样本2的平均值,std dev和n - 样本来自样本总体,但是由不同的实验室测量。

n对于样本1和样本2是不同的。我想进行加权(考虑到n)双尾t检验。

我尝试使用scipy.stat模块创建我的数字np.random.normal,因为它只需要数据而不是像mean和std dev这样的stat值(有没有办法直接使用这些值)。但它没有用,因为数据阵列必须具有相同的大小。

任何有关如何获得p值的帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:51)

如果原始数据为数组ab,则可以将scipy.stats.ttest_ind与参数equal_var=False一起使用:

t, p = ttest_ind(a, b, equal_var=False)

如果您只有两个数据集的摘要统计信息,则可以使用scipy.stats.ttest_ind_from_stats(在版本0.16中添加到scipy)或从公式(http://en.wikipedia.org/wiki/Welch%27s_t_test)计算t值。

以下脚本显示了可能性。

from __future__ import print_function

import numpy as np
from scipy.stats import ttest_ind, ttest_ind_from_stats
from scipy.special import stdtr

np.random.seed(1)

# Create sample data.
a = np.random.randn(40)
b = 4*np.random.randn(50)

# Use scipy.stats.ttest_ind.
t, p = ttest_ind(a, b, equal_var=False)
print("ttest_ind:            t = %g  p = %g" % (t, p))

# Compute the descriptive statistics of a and b.
abar = a.mean()
avar = a.var(ddof=1)
na = a.size
adof = na - 1

bbar = b.mean()
bvar = b.var(ddof=1)
nb = b.size
bdof = nb - 1

# Use scipy.stats.ttest_ind_from_stats.
t2, p2 = ttest_ind_from_stats(abar, np.sqrt(avar), na,
                              bbar, np.sqrt(bvar), nb,
                              equal_var=False)
print("ttest_ind_from_stats: t = %g  p = %g" % (t2, p2))

# Use the formulas directly.
tf = (abar - bbar) / np.sqrt(avar/na + bvar/nb)
dof = (avar/na + bvar/nb)**2 / (avar**2/(na**2*adof) + bvar**2/(nb**2*bdof))
pf = 2*stdtr(dof, -np.abs(tf))

print("formula:              t = %g  p = %g" % (tf, pf))

输出:

ttest_ind:            t = -1.5827  p = 0.118873
ttest_ind_from_stats: t = -1.5827  p = 0.118873
formula:              t = -1.5827  p = 0.118873

答案 1 :(得分:5)

使用最新版本的Scipy 0.12.0,内置了此功能(实际上可以对不同大小的样本进行操作)。在scipy.stats ttest_ind函数中,当标记equal_var设置为False时,{{3}}函数会执行Welch的t检验。

例如:

>>> import scipy.stats as stats
>>> sample1 = np.random.randn(10, 1)
>>> sample2 = 1 + np.random.randn(15, 1)
>>> t_stat, p_val = stats.ttest_ind(sample1, sample2, equal_var=False)
>>> t_stat
array([-3.94339083])
>>> p_val
array([ 0.00070813])
相关问题