[英]Not getting expected results in Chi-squared Test using 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()
假设
Null 假设:不同文化程度的婚姻状况分布不存在差异。
替代假设:存在差异
编码
1. import chi2_contingency
并from scipy.stats import chi2
。
2.声明一个二维数组,其中包含按教育程度划分的婚姻状况列联表中提到的值。
3.计算和打印的值
– 卡方统计 – 自由度 – P 值 – 提示:使用chi2_contigency()
function 4.假设 alpha 值为 0.05
5.将P值与alpha进行比较,决定是否拒绝null假设。
– If Rejected print “Reject the Null Hypothesis” – Else print “Failed to reject the Null Hypothesis”
样本 output 2.33 4.5 8.9 拒绝 Null 假设
我的代码:
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')
谢谢你,拉克什
使用 prob = 0.05 而不是 0.95
谢谢!
从 scipy.stats 导入 chi2_contingency 从 scipy.stats 导入 chi2
def chi_test(): # Notation Output 1. stat: Float 2. dof: Integer 3. p_val: Float 4. res: String
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
如果名称=='主要':打印(chi_test())
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.