首页 > 解决方案 > 使用python在学生t检验中出错

问题描述

我想从以下两个具有零假设的样本中执行学生 t 检验,因为它们具有相同的均值:

$猫数据1.txt

2
3
4
5
5
5
5
2

$猫数据2.txt

4
7
9
10
8
7
3

我从https://machinelearningmastery.com/how-to-code-the-students-t-test-from-scratch-in-python/得到了执行 t-test 的想法和脚本

我的脚本是:

$猫测试.py

from math import sqrt
from numpy import mean
from scipy.stats import sem
from scipy.stats import t
def independent_ttest(data1, data2, alpha):
        # calculate means
        mean1, mean2 = mean(data1), mean(data2)
        # calculate standard errors
        se1, se2 = sem(data1), sem(data2)
        # standard error on the difference between the samples
        sed = sqrt(se1**2.0 + se2**2.0)
        # calculate the t statistic
        t_stat = (mean1 - mean2) / sed
        # degrees of freedom
        df = len(data1) + len(data2) - 2
        # calculate the critical value
        cv = t.ppf(1.0 - alpha, df)
        # calculate the p-value
        p = (1.0 - t.cdf(abs(t_stat), df)) * 2.0
        # return everything
        return t_stat, df, cv, p
data1 = open('data1.txt')
data2 = open('data2.txt')
alpha = 0.05
t_stat, df, cv, p = independent_ttest(data1, data2, alpha)
print('t=%.3f, df=%d, cv=%.3f, p=%.3f' % (t_stat, df, cv, p))
# interpret via critical value
if abs(t_stat) <= cv:
        print('Accept null hypothesis that the means are equal.')
else:
        print('Reject the null hypothesis that the means are equal.')
# interpret via p-value
if p > alpha:
        print('Accept null hypothesis that the means are equal.')
else:
        print('Reject the null hypothesis that the means are equal.')

当我将此脚本作为 python3 ttest.py 运行时,我收到以下错误。我想我需要更改打印语句,但无法做到。

Traceback (most recent call last):
  File "t-test.py", line 28, in <module>
    t_stat, df, cv, p = independent_ttest(data1, data2, alpha)
  File "t-test.py", line 10, in independent_ttest
    mean1, mean2 = mean(data1), mean(data2)
  File "/home/kay/.local/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 3118, in mean
    out=out, **kwargs)
  File "/home/kay/.local/lib/python3.5/site-packages/numpy/core/_methods.py", line 87, in _mean
    ret = ret / rcount

  TypeError: unsupported operand type(s) for /: '_io.TextIOWrapper' and 'int'

标签: python

解决方案


所以您的问题是您正在打开文件但没有从文件中读取数据(或将其转换为列表)。基本上,打开文件只是准备要被 Python 读取的文件——您需要单独读取它。

另外作为一个快速的旁注,请确保在完成后关闭文件,否则如果您快速连续多次运行代码,您可能会遇到问题。下面的代码应该可以满足您的需要,只需用此代码替换对打开的调用,并根据需要替换文件名和其他详细信息。这里的数组是您要传递给的数据independent_ttest

array = []
with open("test1.txt") as file:
        while value:=file.readline():
                array.append(int(value))
print(array)

我们使用打开我们的文件with 以确保它在最后关闭。 然后我们使用一个while循环来读取每一行。将:= 每一行分配给值,因为它们是循环的。 最后,对于每个值,我们将其从 string 转换为 int,然后将其附加到我们的列表中。

希望这有帮助!如果您有任何问题,请告诉我!


推荐阅读