top_k
有梯度,是从0.8版本开始添加的,详见这里
只需三行代码即可添加另一个实现
scores: 未缩放的分数,张量,形状为(n_classes, batch_size),数据类型为float32
classes: 张量,形状为(batch_size, batch_size),数据类型为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
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))
top_k
有梯度。 - Yaroslav Bulatov