[Keras] Weighted Cross Entropy 적용하는 방법

2020. 11. 21. 21:05분석 Python/Tensorflow

728x90

 

keras에서 weighted binary crossentropy를 적용할 때 방법을 공유하고자 한다.

바로 sklearn의 class_weight를 활용하는 것이다.

from sklearn.utils import class_weight
weights = class_weight.compute_class_weight('balanced',
                                            np.unique(train_y),
                                            train_y)
weights = {i : weights[i] for i in range(2)}
weights
## {0: 0.6254180602006689, 1: 2.493333333333333}

class_weight에 어떻게 보면 고정된 weight를 주는 방법이다.

더 나은 방법은 아마도 batch_size마다 weight를 계산해서 주는 방법이 있을 텐데, 그것은 다른 사람에게 맡기고 패스~

history = model.fit(train, 
                    train_y,
                    validation_data=(valid, valid_y),       
                    class_weight= weights,
                   )

 

 

 

https://stackoverflow.com/questions/61261907/on-colab-class-weight-is-causing-a-valueerror-the-truth-value-of-an-array-wit

 

on colab - class_weight is causing a ValueError: The truth value of an array with more than one element is ambiguous. Use a.any(

i'm running a CNN with keras sequential on google colab. i'm getting the following error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() w...

stackoverflow.com

 

728x90