본문 바로가기
쫌쫌따리 통계+데이터+AI

Data Imbalance 이슈 해결 : 언더샘플링 & 오버샘플링

by stherhj 2022. 3. 20.

비정형 데이터 공부하기 넘 싫어서 진짜 한글 문서 분석이 나오나 하고 찾아보다가 작년 20~23회차 기출문제에 빠진 것을 보고! 때려치다가..맨날 오버피팅 이슈만 해결했지 언더..오버..샘플링이라는 생소하면 안되는데 생소한 기출문제가 있길래 늦었지만 공부~.~

 

데이터 불균형을 해소하기 위한 두 기법: Under-sampling & Over-sampling 

(석사 플젝 때 ㄷㄹㅇㅌ에서 계속 데이터 불균형 이슈 해결을 위한 샘플링 기법에 대해 고민해본 적 있는지 여러번 질문 받았었는데 그 때마다 관련 논문에서 데이터 변형 없이 진행해도 ㄱㅊㄱㅊ해서 이케 했다라는걸로 맨날 돌려 막았던 기억이 난다. 다시 생각해보면 이러이러한 기법들이 있지만 그럼에도 ~~한 이유로 데이터를 변형없이 활용하기로 했다. 정도는 답했어야하는데ㅠ_ㅠ)

Under-sampling Over-sampling
(장) 계산 시간 감소, class overlap 감소 (장) 정보 손실 X, 언더샘플링 대비 분류 정확도 향상
(단) 정보 손실 발생 (단) overfitting, 계산 시간 증가, noise & outlier에 민감

 

Under-sampling

1. 랜덤 언더 샘플링(RUS) : majority class의 x 무작위로 샘플링. 수행할 때마다 다른 결과(다른 샘플, 다른 성능) 도출

caret::upSample(
  x, y  # 데이터
)
#반환 값은 업 샘플링된 결과

caret::downSample(
  x, y  # 데이터
)
#반환 값은 다운 샘플링된 결과
install.packages("ROSE")
library(ROSE)
# over sampling
data_balanced_over <- ovun.sample(cls~., data = hacide.train, method = "over", N=1960)$data
# N refers to number of observations in the resulting balanced set.

# under sampling
data_balanced_under <- ovun.sample(cls~., data = hacide.train, method = "under", N=40)$data

# under and over smapling (both)
# the minority class is oversampled with replacement and majority class is undersampled without replacement
data_balanced_both <- ovun.sample(cls ~ ., data = hacide.train, method = "both", p=0.5, N=1000, seed = 1)$data
table(data_balanced_both$cls)

data.rose <- ROSE(cls ~ ., data = hacide.train, seed = 1)$data
table(data.rose$cls)


출처: https://goodtogreate.tistory.com/entry/Handling-Class-Imbalance-with-R-and-Caret-An-introduction [GOOD to GREAT]


2. Tomek Links : 서로 다른 클래스 데이터 두 점을 연결하고 주변의 다른 임의 데이터 k. 두 점 연결한 거리 < 각각 k와 연결한 거리 -> 두 점의 연결 거리 '토멕링크'. 토멕링크로 연결된 점 중 majority class 속한 x 삭제


3. CNN(Convolution Neural Network 대신 Condensed Nearest Neighbor 크크) : minority class 전체와 majority class 중 하나로 구성된 sub-데이터 구성. 해당 sub-데이터 외 나머지 데이터(즉, majority 데이터 - 1) ~ sub-데이터의 majority 1개 or minority 중 아무거나 중 어느 쪽에 더 가까운가. 후자에 속하는 경우 minority로 구분하고, 전자의 데이터를 언더 샘플링(1-NN을 통해) 


4. OSS(One-side Selection) : Tomek links 와 CNN을 같이 수행. (경계에 존재하는 데이터를 언더샘플링하고 동시에 CNN으로 obvious한 데이터를 언더샘플링)

 

Over-sampling

1. 랜덤 오버 샘플링(ROS) : minority 단순 복제하여 비율을 맞춤.(분포는 그대로, 가중치를 높게) issue: overfitting의 위험 존재


2. !주인공! SMOTE(Synthetic Minority Over-sampling Technique)  : minority class data로부터 새로운 데이터를 생성. 관측치 x의 가장 가까운 이웃 K개를 새로운 데이터로 생성

DMwR::SMOTE(
  form,  # 모델 포뮬러
  data,  # 포뮬러를 적용할 데이터
  perc.over=200,  # 적은 쪽의 데이터를 얼마나 추가로 샘플링해야 하는지
  k=5,            # 고려할 최근접 이웃의 수
  # 적은 쪽의 데이터를 추가로 샘플링할 때 각 샘플에 대응해서 많은 쪽의 데이터를
  # 얼마나 샘플링할지 지정
  perc.under=200
)
##perc.over는 보통 100 이상으로. 적은 쪽의 데이터 한 개당 perc.over/100개의 추가 데이터가 생성.
##perc.under는 majority 중 얼마만큼의 비율을 샘플링할 것인지. 이 비율은 perc.over에 의해 추가로 생성된 데이터와 비례.
##예: perc.over에 의해 200개의 추가 데이터가 minority에 추가로 생성되었고, perc.over가 100 - majority로부터도 200개의 데이터가 취해짐.
data(iris)
data <- iris[, c(1, 2, 5)]
data$Species <- factor(ifelse(data$Species == "setosa","rare","common"))
newData <- SMOTE(Species ~ ., data, perc.over = 600, perc.under=100)


3. BSMOTE(Borderline-SMOTE) : majority | minority 그 경계선 가까이에 있는 minority에 대해 SMOTE 적용. X 근접 K개의 class 수에 따라 Danger, Safe, Noise로 구분 (Noise: 근접 K 모두 majority면 noise, Safe: 절반 이상 minor면 이미 적당히 minor 분포, Danger: 절반 이상이 majority이면 SMOTE 적용) 완전히 고립된(noise) 데이터를 제외하고 수적 열세에 놓인(danger) minority 데이터를 도와줌!


4. ADASYN(Adaptive Synthetic Sampling) : 가중치를 통해 SMOTE 적용. 인근 K개의 X의 majority의 비율 * G(major-minor) = 각 X에 대해 생성할 샘플의 수

-

https://www.youtube.com/watch?v=Vhwz228VrIk&list=PLpIPLT0Pf7IoTxTCi2MEQ94MZnHaxrP0j&index=8 

https://techblog-history-younghunjo1.tistory.com/123

'쫌쫌따리 통계+데이터+AI' 카테고리의 다른 글

비모수적 검정 방법  (0) 2022.03.20
데이터 처리 속도 측정 (코드 수행 시간 측정)  (0) 2022.03.20
선형회귀  (0) 2022.03.12
통계학습  (0) 2022.03.12
잔차분석  (0) 2022.03.11

댓글