在使用Python的卡方测试中没有得到预期的结果



有人能检查一下下面的问题和我的代码,告诉我为什么我没有得到预期的结果吗?

问题:该表显示了按教育程度划分的婚姻状况的列联表。采用卡方检验检验同性恋。教育程度婚姻状况列联表。

通过执行以下命令python 查看表格

from prettytable import PrettyTable
t = PrettyTable([‘Marital Status’,’Middle school’, ‘High School’,’Bachelor’,’Masters’,’PhD’])
t.add_row([‘Single’,18,36,21,9,6])
t.add_row([‘Married’,12,36,45,36,21])
t.add_row([‘Divorced’,6,9,9,3,3])
t.add_row([‘Widowed’,3,9,9,6,3])
print (t)
exit()

假设

零假设:不同类型的教育水平在婚姻状况方面的分布没有差异。

替代假设:存在差异

编码

1.CCD_ 1和CCD_。

2.声明一个2D数组,其中包含按教育程度划分的婚姻状况列联表中提到的值。

3.计算并打印的值

–卡方统计–自由度–P值–提示:使用chi2_contigency()函数4.假设阿尔法值为0.05

5.将p值与α进行比较,并决定是否拒绝零假设。

–如果被拒绝,打印"拒绝零假设"–否则打印"拒绝零假设失败">

样本输出2.33 4.5 8.9拒绝零假设

我的代码:

from scipy.stats import chi2_contingency
from scipy.stats import chi2
table= [ [18,36,21,9,6],[12,36,45,36,21], [6,9,9,3,3],[3,9,9,6,3] ]
stat,p,dof,expected = chi2_contingency(table)
prob = 0.95
critical = chi2.ppf(prob, dof)
if abs(stat) >= critical:
print(stat, dof ,p ,'Reject the Null Hypothesis')
else:
print(stat, dof ,p ,'Failed to reject the Null Hypothesis')

谢谢,Rakesh

使用prob=0.05而不是0.95

谢谢!

from scipy.stats import chi2_contingency
from scipy.stats import chi2
def chi_test():
'''
Output
1. stat: Float
2. dof : Integer
3. p_val: Float
4. res: String
'''
#Note: Round off the Float values to 2 decimal places.
table=[[18,36,21,9,6],[12,36,45,36,21],[6,9,9,3,3],[3,9,9,6,3]]
stat,p_val,dof,res=chi2_contingency(table)

prob=0.95
critical=chi2.ppf(prob, dof)
if abs(stat) >= critical:
res = 'Reject the Null Hypothesis'
else:
res= 'Failed to reject the Null Hypothesis'
alpha=1.0-prob
if p_val <= alpha:
res = 'Reject the Null Hypothesis'
else:
res = 'Failed to reject the Null Hypothesis'

stat = round(stat,2)
dof = round(dof,2)
p_val = round(p_val,2)


return stat,dof,p_val,res   
if __name__=='__main__':
print(chi_test())

从scipy.stats导入chi2_应急从scipy.stats导入chi2

def chi_test((:#符号输出1.统计:浮动2.自由度:整数3.p_val:浮动4.res:字符串

代码

table=[[18,36,21,9,6],[12,36,45,36,21],[6,9,9,3,3],[3,9,9,6,3]]
stat,dof,p_val,res=chi2_contingency(table)

prob=0.95
critical=chi2.ppf(prob, dof)
if abs(stat) >= critical:
print('Reject the Null Hypothesis')
else:
print('Failed to reject the Null Hypothesis')
alpha=1.0-prob
if p_val <= alpha:
print('Reject the Null Hypothesis')
else:
print('Failed to reject the Null Hypothesis')

return stat,dof,p_val,res   

如果name='main':打印(chi_test(((

最新更新