Как рассчитать статистику "t-test" с помощью numpy - PullRequest
24 голосов
/ 24 февраля 2010

Я хочу сгенерировать статистику о модели, которую я создал в python. Я хотел бы сгенерировать t-критерий, но мне было интересно, есть ли простой способ сделать это с помощью numpy / scipy. Есть ли хорошие объяснения вокруг?

Например, у меня есть три связанных набора данных, которые выглядят так:

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

Теперь я хотел бы провести t-тест студента на них.

Ответы [ 3 ]

27 голосов
/ 24 февраля 2010

В пакете scipy.stats имеется несколько ttest_... функций. Смотрите пример из здесь :

>>> print 't-statistic = %6.3f pvalue = %6.4f' %  stats.ttest_1samp(x, m)
t-statistic =  0.391 pvalue = 0.6955
3 голосов
/ 26 июня 2017

ответ ван с использованием scipy абсолютно правильный, а использование 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%), вы не должны ничего делать для конкретного случая.

0 голосов
/ 09 января 2013

Как только вы получите свое t-значение, вы можете задаться вопросом, как интерпретировать его как вероятность - я понял. Вот функция, которую я написал, чтобы помочь с этим.

Это основано на информации, которую я почерпнул из http://www.vassarstats.net/rsig.html и http://en.wikipedia.org/wiki/Student%27s_t_distribution.

# Given (possibly random) variables, X and Y, and a correlation direction,
# returns:
#  (r, p),
# where r is the Pearson correlation coefficient, and p is the probability
# of getting the observed values if there is actually no correlation in the given
# direction.
#
# direction:
#  if positive, p is the probability of getting the observed result when there is no
#     positive correlation in the normally distributed full populations sampled by X
#     and Y
#  if negative, p is the probability of getting the observed result, when there is no
#     negative correlation
#  if 0, p is the probability of getting your result, if your hypothesis is true that
#    there is no correlation in either direction
def probabilityOfResult(X, Y, direction=0):
    x = len(X)
    if x != len(Y):
        raise ValueError("variables not same len: " + str(x) + ", and " + \
                         str(len(Y)))
    if x < 6:
        raise ValueError("must have at least 6 samples, but have " + str(x))
    (corr, prb_2_tail) = stats.pearsonr(X, Y)

    if not direction:
        return (corr, prb_2_tail)

    prb_1_tail = prb_2_tail / 2
    if corr * direction > 0:
        return (corr, prb_1_tail)

    return (corr, 1 - prb_1_tail)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...