Python卡方檢驗判斷分類變量是否相關

問題描述

性別與寵物偏愛是否相關

列聯表

207 282
231 242

解決方案

調用scipy.stats.chi2_contingency

from scipy import stats

x = [[207, 282], [231, 242]]
chi2, p, df, expected = stats.chi2_contingency(x, correction=False)  # 卡方值、P值、自由度、理論值,無需耶茨連續性修正
value = stats.chi2.ppf(0.95, df=df)  # 變量相關概率爲0.95時對應的卡方值
print('自由度{}'.format(df))
print('數據卡方值{:.2f}大於變量相關爲0.95的卡方值{:.2f}'.format(chi2, value))
print('因此變量相關的可能性大於0.95')
print('變量相關的可能性具體爲{:.2f}'.format(1 - p))

# 自由度1
# 數據卡方值4.10大於變量相關爲0.95的卡方值3.84
# 所因此變量相關的可能性大於0.95
# 變量相關的可能性具體爲0.96

參考文獻

  1. Chi-Square Statistic
  2. How to Calculate Critical Values for Statistical Hypothesis Testing with Python
  3. 結合日常生活的例子,瞭解什麼是卡方檢驗
  4. 卡方檢驗
  5. Python - 列聯表的獨立性檢驗(卡方檢驗)
  6. scipy.stats.chi2_contingency
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章