Nor*_*ldt 22 python statistics numpy
我有样本1和样本2的平均值,std dev和n - 样本来自样本群体,但是由不同的实验室测量.
n对于样本1和样本2是不同的.我想进行加权(考虑n)双尾t检验.
我尝试使用scipy.stat模块创建我的数字np.random.normal
,因为它只需要数据而不是像mean和std dev那样的stat值(有没有办法直接使用这些值).但它不起作用,因为数据阵列必须具有相同的大小.
任何有关如何获得p值的帮助都将受到高度赞赏.
War*_*ser 57
如果您有原始数据作为数组a
和b
,你可以使用scipy.stats.ttest_ind
带参数equal_var=False
:
t, p = ttest_ind(a, b, equal_var=False)
Run Code Online (Sandbox Code Playgroud)
如果您只有两个数据集的摘要统计信息,则可以使用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))
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
使用最新版本的Scipy 0.12.0,内置了此功能(实际上可以对不同大小的样本进行操作).在scipy.stats
该ttest_ind
标志equal_var
设置为时,该函数执行Welch的t检验False
.
例如:
>>> 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])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
59558 次 |
最近记录: |