【问题标题】:How to implement multi-class hinge loss in tensorflow如何在tensorflow中实现多类铰链损失
【发布时间】:2016-04-28 02:39:06
【问题描述】:

我想在 tensorflow 中实现多类铰链损失。配方如下:

当预测正确时,我发现很难获得第二个最大预测概率。我尝试使用 tf.nn.top_k 来计算它,但不幸的是 tf.nn.top_k 没有实现梯度操作。那么我该如何实现呢?

【问题讨论】:

  • 你的TF是哪个版本的?在最新版本中top_k 有渐变
  • @csz-carrot 我知道你问这个问题已经有一段时间了,但如果你能够让它工作,它会帮助很多人,如果你可以发布损失的 tensorflow 实现这里。谢谢。

标签: neural-network tensorflow


【解决方案1】:

top_k 有渐变,在 0.8 版本中添加 here

【讨论】:

  • 谢谢。我从 TF 0.7 更改为 0.8。
  • ps:正如另一位用户所说,在 TensorFlow 中提供一个铰链损失的工作示例会很有用,以用于将来的文档目的,谢谢!
【解决方案2】:

用三行代码添加另一个实现 分数:未缩放的分数,张量,形状=(n_classes,batch_size),dtype=float32 类:张量,形状=(batch_size,batch_size),dtype=float32

通过选择最违反的类而不是考虑所有类来实现上述损失

#H - hard negative for each sample
H = tf.reduce_max(scores * (1 - classes), 0)    
L = tf.nn.relu((1 - scores + H) * classes)
final_loss = tf.reduce_mean(tf.reduce_max(L, 0))

我们对所有负类求和的另一种实现

# implements loss as sum_(j~=y) max(0, 1 - s(x, y) + s(x, j))
def multiclasshingeloss1(scores, classes):
    true_classes = tf.argmax(classes, 0)
    idx_flattened = tf.range(0, scores.get_shape()[1]) * scores.get_shape()[0]+\
    tf.cast(true_classes, dtype=tf.int32)
    true_scores = tf.gather(tf.reshape(tf.transpose(scores), [-1]),
                            idx_flattened)
    L = tf.nn.relu((1 - true_scores + scores) * (1 - classes))
    final_loss = tf.reduce_mean(L)
    return final_loss

您可以根据您的实现在此处最小化转置。

【讨论】:

    【解决方案3】:

    我的实现如下,但我认为必须有更高效的实现。

    logits:未缩放的分数、张量、shape=(batch_size, n_classes)

    标签:张量,形状=(batch_size, )

    batch_size, n_classes: int

    def multi_class_hinge_loss(logits, label, batch_size, n_classes):
        # get the correct logit
        flat_logits = tf.reshape(logits, (-1,))
        correct_id = tf.range(0, batch_size) * n_classes + label
        correct_logit = tf.gather(flat_logits, correct_id)
    
        # get the wrong maximum logit
        max_label = tf.argmax(logits, 1)
        top2, _ = tf.nn.top_k(logits, k=2, sorted=True)
        top2 = tf.split(1, 2, top2)
        for i in xrange(2):
            top2[i] = tf.reshape(top2[i], (batch_size, ))
        wrong_max_logit = tf.select(tf.equal(max_label, label), top2[1], top2[0])
    
        # calculate multi-class hinge loss
        return tf.reduce_mean(tf.maximum(0., 1. + wrong_max_logit - correct_logit))
    

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 2021-09-09
      • 2019-01-14
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 2018-12-08
      • 2020-05-20
      相关资源
      最近更新 更多