YOGYUI

R boxplot 함수로 이상치(outlier) 감지하기 본문

Software/R

R boxplot 함수로 이상치(outlier) 감지하기

요겨 2021. 6. 18. 21:20
반응형

 

탐색적 데이터 분석 (Exploratory Data Analysis, EDA) 단계에서 이상치(outlier) 감지를 위한 방법은 여러가지가 있다

  • 사분범위 (interquartile range, IQR) 
  • 백분위수 (percentile)
  • Hampel filter
  • Grubbs’s test
  • Dixon’s test
  • Rosner’s test

이 글에서는 직관적으로 이해하기 쉬운 방법 중 하나인 IQR Criterion 기법을 알아보도록 한다

 

1. 이론

다음 범위(Interval) $I$를 벗어나는 값을 이상치라고 정의한다

\(I=[Q_{1}-1.5\cdot IQR, Q_{3}+1.5\cdot IQR]\)

\(IQR = Q_{3}-Q_{1}\)

\(Q_{3}\): 중앙값 위 데이터들의 중앙값, 제 3사분위 수

\(Q_{1}\): 중앙값 아래 데이터들의 중앙값, 제 1사분위 수

 

2. 구현

Box plot (box & whisker plot)를 그리면 위 조건 (인터벌 \(I\))을 벗어나는 데이터는 작은 원으로 표기된다

iris 데이터를 예시로 들어보자

 

boxplot 함수로 4개 수치형 속성에 대한 상자 그림을 그릴 수 있다

boxplot(iris[1:4])

iris data boxplot

Sepal.Width에 4개의 이상치가 감지된 것을 볼 수 있다

summary(iris$Sepal.Width)
>
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.000   2.800   3.000   3.057   3.300   4.400 

\(Q_{1}\)은 2.8, \(Q_{3}\)는 3.3이므로 인터벌 \(I\)는 \([2.05, 4.05]\)가 된다

이상치에 해당하는 레코드는 다음과 같이 추출할 수 있다

iris[iris$Sepal.Width < 2.05 | iris$Sepal.Width > 4.05, ]
>
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
16          5.7         4.4          1.5         0.4     setosa
33          5.2         4.1          1.5         0.1     setosa
34          5.5         4.2          1.4         0.2     setosa
61          5.0         2.0          3.5         1.0 versicolor

 

위 구문은 boxplot 객체(객체의 class는 list)를 활용해서 수식을 계산하지 않고서도 구현할 수 있다

boxplot(iris$Sepal.Width)$out
> [1] 4.4 4.1 4.2 2.0

$out 구문을 사용하면 이상치에 해당하는 '값'들을 가져올 수 있다

이를 활용하면 다음과 같이 이상치에 해당하는 레코드를 추출할 수 있다

outtemp <- boxplot(iris$Sepal.Width)$out
iris[iris$Sepal.Width %in% outtemp, ]
>
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
16          5.7         4.4          1.5         0.4     setosa
33          5.2         4.1          1.5         0.1     setosa
34          5.5         4.2          1.4         0.2     setosa
61          5.0         2.0          3.5         1.0 versicolor

상당히 간단하다!

 

상자 그림을 이용한 (혹은 사분위수를 이용한) 이상치 탐색은 수식도 간단하고 이론도 직관적으로 이해하기 쉽다는 장점이 있다

 

시간이 되는대로 이상치 추출에 대한 여러 방법을 하나씩 포스팅해봐야겠다

 

[참고]

https://sosal.kr/945

https://statsandr.com/blog/outliers-detection-in-r/

https://www.journaldev.com/47986/outlier-analysis-in-r

https://blog.naver.com/PostView.nhn?blogId=sw4r&logNo=221021173204&parentCategoryNo=&categoryNo=117&viewDate=&isShowPopularPosts=true&from=search

https://ko.wikipedia.org/wiki/%EC%83%81%EC%9E%90_%EC%88%98%EC%97%BC_%EA%B7%B8%EB%A6%BC

반응형
Comments