数据间是否有明显差异?使用Kruskal–Wallis检验

介绍

Kruskal –Wallis秩检验、或秩上的单向方差分析,是一种非参数方法(ANOVA),用于检验样本是否来自相同的分布。

简而言之,当我们绘制分布图(如箱线图)时,如下图,有没有定量的把握确定1和3有显著的组间差异?

alt

Kruskal-Wallis 检验用于回答该问题,回答组间的分布是否有显著性差异。

原理

而Kruskal-Wallis 单因素方差分析原理也很简单:先把多个完全随机设计的样本混合起来求秩,再按样本组求秩和,考虑到各个处理的观测值可能不同,可以比较各个处理之间的平均秩差异,从而达到比较的目的。

在计算所有数据混合样本秩时,如果遇到有相同的观测值,则用秩平均法定秩。Kruskal-Wallis 方法也称 H 检验,检验方法的基本前提是数据的分布是连续的,除位置参数不同以外,分布是相似的。

求解步骤

其中:

  • N是所有组的观察总数
  • g是组数
  • ni是组中的观察数i
  • rij是观察的等级
  • 下式是组中所有观测值的平均排名
  • 下式是所有rij的平均值

如果数据不包含关系,则表达式H可以写作:

Misplaced & H & = \frac{12}{N(N+1)}\sum_{i=1}^g n_i \left(\bar{r}_{i\cdot} - \frac{N+1}{2}\right)^2 \\ & = \frac{12}{N(N+1)}\sum_{i=1}^g n_i \bar{r}_{i\cdot }^2 -\ 3(N+1)

最后,通过比较做出是否拒绝原假设的决定。

实现方法

使用python scipy的统计检验模块:

实例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()
image-20230320165208080
image-20230320165208080

考虑组2和组3是否有明显的差异:

import scipy.stats as stats
stats.kruskal(df[df['species'] == 'versicolor']['sepal_length'], df[df['species'] == 'virginica']['sepal_length'])

结果为:

KruskalResult(statistic=24.98930909528678, pvalue=5.764908716512588e-07)

p<0.05认为组2和组3有明显差异

实例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")
alt

考虑组“Sun”和组“Sat”是否具有明显差异?

直观上来看,是没有差异的,用KW检验尝试:

stats.kruskal(tips[tips['day'] == 'Sun']['total_bill'], tips[tips['day'] == 'Sat']['total_bill'])

结果为

KruskalResult(statistic=0.8460558571594718, pvalue=0.357670516500295)

p > 0.05认为组“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 多平台发布

猜你喜欢

转载自blog.csdn.net/wlh2067/article/details/129671682