如何在 Tensorflow 中编写自定义损失函数?

How to write a custom loss function in Tensorflow?

我是 tensorflow 的新手。我想编写自己的自定义损失函数。有没有关于这个的教程?例如,铰链损失或 sum_of_square_loss(虽然这已经在 tf 中了)? 我可以直接在 python 中执行还是必须编写 cpp 代码?

除了另一个答案,你可以在Python中写一个损失函数,如果它可以表示为现有函数的组合。

例如,看一下 sigmoid_cross_entropy_with_logits link 的实现,它是使用基本转换实现的。

我们需要写下损失函数。例如,我们可以使用基本均方误差作为预测 y 和目标 y_:

的损失函数
 loss_mse = 1/n(Sum((y-y_)^2))

有张量的基本函数,如 tf.add(x,y)tf.sub(x,y)tf.square(x)tf.reduce_sum(x) etc

然后我们可以在 Tensorflow 中定义我们的损失函数:

cost = tf.reduce_mean(tf.square(tf.sub(y,y_)))

注:y 和 y_ 是张量。

此外,如果我们可以写下方程,我们可以定义任何其他损失函数。对于一些训练算子(最小化器),损失函数应该满足一些条件(平滑,可微...)。

一言以蔽之,Tensorflow 将数组、常量、变量定义为张量,使用 tf 函数定义计算,并使用 session 到 运行 though graph。我们可以定义任何我们喜欢的东西,最后运行它。

几乎在所有 TensorFlow 教程中,他们都使用自定义函数。例如在 beginning tutorial 他们写了一个自定义函数:

sums the squares of the deltas between the current model and the provided data

squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)

在下MNIST for beginners they use a cross-entropy:

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

如您所见,一点也不难:您只需要将您的函数编码为张量格式并使用它们的基本函数。

例如,这里是您可以如何实施 F-beta 分数F1 score 的一般方法)。其公式为:

我们唯一需要做的就是找到如何计算布尔值或 0/1 值的 true_positive、false_positive、false_negative。如果您有 0/1 值的向量,则可以将每个值计算为:

TP = tf.count_nonzero(actual, predicted)
FP = tf.count_nonzero((actual - 1) * predicted)
FN = tf.count_nonzero((predicted - 1) * actual)

现在,一旦您知道了这些值,您就可以轻松获得

denom = (1 + b**2) * TP + b**2 TN + FP
Fb = (1 + b**2) * TP / denom
def focal_loss(y_true, y_pred):
  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))
  custom_loss=kb.square((pt_1-pt_0)/10)
  return custom_loss    

model.compile(loss=focal_loss,
          optimizer='adam',
          metrics=['accuracy'])

我使用 Kullbak-Leibler 散度实现自定义损失函数,其中 p = 常数。 我在自动编码器中使用它。

rho = 0.05

class loss_with_KLD(losses.Loss):
    
    def __init__(self, rho):
        super(loss_with_KLD, self).__init__()
        self.rho = rho
        self.kl = losses.KLDivergence()
        self.mse = losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.SUM)
        
    def call(self, y_true, y_pred):
        mse = self.mse(y_true, y_pred)
        kl = self.kl(self.rho, y_pred)
        return mse + kl

可能对任何人都有帮助。