在實際應用中,一個實驗的指標往往受到多個因素的影響。
例如飲料的銷量有可能受到銷售地區或者飲料顏色的影響。在方差分析中,若把飲料的顏色看做影響銷量的因素A,把銷售地區看做影響因素B。同時對因素A和因素B進行分析,就稱爲雙因素方差分析。
a b c
a1 b1 20
a1 b2 22
a1 b3 24
a1 b4 16
a1 b5 26
a2 b1 12
a2 b2 10
a2 b3 14
a2 b4 4
a2 b5 22
a3 b1 20
a3 b2 20
a3 b3 18
a3 b4 8
a3 b5 16
a4 b1 10
a4 b2 12
a4 b3 18
a4 b4 6
a4 b5 20
a5 b1 14
a5 b2 6
a5 b3 10
a5 b4 18
a5 b5 10
from statsmodels.formula.api import ols
from statsmodels.stats.anova import anova_lm
formula = 'c~ a + b '
anova_results = anova_lm(ols(formula,df).fit())
print(anova_results)
df sum_sq mean_sq F PR(>F)
a 4.0 335.36 83.84 3.874307 0.021886
b 4.0 199.36 49.84 2.303142 0.103195
Residual 16.0 346.24 21.64 NaN NaN
檢驗的結論:
因素A的p值0.021886<0.05,拒絕原假設,說明飲料顏色對銷量有顯著影響;而因素B的p值0.103195>0.05,不能拒絕原假設,因此沒有充分的理由說明銷售地區對銷量有顯著影響。
然而,我們知道了顏色對銷量有顯著影響,那麼是哪種顏色呢?
使用tukey方法對顏色進行多重比較
from statsmodels.stats.multicomp import pairwise_tukeyhsd
print(pairwise_tukeyhsd(df['c'], df['a']))
Multiple Comparison of Means - Tukey HSD,FWER=0.05
==============================================
group1 group2 meandiff lower upper reject
----------------------------------------------
1 2 -9.2 -19.0855 0.6855 False
1 3 -5.2 -15.0855 4.6855 False
1 4 -8.4 -18.2855 1.4855 False
1 5 -10.0 -19.8855 -0.1145 True
2 3 4.0 -5.8855 13.8855 False
2 4 0.8 -9.0855 10.6855 False
2 5 -0.8 -10.6855 9.0855 False
3 4 -3.2 -13.0855 6.6855 False
3 5 -4.8 -14.6855 5.0855 False
4 5 -1.6 -11.4855 8.2855 False
----------------------------------------------
結果說明:1和5的reject=True,說明這兩種顏色有顯著性差異