介紹
Kruskal –Wallis秩檢驗(yàn)、或秩上的單向方差分析,是一種非參數(shù)方法(ANOVA),用于檢驗(yàn)樣本是否來自相同的分布。
簡而言之,當(dāng)我們繪制分布圖(如箱線圖)時(shí),如下圖,有沒有定量的把握確定1和3有顯著的組間差異?

Kruskal-Wallis 檢驗(yàn)用于回答該問題,回答組間的分布是否有顯著性差異。
原理
而Kruskal-Wallis 單因素方差分析原理也很簡單:先把多個(gè)完全隨機(jī)設(shè)計(jì)的樣本混合起來求秩,再按樣本組求秩和,考慮到各個(gè)處理的觀測值可能不同,可以比較各個(gè)處理之間的平均秩差異,從而達(dá)到比較的目的。
在計(jì)算所有數(shù)據(jù)混合樣本秩時(shí),如果遇到有相同的觀測值,則用秩平均法定秩。Kruskal-Wallis 方法也稱 H 檢驗(yàn),檢驗(yàn)方法的基本前提是數(shù)據(jù)的分布是連續(xù)的,除位置參數(shù)不同以外,分布是相似的。
求解步驟
其中:
- N是所有組的觀察總數(shù)
- g是組數(shù)
- ni是組中的觀察數(shù)i
- rij是觀察的等級
- 下式是組中所有觀測值的平均排名
- 下式是所有rij的平均值
如果數(shù)據(jù)不包含關(guān)系,則表達(dá)式H可以寫作:
最后,通過比較做出是否拒絕原假設(shè)的決定。
實(shí)現(xiàn)方法
使用python scipy的統(tǒng)計(jì)檢驗(yàn)?zāi)K:
實(shí)例1
# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
df = sns.load_dataset('iris')
# Usual boxplot
ax = sns.boxplot(x='species', y='sepal_length', data=df)
# Add jitter with the swarmplot function
ax = sns.swarmplot(x='species', y='sepal_length', data=df, color="grey")
plt.show()

考慮組2和組3是否有明顯的差異:
import scipy.stats as stats
stats.kruskal(df[df['species'] == 'versicolor']['sepal_length'], df[df['species'] == 'virginica']['sepal_length'])
結(jié)果為:
KruskalResult(statistic=24.98930909528678, pvalue=5.764908716512588e-07)
p<0.05認(rèn)為組2和組3有明顯差異
實(shí)例2
import pandas as pd
tips = pd.read_csv('./python/seaborn-data-master/tips.csv')
sns.catplot(data=tips, kind="swarm", x="day", y="total_bill", hue="smoker")

考慮組“Sun”和組“Sat”是否具有明顯差異?
直觀上來看,是沒有差異的,用KW檢驗(yàn)嘗試:
stats.kruskal(tips[tips['day'] == 'Sun']['total_bill'], tips[tips['day'] == 'Sat']['total_bill'])
結(jié)果為
KruskalResult(statistic=0.8460558571594718, pvalue=0.357670516500295)
p > 0.05認(rèn)為組“Sun”和組“Sat”沒有明顯差異
參考:
[1] https://en.wikipedia.org/wiki/Kruskal%E2%80%93Wallis_one-way_analysis_of_variance
[2] Kruskal, W. H., & Wallis, W. A. (1952). USE OF RANKS IN ONE-CRITERION VARIANCE ANALYSIS. Journal of the American Statistical Association, 47(260), 583-621. https://doi.org/10.1080/01621459.1952.10483441
本文由mdnice多平臺發(fā)布