Skip to main content
 首页 » 编程设计

python之TensorFlow sequence_loss 与 label_smoothing

2024年08月16日34zdz8207

是否可以使用 label_smoothing来自 tf.losses.softmax_cross_entropy 的功能与 tf.contrib.seq2seq.sequence_loss ?

我可以看到 sequence_loss可选择使用 softmax_loss_function作为参数。但是,此函数将采用 targets作为整数列表,而不是 tf.losses.softmax_cross_entropy 所需的单热编码向量, 这也是唯一支持 label_smoothing 的函数在 TensorFlow 中。

你能推荐一种让 label_smoothing 与 sequence_loss 一起工作的方法吗? ?

请您参考如下方法:

这无法有效地完成。

tf.contrib.seq2seq.sequence_loss旨在处理非常大的词汇表,因此它需要一个来自sparse 系列的损失函数(有关详细信息,请参阅 this question)。主要区别在于标签使用 ordinal 编码而不是 one-hot,因为后者占用太多内存。实际的单热编码从未计算过。

label_smoothing tf.losses.softmax_cross_entropy 的参数另一方面是操纵单热编码的选项。这是它的作用:

if label_smoothing > 0: 
  num_classes = math_ops.cast( 
      array_ops.shape(onehot_labels)[1], logits.dtype) 
  smooth_positives = 1.0 - label_smoothing 
  smooth_negatives = label_smoothing / num_classes 
  onehot_labels = onehot_labels * smooth_positives + smooth_negatives 

如您所见,要计算此张量,onehot_labels 必须显式存储,这正是稀疏函数试图避免的。这就是为什么 tf.nn.sparse_softmax_cross_entropy_with_logits 和 tf.contrib.seq2seq.sequence_loss 都没有提供类似的参数。当然,您可以自己进行转换,但这会破坏整个优化。