2016-04-28 93 views
3

我想在张量流中实现多级铰链损失。该配方如下:如何在张量流中实现多级铰链损失

multi-class hinge loss function

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

+0

哪个版本的TF你有?在最新版本中'top_k'有梯度 –

回答

3

top_k有梯度,在版本中添加0.8 here

+0

谢谢。我从TF 0.7改为0.8。 –

+0

ps:正如另一位用户所指出的那样,在TensorFlow中有一个关于铰链损失的工作示例,对于未来的文档目的将是有用的,谢谢! –

1

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

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

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

的batch_size,n_classes:整数

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)) 
1

添加另一实现三行代码 得分:非标度分数,张量,shape =(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 

您可以最小化在这里转置的实现。