繁体   English   中英

在 2d numpy 数组列上计算成对 t 检验

[英]Compute pairwise t-test on 2d numpy array columns

我想对二维数组列执行成对 t 检验。 如果不使用 itertools,有什么方法可以获得列的所有成对组合?

from scipy import stats
import numpy as np

a = np.random.randn(20,6)

如果您想避免使用 for 循环或列表推导式,您可以使用 numpy 广播实现 t 检验:

a = np.random.randn(20,6)
n1, n2 = a.shape
# Columns mean and squared std
m = np.mean(a,axis=0)
s2 = np.square(np.std(a,axis=0, ddof=1))

# Compute the test statistic
t = (m[:,np.newaxis] - m[np.newaxis,:])/np.sqrt((s2[:,np.newaxis] + s2[np.newaxis,:])/n1)

# Compute the 2-sided p-value
df = 2*n1 - 2
p = 2 - 2*stats.t.cdf(t,df=df)

检查与朴素列表理解实现相关的性能:

def t_test(a):
    n1, n2 = a.shape
    m = np.mean(a,axis=0)
    s2 = np.square(np.std(a,axis=0, ddof=1))

    t = (m[:,np.newaxis] - m[np.newaxis,:])/np.sqrt((s2[:,np.newaxis] + s2[np.newaxis,:])/n1)

    df = 2*n1 - 2
    p = 2 - 2*stats.t.cdf(t,df=df)

    return t,p


%timeit t_test(a)
213 µs ± 13 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit [[ (i,j, stats.ttest_ind(a[:,i], a[:,j])) for i in range(n2) if i <j] for j in range(n2)]
4.36 ms ± 139 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

表明 numpy 实现快了大约 20 倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM