【问题标题】:Sparse Cross Entropy in TensorflowTensorflow 中的稀疏交叉熵
【发布时间】:2016-09-18 09:37:17
【问题描述】:

在 tensorflow 中使用 tf.nn.sparse_softmax_cross_entropy_with_logits,可以通过将类标签设置为 -1 来仅计算特定行的损失(否则它应该在 0->numclasses-1 的范围内)。

不幸的是,这会破坏梯度计算(如源 nn_ops.py 中的 cmets 所述)。

我想做的事情如下:

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)

将这些渐变归零最直接的方法是什么?

【问题讨论】:

  • 您可以使用clip_by_value 剪辑您的祖孙。
  • 抱歉,我只是不确定您所说的“不正确”渐变是什么意思。带有“-1”的行的loss会为零,也就是说你的参数在最终loss中没有生效,那为什么不为零呢?

标签: python tensorflow


【解决方案1】:

最简单的方法是将分类损失乘以一个相似的张量,在需要损失的地方为 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)))

它也应该将梯度归零。

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 2020-10-12
    • 2017-12-26
    • 2019-12-18
    • 2021-02-15
    • 2021-03-19
    • 2022-10-04
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多