【问题标题】:Perform 2 sample t-test执行 2 个样本 t 检验
【发布时间】:2014-05-01 22:19:42
【问题描述】:

我有样本 1 和样本 2 的平均值、标准差和 n - 样本取自样本总体,但由不同的实验室测量。

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

我尝试通过使用np.random.normal 创建我的数字来使用scipy.stat 模块,因为它只需要数据而不是像mean 和std dev 这样的统计值(有什么方法可以直接使用这些值)。但它不起作用,因为数据数组必须具有相同的大小。

任何有关如何获得 p 值的帮助将不胜感激。

【问题讨论】:

  • 据我了解,Welch 的 t 检验是针对未配对的情况(即不相关的样本)...
  • 问题标题中有“(相关)”。正如@rroowwllaandd 指出的那样,韦尔奇的 t 检验适用于独立样本。如果您有其他想法,请解释一下。
  • 我已经更新了这个问题。希望现在更清楚了

标签: python numpy statistics


【解决方案1】:

如果您将原始数据作为数组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

【讨论】:

  • 非常感谢。特别是对于stdtr - 非常有用
  • 如果只有统计,可以使用 scipy.stats.ttest_ind_from_stats (docs.scipy.org/doc/scipy/reference/generated/…)
  • @JensdeBruijn 感谢您的提醒。在最初编写此答案后,ttest_ind_from_stats 已添加到 scipy 中。我已经更新了答案以包含它。
  • 在使用只有统计信息的版本时,是否有理由使用b.var(ddof=1) 而不是np.std(b)
【解决方案2】:

使用最新版本的 Scipy 0.12.0,此功能是内置的(实际上可以在不同大小的样本上运行)。在 scipy.stats 中,ttest_ind 函数在标志 equal_var 设置为 False 时执行 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])

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2018-11-19
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 2020-09-05
    相关资源
    最近更新 更多