小编Pau*_*aul的帖子

如何加载具有自定义损失的模型?

如何加载具有子类 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)

python deep-learning keras tensorflow tensorflow2.0

3
推荐指数
1
解决办法
1586
查看次数

标签 统计

deep-learning ×1

keras ×1

python ×1

tensorflow ×1

tensorflow2.0 ×1