Подтвердить что ты не робот

Как рассчитать статистику "t-test" с numpy

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

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

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

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

4b9b3361

Ответ 1

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

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

Ответ 2

Ответ на

van с помощью scipy в точности правильный, и использование функций scipy.stats.ttest_* очень удобно.

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

Ответ 3

Как только вы получите 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)