进行两次样品测试

2024-04-20 10:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个样本1和样本2的平均值,标准偏差和n-样本取自样本人群,但由不同的实验室测量。

样品1和样品2的n不同。我想做一个加权(考虑n)双尾t检验。

我尝试使用scipy.stat模块,用np.random.normal创建数字,因为它只接受数据,而不接受mean和std dev之类的stat值(有没有办法直接使用这些值)。但由于数据数组的大小必须相等,因此它不起作用。

任何关于如何得到p值的帮助都将非常感谢。


Tags: 模块数据np样品数字randomscipy实验室
2条回答

如果原始数据是数组ab,则可以将^{}与参数equal_var=False一起使用:

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

如果只有这两个数据集的摘要统计信息,则可以使用^{}(在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

使用最新版本的Scipy 0.12.0,此功能是内置的(实际上对不同大小的样本进行操作)。在scipy.stats中,当标志equal_var设置为False时,^{}函数执行Welch的t-test。

例如:

>>> 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])

相关问题 更多 >