Skip to main content
 首页 » 编程设计

python之Tensorflow 中的稀疏交叉熵

2025年04月02日28bluestorm

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

将这些梯度归零的最直接方法是什么?

请您参考如下方法:

最简单的方法是将分类损失乘以类似的张量,在需要损失的地方为 1,在不需要损失的地方为零。由于您不希望更新损失已经为零,因此这变得更容易。这基本上只是一个变通方法,因为如果你对这个稀疏 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))) 

它也应该将梯度归零。