def FocalLoss(y_true, y_pred): """ :param y_true: A tensor of the same shape as `y_pred` :param y_pred: A tensor resulting from a sigmoid :return: Output tensor. """ gamma = 2.0 alpha = 0.25 pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred)) pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred)) epsilon = K.epsilon() # clip to prevent NaN's and Inf's pt_1 = K.clip(pt_1, epsilon, 1. - epsilon) pt_0 = K.clip(pt_0, epsilon, 1. - epsilon) return -K.mean(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) \ - K.mean((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))
def jaccard_coef_logloss(y_true, y_pred, smooth=1e-10): """ Loss function based on jaccard coefficient. Parameters ---------- y_true : keras tensor tensor containing target mask. y_pred : keras tensor tensor containing predicted mask. smooth : float small real value used for avoiding division by zero error. Returns ------- keras tensor tensor containing negative logarithm of jaccard coefficient. """ y_true = K.flatten(y_true) y_pred = K.flatten(y_pred) truepos = K.sum(y_true * y_pred) falsepos = K.sum(y_pred) - truepos falseneg = K.sum(y_true) - truepos jaccard = (truepos + smooth) / (smooth + truepos + falseneg + falsepos) return -K.log(jaccard + smooth) # might be 1 -