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

时间:2016-01-19 11:44:36

标签: tensorflow

我是tensorflow的新手。我想写自己的自定义丢失函数。有关于此的任何教程吗?例如,铰链损失或sum_of_square_loss(虽然这已经在tf中)? 我可以直接在python中完成它,或者我必须编写cpp代码吗?

5 个答案:

答案 0 :(得分:46)

我们需要记下损失函数。例如,我们可以使用基本均方误差作为预测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函数定义计算,并使用会话来运行图形。我们可以定义我们喜欢的任何内容并最终运行它。

答案 1 :(得分:12)

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

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

答案 2 :(得分:7)

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

  

对当前模型与提供的数据之间的增量的平方进行求和

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的一般方法)。它的公式是:

enter image description here

我们唯一需要做的就是找到如何计算布尔值或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

答案 3 :(得分:0)

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'])

答案 4 :(得分:0)

我使用 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

可能对任何人都有帮助。