[英]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.