Skip to content

Instantly share code, notes, and snippets.

@zhoudaxia233
Created May 22, 2019 14:05
Show Gist options
  • Save zhoudaxia233/6258765ecb968f284a3f9ea28d69394f to your computer and use it in GitHub Desktop.
Save zhoudaxia233/6258765ecb968f284a3f9ea28d69394f to your computer and use it in GitHub Desktop.
Multi-class Focal Loss in Keras
from keras import backend as K
def focal_loss(gamma=2):
def loss(y_true, y_pred):
epsilon = K.epsilon()
y_pred = K.clip(y_pred, epsilon, 1 - epsilon)
pt = K.max(y_true * y_pred, axis=-1)
batch_loss = -K.pow((1 - pt), gamma) * K.log(pt)
return K.mean(batch_loss)
return loss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment