#loss的shape=[batch,num_step],seqlen的shape = [batch]
def mask(self, loss, seqlen):
mask = tf.sequence_mask(seqlen, maxlen=config.num_steps, dtype=tf.int32)
clear_loss = np.sum(loss * mask) / np.sum(mask)
return clear_loss
该段代码的实现是受下面问答的启发:
Question:
Hi,
Say I want to train some LSTM unit, and my training data has variable lengths with a maximum length of say, 30.
What is the right thing to do?
In TF we cannot dynamically create a computation graph of varied lengths, so the number of LSTM unrolling is fixed.
So do we have to pad everything to have a length of 30?
Let’s say

在训练LSTM时,面对不同长度的输入序列,通常需要填充到固定长度。在TensorFlow中,可以通过添加“NUL”符号来实现。然而,这可能导致模型学习到填充符号的行为,影响泛化能力。解决办法是在计算成本时应用Mask,忽略填充部分。在序列到序列模型中,可以找到许多这样的例子,如TensorFlow官方的seq2seq教程中所介绍的‘bucketing and padding’。
最低0.47元/天 解锁文章
1193

被折叠的 条评论
为什么被折叠?



