列聯表: 獨立檢定 (Contingency Table: Test of Independence)

套路33: 列聯表: 獨立檢定
(Contingency Table: Test of Independence)

1. 使用時機: 用於檢定兩個隨機變數之間是否無關(independent)
2. 分析類型: 類別資料分析(Categorical Data Analysis)
3. 資料範例一:
咪路調查不同性別大學生頭髮顏色資料如下:
髮色
黑色
棕色
金色
紅色
總數
男生
32
43
16
9
100
女生
55
65
64
16
200
試問髮色與性別是否有關?
H0: 髮色與性別無關(independent)
HA: 髮色與性別有關。

4. 使用Python計算列聯表分析一:
import numpy as np
import scipy.stats
obs = np.array([[32,43,16,9], [55,65,64,16]])
scipy.stats.chi2_contingency(obs, correction = False, lambda_ = "log-likelihood")
結果:
(9.512148957197008,         # The test statistic
 0.023202466535552493,      # The p-value of the test
 3,                         # Degrees of freedom
 array([[29.        , 36.        , 26.66666667,  8.33333333],
        [58.        , 72.        , 53.33333333, 16.66666667]]))
# p = 0.023 < 0.05H0: 髮色與性別無關(independent)不成立。
# 反之如果p-value > 0.05H0: 髮色與性別無關(independent)成立。

# lambda_ 有下列選項:
# String              Value   Description
# "pearson"             1     Pearson's chi-squared statistic.
#                           In this case, the function is equivalent to `stats.chisquare`.
# "log-likelihood"      0     Log-likelihood ratio. Also known as the G-test.
# "freeman-tukey"      -1/2   Freeman-Tukey statistic.
# "mod-log-likelihood" -1     Modified log-likelihood ratio.
# "neyman"             -2     Neyman's statistic.
# "cressie-read"        2/3   The power recommended.

5. 注意有一種狀況是資料為2 x 2列聯表(degree of freedom = 1)時需做葉慈修正(Yates' correction)如下列範例所示:
咪路調查大學生不同性別慣用左手或右手人數資料如下:

男生
女生
總數
慣用左手
6
12
18
慣用右手
28
24
52
試問慣用左手或右手是否與性別有關?
H0: 慣用左手或右手與性別無關(independent)
HA: 慣用左手或右手與性別有關。

6. 使用Python計算列聯表分析二:
import numpy as np
import scipy.stats
obs = np.array([[6,12], [28,24]])
scipy.stats.chi2_contingency(obs, correction = True, lambda_ = "log-likelihood")
結果:
(1.5233477576256718,    # The test statistic
0.21711357985017252,    # The p-value of the test
1,                      # Degrees of freedom = 1需做葉慈修正correction = True
array([[ 8.74285714,  9.25714286],
        [25.25714286, 26.74285714]]))
# p = 0.2171 > 0.05H0: 慣用左手或右手與性別無關(independent)成立。
# 反之如果p-value < 0.05H0: 慣用左手或右手與性別無關(independent)不成立。

留言

這個網誌中的熱門文章

三因子變異數分析 (Three-Way ANOVA)

兩組獨立樣本變異數相同 t 檢定 (Two-Sample t test with equal variances,parametric)

雙因子變異數分析 (Two-Way ANOVA)