#coding=utf-8 """ @author=wanggang data=2020.10.30 """ from scipy.stats import ttest_1samp import numpy as np from scipy.stats import ttest_ind, norm, f import numpy as np def read(): sample=[] """ def ftest(s1, s2): '''F检验样本总体方差是否相等''' print("Null Hypothesis:var(s1)=var(s2),α=0.05") F = np.var(s1) / np.var(s2) v1 = len(s1) - 1 v2 = len(s2) - 1 p_val = 1 - 2 * abs(0.5 - f.cdf(F, v1, v2)) print(p_val) if p_val < 0.05: print("Reject the Null Hypothesis.") equal_var = False else: print("Accept the Null Hypothesis.") equal_var = True return equal_var def ttest_ind_fun(s1, s2): '''t检验独立样本所代表的两个总体均值是否存在差异''' equal_var = ftest(s1, s2) print("Null Hypothesis:mean(s1)=mean(s2),α=0.05") ttest, pval = ttest_ind(s1, s2, equal_var=equal_var) if pval < 0.05: print("Reject the Null Hypothesis.") else: print("Accept the Null Hypothesis.") return pval """ #np.random.seed(42) #s1 = norm.rvs(loc=1, scale=1.0, size=20) #s2 = norm.rvs(loc=1.5, scale=0.5, size=20) #s3 = norm.rvs(loc=1.5, scale=0.5, size=25) #ttest_ind_fun(s1, s2) #ttest_ind_fun(s2, s3) print("原假设:假设非专业均值和总体的相等") print("备择假设:假设非专业的均值不等于总体的均值") print("Null Hypothesis:μ=μ0=30,α=0.05") ages = [25,36,15,40,28,31,32,30,29,28,27,33,35] t = (np.mean(ages)-30)/(np.std(ages,ddof=1)/np.sqrt(len(ages)))#这里的30 为总体的平均值 ddof=1 是计算的标准差。np.sqrt(len(ages))这个是 ttest,pval = ttest_1samp(ages,30)#计算p 值 #print(t,ttest) if pval < 0.05: print("拒绝原假设,备择假设成立。存在显著性差异") else: print("接收原假设,不存在显著性差异")
t检验的代码
最新推荐文章于 2022-03-02 07:46:19 发布
本文介绍了如何使用scipy库进行F检验,检查两个样本总体方差是否相等,以及t检验来判断独立样本均值是否存在显著差异。通过实例演示了如何应用ttest_1samp和ttest_ind函数,并针对特定假设进行了实际计算。
摘要由CSDN通过智能技术生成