[ Python ] class weight 쉽게 구하는 법

2019. 11. 24. 16:50분석 Python/Scikit Learn (싸이킷런)

728x90

도움이 되셨다면, 광고 한번만 눌러주세요.  블로그 관리에 큰 힘이 됩니다 ^^

기존에 내가 하던 방식은 일일히 계산을 하였지만, 역시 찾아보면 다 있는 것 같다.

from sklearn.utils.class_weight import compute_class_weight
label = [0] * 100 + [1] * 50 + [2] * 5
compute_class_weight(class_weight = "balanced" , 
                     classes=np.unique(label), 
                     y = label)

보통 이걸 쓰는 이유는 class 의 imbalance할 때 class에 따른 가중치를 부여하고 싶을 때 사용한다.

from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(class_weight={0:1,1:10})

class weight 가 {0:1 , 1 :20}

 

이와 같이 imbalance 할 경우에 가중치를 부여할 수 있는데, 저런 식으로 Loss를 하게 되면 학습시 우리가 원하는 타겟에 대해서 못맞출 경우 더 가중치를 줄 수 있다는 장점이 있다.

이런식의 Loss가 필요한 이유는 그냥 Loss를 쓰다면 일반화가 더 쉽게 되서 대다수의 클래스만 맞추게 된다.
그래서 적은 클래스에 대해서 학습하길 원할 때 사용한다.

이러한 Loss 중에서 요즘 나온 것은 내가 알기로는 Focal Loss도 있고, 아래 글에도 관련 코드가 있으니 참고하길 바란다.

>> tensorflow에서는 다음과 같이 사용하니 아래 글 참고

https://data-newbie.tistory.com/325 

 

[ Tensorflow ] Binary, MutliClass Loss

코딩을 하다 보니 Loss를 사용하는 데 있어서 헷갈리는 부분이 있어서 따로 정리를 하고 싶어 짐! 코드는 주로 사용하는 Tensorflow 1.4 위주로... Tensorflow 2.0 은 추후에... Binary CrossEntropy & Weight Cr..

data-newbie.tistory.com

 

 

https://towardsdatascience.com/the-5-most-useful-techniques-to-handle-imbalanced-datasets-6cdba096d55a

 

The 5 most useful Techniques to Handle Imbalanced datasets

If you haven’t yet encountered imbalanced datasets, you will

towardsdatascience.com

 

728x90