列聯表: 卡方獨立檢定 (Contingency Table: Chi-square Test of Independence)

套路32: 列聯表: 卡方獨立檢定
(Contingency Table: Chi-square 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)
結果:
(8.987183908045976,      # The test statistic
 0.02946176965294219,    # 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.029 < 0.05H0: 髮色與性別無關(independent)不成立。
# 反之如果p-value > 0.05H0: 髮色與性別無關(independent)成立。

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)
結果:
(1.5060523853416006,   # The test statistic
0.2197424469161312,    # The p-value of the test
1,                     # Degrees of freedom = 1需做葉慈修正correction = True
array([[ 8.74285714,  9.25714286],
        [25.25714286, 26.74285714]]))
# p = 0.2197 > 0.05H0: 慣用左手或右手與性別無關(independent)成立。
# 反之如果p-value < 0.05H0: 慣用左手或右手與性別無關(independent)不成立。

留言

這個網誌中的熱門文章

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

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

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