web-dev-qa-db-ja.com

numpyで統計「t検定」を計算する方法

私はpythonで作成したモデルに関するいくつかの統計を生成しようとしています。その上でt検定を生成したいのですが、numpy/scipyでこれを行う簡単な方法があるかどうか疑問に思っていました。周りに良い説明はありますか?

たとえば、次のような3つの関連データセットがあります。

[55.0, 55.0, 47.0, 47.0, 55.0, 55.0, 55.0, 63.0]

今、私はそれらの学生のt検定をしたいと思います。

25
Mark

scipy.stats パッケージには、いくつかのttest_... 機能。 here の例を参照してください:

>>> print 't-statistic = %6.3f pvalue = %6.4f' %  stats.ttest_1samp(x, m)
t-statistic =  0.391 pvalue = 0.6955
27
van

scipyを使用したvanの答えは正確であり、scipy.stats.ttest_*関数は非常に便利です。

しかし、私はこのページにアクセスして、見出しに記載されているように、純粋なnumpyを使用して、scipyへの依存を回避するソリューションを探しました。この目的のために、ここに示した例を指摘しておきます。 https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html

主な問題は、numpyには累積分布関数がないことです。したがって、私の結論は、実際にはscipyを使用する必要があるということです。とにかく、numpyのみを使用することが可能です。

元の質問から、データセットを比較し、有意な偏差があるかどうかをt検定で判断したいと思います。さらに、サンプルはペアになっていますか? ( https://en.wikipedia.org/wiki/Student%27s_t-test#Unpaired_and_paired_two-sample_t-tests を参照)その場合、次のようにt値とp値を計算できます。

import numpy as np
sample1 = np.array([55.0, 55.0, 47.0, 47.0, 55.0, 55.0, 55.0, 63.0])
sample2 = np.array([54.0, 56.0, 48.0, 46.0, 56.0, 56.0, 55.0, 62.0])
# paired sample -> the difference has mean 0
difference = sample1 - sample2
# the t-value is easily computed with numpy
t = (np.mean(difference))/(difference.std(ddof=1)/np.sqrt(len(difference)))
# unfortunately, numpy does not have a build in CDF
# here is a ridiculous work-around integrating by sampling
s = np.random.standard_t(len(difference), size=100000)
p = np.sum(s<t) / float(len(s))
# using a two-sided test
print("There is a {} % probability that the paired samples stem from distributions with the same means.".format(2 * min(p, 1 - p) * 100))

これはThere is a 73.028 % probability that the paired samples stem from distributions with the same means.これは正気な信頼区間(たとえば5%)をはるかに上回っているため、具体的なケースについては何も結論付けるべきではありません。

4
Echsecutor