Skip to main content
 首页 » 编程设计

使用R语言boxplot.stats函数进行异常检测

2022年07月19日133shihaiming

异常值一般指数据远离大多数观察值。有很多种方式进行异常值检测,如基于变量空间距离度量,把距离太远的观察值标记为异常值。还有基于数据分布的检测方法,本文利用boxplot.stats函数来解释基于分布的异常检测方法,并利用ggplot图视表示。

boxplot.stats函数原理

该检测方法先假定数据的预期分布,把背离这种分布的数值标记为异常值。

首先计算数据集的四分位数据Q1、Q3,利用公示计算四分位距:IQR=Q3-Q1 ;
然后就能计算两边的异常值(或离群值):

  • 上须值:Q3+1.5*IQR
  • 下须值:Q1-1.5*IQR

识别异常值就是计算大于上须值或小于下须值的数据。

library(ggplot2) 
library(tibble) 
 
set.seed(222) 
 
m <- as_tibble(rnorm(100)) %>% mutate(id=row_number(), .before="value") 
head(m, 10) 
#     id    value 
# <int>    <dbl> 
#     1  1.49    
#     2 -0.00189 
#     3  1.38    
#     4 -0.380   
#     5  0.184   
#     6 -0.247   
#     7 -1.22    
#     8  1.56    
#     9  0.427   
#    10 -1.20  
 
st <- boxplot.stats(m$value) 
out_points <- filter(m, m$value %in% st$out) 
out_points 
 
#      id value 
#   <int> <dbl> 
# 1    70 -2.77 
# 2    74 -2.53 
 
# 首先画原始数据,然后再用红色画出离群值 
ggplot(m, aes(x=id, y=value)) + geom_point() + 
  geom_point(data = out_points, aes(x=id, y=value, color ="red")) 
 
ggplot(m, aes(y=value)) + geom_boxplot() + 
  ggtitle("箱线图展示") 
在这里插入图片描述
在这里插入图片描述

本文参考链接:https://blog.csdn.net/neweastsun/article/details/121855450
阅读延展