Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

uos-machine-learning

Keras Custom Loss 만들기 본문

딥러닝

Keras Custom Loss 만들기

이산한하루 2019. 5. 9. 23:56

Keras는 다양한 손실함수를 제공한다. 사용하는 방법도 간단하다.

from keras import losses

model.compile(loss=losses.mean_squared_error, optimizer='sgd')

하지만 딥러닝 관련 여러 프로젝트를 진행하다보면 Custom loss를 만들고 싶은 욕심이 생긴다. 

예를 들어 segmentation에서 dice-coef를 손실함수로 만들고자 할 때는 아래와 같이 설계하면 된다.

    def dice_coef(y_true, y_pred):
        y_true_f = K.flatten(y_true)
        y_pred_f = K.flatten(y_pred)
        intersection = K.sum(y_true_f * y_pred_f)
        return (2. * intersection + K.epsilon()) / (K.sum(y_true_f) + K.sum(y_pred_f) + K.epsilon())

    def dice_coef_loss(y_true, y_pred):
        return 1-self.dice_coef(y_true, y_pred)

K는 케라스를 벡엔드로 쓰는 함수를 사용할 수 있게 해준다. 단 나누기 연산이 있을 때는 분모가 0이 되는 것을 방지하기 위해 K.epsilon()를 더해준다.

binary_crossentropy와 dice_coef를 합치는 것도 가능하다.

    def bce_dice_loss(y_true, y_pred):
        loss = losses.binary_crossentropy(y_true, y_pred) + dice_coef_loss(y_true, y_pred)
        return loss

 

Comments