def contrastive_loss(y_true, y_pred): '''Contrastive loss from Hadsell-et-al.'06 http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf ''' square_pred = K.square(y_pred) margin_square = K.square(K.maximum(margin - y_pred, 0)) return K.mean(y_true * square_pred + (1 - y_true) * margin_square)
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 f1_loss(y_true, y_pred): tp = K.sum(K.cast(y_true * y_pred, 'float'), axis=0) tn = K.sum(K.cast((1 - y_true) * (1 - y_pred), 'float'), axis=0) fp = K.sum(K.cast((1 - y_true) * y_pred, 'float'), axis=0) fn = K.sum(K.cast(y_true * (1 - y_pred), 'float'), axis=0) p = tp / (tp + fp + K.epsilon()) r = tp / (tp + fn + K.epsilon()) f1 = 2 * p * r / (p + r + K.epsilon()) f1 = tf.where(tf.math.is_nan(f1), tf.zeros_like(f1), f1) return 1 - K.mean(f1)
def surface_loss(y_true, y_pred): y_true_dist_map = tf.py_function(func=calc_dist_map_batch, inp=[y_true], Tout=tf.float32) multipled = y_pred * y_true_dist_map return K.mean(multipled)
def call(self, y_true, y_pred): square_pred = keras.square(y_pred) margin_square = keras.square(keras.maximum(self.margin - y_pred, 0)) return keras.mean(y_true * square_pred + (1 - y_true) * margin_square)