불균형 데이터란?
불균형 데이터는 클래스(범주)별 관측치의 수가 현저하게 차이가 나는 데이터이다. 즉 정상 범주의 관측치 수와 이상 범주의 관측치 수의 차이가 크게 나타나는 경우를 말한다. 예를 들어 암환자를 분류하는 문제로 생각해봤을때 암에 걸린 사람보다는 암에 걸리지 않은 사람이 더 많기 때문에 암환자로부터 얻어진 샘플이 그렇지 않은 경우의 샘플보다 훨씬 적을 수 있다. 데이터 불균형 문제를 해결하지 않고 학습하게 되면 분류기는 정상인의 샘플에 더 많은 가중치를 두고 학습할 것이고, 아래의 그림과 같이 분류 경계면에 Bias가 존재하게 되어 암환자를 정상인으로 잘못 분류할 수 있게 된다.
또 다른 예시로는 제조업의 정상제품과 불량품 구분하는 경우와 금융범죄에서의 이상 거래(사기) 경우가 정상 거래인 경우보다 현전히 적은 경우 등등 현실세계에서 우리가 볼 수 있는 데이터들은 균형 잡힌 데이터보다는 불균형 된 데이터가 훨씬 많은 경우가 많다.
불균형 데이터의 문제점
우리는 정상(다수)을 정확히 분류하는것도 중요하고 이상(소수)을 정확히 분류하는것도 중요하다. 하지만 일반적으로 이상을 정확히 분류 하는 것이 중요할것이다. 왜? 예를들어 건강한 사람을 암환자로 잘못 진료하는것 보다 암환자를 건강한 사람으로 잘못 진료하는것이 더 큰 문제가 될 것이다. 제조업에서는 정상제품을 불량품으로 잘못 판단하는것 보다 불량품을 정상제품으로 판단하여 고객에게 불량품을 전달해주는것이 더 큰 문제가 될 것이고 금융업에서는 정상 거래를 사기 거래로 잘못 판단하는것 보다 사기 거래를 정상 거래로 판단하는것이 더 큰 문제가 될것이다.(물론 양쪽 모두 중요하다.)
문제점을 모델링 관점에서 아래 그림을 보며 다시 한번 말하자면 파란색은 정상 데이터, 빨간색은 이상 데이터, 회색은 아직 관측은 되지 않았지만 미래에 이상 데이터가 발생했을때를 생각한 데이터라고 했을때 우리가 생각한 이상적인 분류 경계선은 왼쪽그림과 같겠지만 정상 관측치가 이상 관측치보다 많기 때문에 실제 분류 경계선은 오른쪽 그림과 같이 정상 관측치에 편향된 분류 경계선이 된다. 그러면 우리가 미래의 이상데이터 나타났을 때 주황색으로 변하는 이러한 데이터들은 실제 이상데이터임에도 불구하고 분류 경계선에 의하여 정상으로 오분류를 하여 이상을 정확히 찾아내지 못하는 문제가 발생하는것이다.
잘못된 평가
보통 분류 모델을 평가할 때 Confusion Matrix를 기반으로 Accuracy(정확도), Precision(정밀도), Recall(재현율), F1 Score를 많이 쓰게 된다. Confusion Matrix는 모델이 맞췄을 때 T, 모델이 틀렸을 때 F, 모델이 예측한게 Ture면 P, 모델이 예측한게 False면 N으로 표현한다.
Accuracy은 모델이 전체 문제(TP+FN+FP+TN) 중에서 정답(TP,TN)을 맞춘 비율이다. Accuracy를 사용하여 아래 그림처럼 구성된 Confusion Matrix를 근거로 Accuracy를 계산하면 92%가 나온다. 비록 모델의 정확도가 92%로써 굉장히 높지만 암환자만 떼어 놓고 보면 암환자가 9명(2+7) 존재하는데 2명만 암환자로 예측했다. 이렇게 모델의 Accuracy는 높지만 정작 모델의 관심범주는 절반도 예측하지 못했다. 이런 이유 때문에 데이터가 불균형할 때는 Accuracy만으로 제대로 분류했는지 알 수 없기 때문에 Recall과 Precision을 사용한다.
해결 방안
불균형 데이터 해결 방안은 크게 두 가지이다. 첫 번째는 데이터를 조정해서 해결하는 방법과 두 번째는 분류 모델 자체를 조정해서 해결하는 방법이 있다. 데이터를 조정해서 해결하는 방법은 샘플링 기법을 사용하는것이고 모델을 조정해서 해결하는 방법은 비용 기반 학습과 단일 클래스 분류기법이 존재한다. 여기서는 데이터를 조정해서 해결하는 방법 즉 샘플링 기법에 대해서 집중적으로 알아보도록 하자.
샘플링 기법은 크게 두 가지로 나뉜다. 언더 샘플링과 오버 샘플링, 언더 샘플링은 다수 범주를 줄여가지고 소수 범주의 개수와 비슷하게 만들자라는 것이 언더 샘플링이고 오버 샘플링은 반대로 소수 범주에 있는 관측치를 증폭시켜 다수 범주에 있는 관측치의 개수랑 비슷하게 만든 다음에 분류를 하자라는 것이 오버 샘플링이다.
Random undersampling(언더 샘플링)
언더 샘플링의 첫 번째 방법으로 Random Undersampling 방법이 있다. 이름처럼 정상 다수 범주에 있는 것을 랜덤하게 샘플링해서 버리는 것이다. 아래 그림의 회색으로 표현한 부분을 랜덤 샘플링 해서 버리고 나머지에 있는 것만 가지고 모델을 만들자 라는것이다. 랜덤 언더 샘플링은 다수 범주에서 무작위로 샘플링을 하기 때문에 할 때마다 분류 경계선이 다르게 나온다. 그래서 랜덤 언더샘플링은 어떻게 보면 굉장히 쉬운 방법이고 생각보다 성능이 잘 나오지만 샘플링 할 때마다 성능이 달라질 수 있기 때문에 단점으로 작용할 수가 있다.
Tomek links(언더 샘플링)
Tomek links는 두 범주 사이를 탐지하고 정리를 통해 부정확한 분류경계선을 방지한다. 정의로는 d(xi,xk) < d(xi,xj) 또는 d(xj,xk) < d(xi,xj)가 되는 관측치 xk가 없는 경우, 두 샘플 xi와 xj가 Tomek Link를 형성한다고 한다.
위의 좌측 그림은 Tomek link가 아니다. 왜냐하면 i번째 점과 j번째 점을 연결을 했는데 그 사이에 점 k가 존재하기 때문이다. 그러면 Tomek link는 무엇일까? Tomek link는 우측 그림처럼 각 점과 k점이 연결됐을 때 i와 j를 연결한 것보다 거리가 작은, 즉 중간에 있는 점이 없을 때 그 두 점을 연결한 것을 Tomek link라고 한다.
위의 그림은 Tomek link의 예제를 보여준다. 좌측 그림에서 Tomek Link를 형성한 파란색 샘플들을 제외하면 우측 그림과 같이 되는데 샘플을 제외하기 이전보다 두 범주의 구분이 보다 명확히 됨을 알 수 있다. 따라서 두 범주간의 분류 경계면을 찾는데 도움이 된다. Tomek link는 다수 범주의 데이터의 중심 분포는 거의 유지하면서 분류 경계를 조정하는 효과를 얻기 때문에 Random undersampling에 비해 정보의 유실을 크게 줄일 수 있지만 제거되는 샘플이 한정적이기 때문에 큰 언더 샘플링 효과를 얻을 수는 없다.
Condensed Nearest Neighbor(언더샘플링)
Condensed Nearest Neighbor 방법은 줄여서 CNN이라고도 한다. CNN방법은 소수 범주 전체와 다수 범주에서 무작위로 하나의 관측치를 선택하여 서브데이터를 구성한다. 그런 다음에 나머지 점들인 회색으로 표현한 다수 범주들을 1-Nearest Neighbor 알고리즘을 통해서 분류를 한다. 1-Nearest Neighbor란 어떤 점이 있으면 거리를 계산해서 범주로 분류하는것이다. 아래 3번 그림에서는 이상 범주에 더 가까웠으니 빨간색 이상 범주로 분류를 하는 것이다. 이런 식으로 4번 그림의 빨간 타원 부분은 전부 이상으로 분류가 된다. 그 다음에 6번 그림처럼 정상 분류된 다수 범주의 관측치를 제거를 한다. 즉 파란색으로 분류된 것들을 다 제거한다는 것이고 나머지 6번 그림의 보라색 점을 가지고 분류를 하는것이다.
그러면 샘플링 이전에는 분류 경계선이 다수 범주, 정상에 치중된 그런 경계선이 되었다면 CNN 기법을 이용을 하면 이렇게 회색으로 표현된 부분이 다 언더 샘플링 됐기 때문에 이 분류 경계선이 왼쪽으로 이동한다.
CNN에서 하나 고려해야 것이 CNN은 1-Nearest Neighbor 알고리즘을 사용한다 라고 그랬는데 k-Nearest Neighbor로 즉 k를 1로 하지 않고 3이나 5 이런 다른 숫자로는 할 수 없다. CNN에서는 무조건 k-Nearest Neighbor을 사용한다. 왜냐하면 예를들어 k를 3이라고 가정해서 해본다면 1번 그림의 초록색 관측지와 가장 가까운 3개의 점을 고를 것이다. 그러면 이 3개의 점 중에서는 빨간색이 2개고 파란색이 1개 이기 때문에 빨간색으로 변화한다. 2번 그림에서 초록색도 3번 그림에서 초록색도 k를 3으로 하면 무조건 다수 범주는 이상이 된다. 그래서 4번 그림처럼 모든 정상이 다 빨간색으로 변하게 되는 것이고 모든 다수 클래스가 다 이상으로 분류되어 있기 때문에 언더 샘플링 할 게 없는 것이다. 그래서 CNN은 알고리즘은 반드시 1-Nearest Neighbor을 사용해야지 알고리즘의 원래 의미가 충족이 된다 라고 생각하면 된다.
One-Sided Selection(언더 샘플링)
One-Sided Selection 방법은 짧게 OSS 라고 얘기한다. OSS는 Tomek link와 CNN을 그냥 합친 것이다.즉 Tomek link에서 언더 샘플링된 거와 CNN에서 언더 샘플링 된 거를 합쳐가지고 다운 샘플링 하는 것이다. 아래 좌측 그림을 보면 Tomek link와 CNN을 적용한 보라색으로 칠해진 부분이 언더 샘플링 돼서 없어질 것이다. 토맥 링크는 border 라인만 지워지는 것이고 CNN은 border 라인이 아닌 완전한 정상만 지워지는데 이러한 장단점을 서로 보완한 방법이 OSS라고 보면 된다.
OSS도 마찬가지로 샘플링 이전 때는 파란색 정상에 좀 편향된 그런 분류 경계선이 만들어진다면 OSS를 적용한 이후에는 분류 경계선이 왼쪽으로 와서 이상을 제대로 분류를 하는것을 아래 그림에서 확인할 수 있다.
언더 샘플링 장/단점
언더 샘플링 장점으로는 다수 범주 관측치 제거로 계산 시간이 감소하고 데이터 클랜징으로 클래스 오버랩이 감소된다. 결국 장점은 데이터가 언더 샘플링을 지우는 것이기 때문에 불필요한 데이터가 잘 날아갈 수가 있고 데이터 자체가 작아지기 때문에 계산 복잡도라든지 시간상에서 효율이 좋아지는 것이다. 하지만 단점으로는 데이터를 제거했다는 것은 그만큼 정보를 손실했다는 것이기 때문에 우리가 불필요한 것을 제대로 지웠다면 별 문제가 생기지 않겠지만 필요한 정보까지 지울 수가 있는 것이다. 그래서 필요한 정보를 지웠을 때는 치명적인 문제가 발생할 수도 있는 것이 언더 샘플링이다.
Resampling(오버 샘플링)
오버 샘플링의 첫 번째 방법은 Resampling이다. 오버 샘플링이란 소수 범주를 증폭하는 것인데 Resampling은 소수 범주의 관측치를 단순히 증폭시키는 것이다. 아래 그림에서 보듯이 새로운 데이터를 생성하는 게 아니라 소수 범주를 그대로 카피해서 균형을 맞추는 굉장히 단순한 방법이다.
아래 좌측 그림을 보면 정상이 굉장히 많기 때문에 정상에 편향된 분류 경계선이 생길 것이다. 오버 샘플링을 한다는 거는 증폭시킨다는 것이고 Resampling은 소수 범주를 계속 카피해서 정상 데이터 즉 다수 데이터의 개수와 비슷하게 하는 건데 소스 클래스의 관측치를 복제를 하면 점들 위에 동일한 데이터가 계속 찍힐것이다. 그러면 실제 경계선이 이상에 가까운 분류 경계선 쪽으로 이동하는것이다. 단순히 데이터를 카피해서 늘리는 건데 큰 도움이 있을까 할 수 있지만 의외로 잘 작동할 때가 많이 존재한다. 하지만 소수 클래스를 증폭 시켰기 때문에 소스 클래스에 과적합이 발생할 가능성이 생기는 단점이 존재한다.
SMOTE(오버 샘플링)
이제 앞서 말한 소수 클래스에 과적합이 발생하는 것을 보완할 수 있는 방법론들을 설명하겠다.
첫 번째는 SMOTE(Synthetic Minority OverSampling Technique)이다. 현재까지는 소수 범주에서 단순히 존재하는 데이터들을 복제했다면 그러지 말고 소수 범주에서 가상의 데이터를 생성하자라는 것이다. 우선 소수 범주에서 가상 데이터를 생성하려면 일단 k를 정해야 한다. k를 5라고 가정한다면 소수 범주에서 임의로 데이터를 하나 선정하고 임의로 선정한 것과 가장 가까운 5개의 소수 범주를 정한다.(k는 Nearest Neighbor라고 보면 된다.) 그 다음에 가장 가까운 5개 중 랜덤하게 하나를 선택한다.
그리고 선택된 두 관측치에 대해 아래의 식을 통해 가상의 관측치 데이터를 생성한다. X는 소수 범주에서 임의로 선택한 것이고 X(nn)은 Nearest Neighbor 관측치, 즉 전에 k가 5개의 Nearest Neighbor 관측치가 선택되는 것 중에 무작위로 하나 선택한 데이터이다. u는 0과 1 사이에 있는 값이 랜덤하게 나오는 값인 균등 분포이다.
가상의 관측치 데이터를 생성하는 예를 들어보자, 소수 범주에서 무작위로 하나 선택한 X가 (5,1)로 선정이 되어있다. 그 다음에 k는 5라고 가정해서 5개 중 하나 선택한 것이 X(nn)이고 좌표는 (2,3)이다. 수식에 값을 대입해 계산해보면 X(nn)과 X가 이루는 선 사이에 (5,1)이라는 점에서부터 이동시킨 데이터(초록색)가 생성될 것이다.
이제 소수 범주 내 모든 관측치에 대해서 위의 과정을 반복하고 가상관측치를 생성한다. 결국 소수 범주의 데이터가 증폭이 되면서 오버 샘플링이 된 것이다.
참고로 k는 1로 하면 안 되고 반드시 2 이상으로 설정해야 한다. 왜냐하면 k를 5로 설정했을 때는 가장 가까운 5개를 고른 후 그 중 랜덤하게 하나를 선택했지만 k를 1로 하면 가장 가까운 것은 반드시 하나고 아래 좌측 그림과 같이 계속 선 사이에 데이터가 생성되는 것이다. 아래 우측 그림은 실제로 데이터를 생성한 것이다. 빨간색의 소수 범주 주변에 예쁜 모양으로 생기는 것이 아니라 쭉 길게 늘어선 모양으로 생기는 것이다. 물론 오버 샘플링은 됐지만 이렇게 생기면 데이터의 형태에 맞지 않게 생성이 되는 문제점이 발생한다.
Borderline - SMOTE(오버 샘플링)
두 번째 방법은 SMOTE에 대한 개선 된 버전중 하나가 Borderline-SMOTE 이다. Borderline-SMOTE란 정상 데이터와 이상 데이터의 경계 부분에 오버 샘플링을 하는것이다. 기존 SMOTE 방법에서는 경계선 주변에 데이터가 생성되는 것이 아니라 기존 이상 데이터 주변으로 데이터가 생성된다. 그래서 분류 모델이 더 잘 분리할 수 있도록 기존 이상 데이터 주변이 아닌 경계선 주변에 데이터를 생성해주는 방법이 Borderline-SMOTE 방법이다.
Borderline-SMOTE의 원리는 우선 Borderline을 찾는다. Borderline은 컴퓨터는 어디인지 알 수 없기 때문에 어디가 Borderline이라는 것을 정해줘야 된다. Borderline을 찾는 기준은 소수 클래스 xi에 대해서 k개 주변을 탐색하고 k개 중 다수 클래스 수를 확인한다. 다수 클래스의 수를 m이라고 할 때 아래와 같이 3가지 타입의 관측치로 분류하여 Borderline을 정한다.
k = m :Noise 관측치(Borderline X)
k/2 < m < k : Danger 관측치(Borderline O)
0 ≤ m ≤ k/2 : Safe 관측치(Borderline X)
예를들어 아래의 좌측 그림에서 소수 클래스 중에 하나를 선택을 하고 그 다음 k가 5인 경우로 가정했을때 5개의 주변을 탐색을 한다. 그 다음에 이 5개중에서 다수 클래스의 개수가 몇 개인지 확인하면되는데 아래 그림에서는 다수 클래스가 하나도 포함되어있지 않다. 즉 소수 클래스의 주변에 있는 게 모두 소수 클래스이기 때문에 이것들은 Borderline이 아닌 Safe 관측치라고 부른다. 가운데 그림에서는 주변 5개 중에서 다수가 3개 있다. 이것은 Danger 관측치라고 부르고 이것은Borderline이다. 우측그림은 주변 5개 중 5개 모두 다수이다. 이것은 Noise 관측치라고 부른다.
정리하면 Danger 관측치에 대해서만 SMOTE를 적용하는것이다. 원래 SMOTE는 모든 소수 관측치에 대해서 다 적용한다라고 했지만 Borderline-SMOTE는 Borderline에 있는 것 즉 Danger 관측치에 대해서만 SMOTE를 적용하여 이상 데이터를 증가시켜 경계선의 위치에만 데이터가 샘플링되는 효과를 얻을 수 있는것이다.
ADASYN : Adaptive Synthetic Sampling Approach(오버 샘플링)
마지막 기법은 ADASYN이다. 이것은 Borderline과 비슷한데 샘플링하는 개수를 위치에 따라서 다르게 하자라는 것이다. 위치에 따라 다르게 하기 위해서 먼저 r이라는 값을 정의해야하는데 r은 아래 그림과 같다.
결국 각 소수 클래스 주변에 얼마큼 많은 다수 클래스 관측치가 있는가를 정량화 한 지표인것이다. 아래의 그림은 3가지 경우를 든 예시이다. 먼저 모든 소수 클래스에 대해 주변을 k개만큼 탐색하고 그 중 다수 클래스 관측치의 비율(r)을 계산한다.
이런식으로 모든 소수 관측치에 대해서 r을 계산해 보면 아래 그림과 같다.
그 후 계산한 r값을 스케일링 한다. 이 r값들을 모두 더한 다음 그 더한 값으로 나눠준다.
스케일링 했던 것을 가지고 이제 각 소수 클래스 부분에 데이터를 오버 샘플링 해야 되는데 몇 개를 증폭시킬지 정하기 위해서 먼저 G를 정의한다 G는 보통 다수 클래스의 개수와 소수 클래스 개수의 차이다 이 예제에서 100이라고 가정하였다. 그 후 스케일링 한 r값에 G를 곱한다. 예를들어 0.1428은 100을 곱하여 14.28이 된것이다.(소수 첫째자리에서 반올림 해야함) 그래서 괄호 안에 있는 계산된 개수만큼 각 소수 클래스에 위치에 맞게 SMOTE를 적용하여 오버샘플링 하는것이다.
GAN : Generative Adversairal Nets(오버 샘플링)
GAN을 이용한 오버 샘플링에 대한 연구도 최근에 활발하게 이루어지고 있다. GAN의 작동방식은 무작위로 노이즈를 생성한다. 그 후 첫 번째 네트워크인 Generator에 아무런 패턴이 없는 데이터를 이용하여 가짜 샘플을 생성한다. 이 가짜 샘플은 랜덤한 이상한 데이터가 들어왔기 때문에 이상한 데이터가 생성이 될 것이다. (여기서 하나의 가정은 진짜 샘플은 소수이지만 존재한다 라는 가정이다.) 그 후 가짜 샘플과 진짜 샘플을 두 번째 네트워크인 Discriminator가 구별을 한다. 즉Classification을 한다. 진짜 돈의 이미지와 가짜 돈의 이미지를 Discriminator에 집어넣으면 이 두 개의 차이가 명확하기 때문에 구별을 굉장히 잘 하여 Classification Error가 거의 0이 될 것이다. Classification Error가 0이 되면 두 번째 네트워크가 첫 번째 네트워크에게 "야 너 똑바로 해. 내가 너무 잘하잖아. 네가 너무 쉽게 주니까 내가 너무 성능이 좋아서 좀 더 진짜 샘플과 비슷한 이미지를 생성해 봐" 이런식으로 반복적인 생성자 업데이트를 통해 진짜 샘플과 유사하게 데이터를 생성한다. 그래서 생성자와 구분자, 첫 번째 네트워크와 두 번째 네트워크는 서로 도와준다기보다는 서로 경쟁을 하면서 같이 발전하는 관계이기 때문에 이런 관계를 Adversarial, 적대적이라고 표현하는 것이다.
오버 샘플링 장/단점
오버 샘플링의 장점은 데이터를 버리는 게 아니기 때문에 정보 손실이 없고 대부분의 경우 언더 샘플링에 비해 높은 분류 정확도를 보인다. 하지만 단점은 과적합이 있을 수가 있고 또 데이터가 많아지기 때문에 계산 시간이 증가할 수 있다. 또 노이즈나 예상치에 민감하다.
참고 자료
[1] 고려대학교 김성범 교수님의 Youtube강의 [핵심 머신러닝] 불균형 데이터 분석을 위한 샘플링 기법
'🤖 AI > Machine Learning' 카테고리의 다른 글
Dicision Tree(의사결정나무) (1) | 2024.08.06 |
---|