在tensorflow中使用tf.nn.sparse_softmax_cross_entropy_with_logits,可以通过将类标签设置为-1来仅计算特定行的损失(否则它应该在0->numclasses-1的范围内)。
不幸的是,这破坏了梯度计算(正如在源nn_ops.py的注释中提到的)。
我想做的事情如下:
raw_classification_output1 = [0,1,0]
raw_classification_output2 = [0,0,1]
classification_output =tf.concat(0,[raw_classification_output1,raw_classification_output2])
classification_labels = [1,-1]
classification_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(classification_output,classification_labels)
total_loss = tf.reduce_sum(classification_loss) + tf.reduce_sum(other_loss)
optimizer = tf.train.GradientDescentOptimizer(1e-3)
grads_and_vars = optimizer.compute_gradients(total_loss)
changed_grads_and_vars = #do something to 0 the incorrect gradients
optimizer.apply_gradients(changed_grads_and_vars)
将这些梯度置零的最直接方法是什么?
发布于 2016-05-21 05:50:37
最简单的方法是将分类损失乘以类似的张量1,在需要损失的地方乘以0,在不希望更新的地方乘以0,这就变得更容易了。这基本上只是一种变通方法,因为如果这个稀疏softmax的损失为零,它仍然会产生一些奇怪的梯度行为。在tf.nn.sparse_softmax_cross_entropy_with_logits:之后添加此行
classification_loss_zeroed = tf.mul(classification_loss,tf.to_float(tf.not_equal(classification_loss,0)))
它也应该将梯度归零。
https://stackoverflow.com/questions/37358241
复制