DL&ML/code.data.tips

Weighted Cross Entropy

식피두 2021. 4. 6. 00:02

클래스 불균형이 심한 경우에서

분류 문제를 풀 때

 

Cross Entropy로 최적화 한다면,

weight 인자에 클래스별 가중치를 전달하여 데이터 비율에 맞게 학습되는 정도를 조정해서

좀 더 균형잡힌 학습을 할 수 있다.

 

CrossEntropyLoss — PyTorch 1.8.1 documentation

Shortcuts

pytorch.org

실제 사용 방법은 아래와 같이 (7개 클래스 가정)

학습 데이터 별 통계를 이용해 weights을 구하고,

CrossEntropyLoss의 첫째 인자로 전달해주면 된다.

 

빈도수가 높을 수록 특정 클래스의 weight은 작아지게 된다.

nSamples = [887, 6130, 480, 317, 972, 101, 128]
normedWeights = [1 - (x / sum(nSamples)) for x in nSamples]
normedWeights = torch.FloatTensor(normedWeights).to(device)

loss = nn.CrossEntropyLoss(normedWeights)
 

Weights in weighted loss (nn.CrossEntropyLoss)

Hello, I do not know what you mean by reverser order, but I think it is better if you normalize the weights proportionnally to the reverse of the initial weights (so the more examples you have in the training data, the smaller the weight you have in the lo

discuss.pytorch.org