如何加载具有子类 tf.keras.losses.Loss 的自定义损失的模型?
我通过子类化 tf.keras.losses.Loss 来定义 ContrastiveLoss,如下所示:
import tensorflow as tf
from tensorflow.keras.losses import Loss
class ContrastiveLoss(Loss):
def __init__(self, alpha, square=True, **kwargs):
super(ContrastiveLoss, self).__init__(**kwargs)
self.alpha = alpha
self.square = square
def get_dists(self, x, y, square):
dists = tf.subtract(x, y)
dists = tf.reduce_sum(tf.square(dists), axis=-1)
if not square:
zero_mask = tf.cast(tf.equal(dists, 0.0), tf.float32)
dists = dists + zero_mask * 1e-16
dists = tf.sqrt(dists)
nonzero_mask = 1.0 - zero_mask
dists = dists * nonzero_mask
return dists
def call(self, y_true, y_pred):
# y_true & …Run Code Online (Sandbox Code Playgroud)