36

我正在寻找一个 Python 函数(或者如果没有,则编写我自己的函数)来获取 t 统计量,以便在置信区间计算中使用。

我找到了可以为各种概率/自由度提供答案的表格,比如这个,但我希望能够为任何给定的概率计算这个。对于任何不熟悉此自由度的人来说,样本中的数据点数 (n) -1,顶部列标题的数字是概率 (p),例如,如果使用 2 尾显着性水平 0.05,则您正在查找 t-score 以在计算中使用 95% 的置信度,即如果您重复 n 次测试,结果将落在平均值 +/- 置信区间内。

我已经研究过在 scipy.stats 中使用各种函数,但我所看到的似乎都没有允许我上面描述的简单输入。

Excel 对此有一个简单的实现,例如获取 1000 样本的 t 分数,我需要有 95% 的信心我会使用:=TINV(0.05,999)并且得到分数 ~1.96

这是迄今为止我用来实现置信区间的代码,如您所见,我目前正在使用一种非常粗略的方法来获取 t 分数(只允许 perc_conf 的一些值并警告它不准确样本 < 1000):

# -*- coding: utf-8 -*-
from __future__ import division
import math

def mean(lst):
    # μ = 1/N Σ(xi)
    return sum(lst) / float(len(lst))

def variance(lst):
    """
    Uses standard variance formula (sum of each (data point - mean) squared)
    all divided by number of data points
    """
    # σ² = 1/N Σ((xi-μ)²)
    mu = mean(lst)
    return 1.0/len(lst) * sum([(i-mu)**2 for i in lst])

def conf_int(lst, perc_conf=95):
    """
    Confidence interval - given a list of values compute the square root of
    the variance of the list (v) divided by the number of entries (n)
    multiplied by a constant factor of (c). This means that I can
    be confident of a result +/- this amount from the mean.
    The constant factor can be looked up from a table, for 95% confidence
    on a reasonable size sample (>=500) 1.96 is used.
    """
    if perc_conf == 95:
        c = 1.96
    elif perc_conf == 90:
        c = 1.64
    elif perc_conf == 99:
        c = 2.58
    else:
        c = 1.96
        print 'Only 90, 95 or 99 % are allowed for, using default 95%'
    n, v = len(lst), variance(lst)
    if n < 1000:
        print 'WARNING: constant factor may not be accurate for n < ~1000'
    return math.sqrt(v/n) * c

这是对上述代码的示例调用:

# Example: 1000 coin tosses on a fair coin. What is the range that I can be 95%
#          confident the result will f all within.

# list of 1000 perfectly distributed...
perc_conf_req = 95
n, p = 1000, 0.5 # sample_size, probability of heads for each coin
l = [0 for i in range(int(n*(1-p)))] + [1 for j in range(int(n*p))]
exp_heads = mean(l) * len(l)
c_int = conf_int(l, perc_conf_req)

print 'I can be '+str(perc_conf_req)+'% confident that the result of '+str(n)+ \
      ' coin flips will be within +/- '+str(round(c_int*100,2))+'% of '+\
      str(int(exp_heads))
x = round(n*c_int,0)
print 'i.e. between '+str(int(exp_heads-x))+' and '+str(int(exp_heads+x))+\
      ' heads (assuming a probability of '+str(p)+' for each flip).' 

输出是:

我有 95% 的把握认为 1000 次掷硬币的结果将在 500 次的 +/- 3.1% 范围内,即在 469 到 531 次正面之间(假设每次掷硬币的概率为 0.5)。

我还研究了计算一个范围的t 分布,然后返回得到最接近所需概率的 t 分数,但我在实现公式时遇到了问题。让我知道这是否相关并且您想查看代码,但我假设不是因为可能有更简单的方法。

提前致谢。

4

3 回答 3

59

你试过scipy吗?

您将需要安装 scipy 库...有关在此处安装它的更多信息: http ://www.scipy.org/install.html

安装后,您可以复制 Excel 功能,如下所示:

from scipy import stats
#Studnt, n=999, p<0.05, 2-tail
#equivalent to Excel TINV(0.05,999)
print stats.t.ppf(1-0.025, 999)

#Studnt, n=999, p<0.05%, Single tail
#equivalent to Excel TINV(2*0.05,999)
print stats.t.ppf(1-0.05, 999)

您还可以在此处阅读有关安装库的信息:如何为 python 安装 scipy?

于 2013-10-12T21:27:50.500 回答
3

试试下面的代码:

from scipy import stats
#Studnt, n=22,  2-tail
#stats.t.ppf(1-0.025, df)
# df=n-1=22-1=21
print (stats.t.ppf(1-0.025, 21))
于 2017-08-09T09:25:07.117 回答
0

你可以试试这段代码:

# for small samples (<50) we use t-statistics
# n = 9, degree of freedom = 9-1 = 8
# for 99% confidence interval, alpha = 1% = 0.01 and alpha/2 = 0.005
from scipy import stats

ci = 99
n = 9
t = stats.t.ppf(1- ((100-ci)/2/100), n-1) # 99% CI, t8,0.005
print(t) # 3.36
于 2018-12-06T01:12:55.470 回答