解决这个问题的方法是:
- 找出可变数据的最大长度。
- 找出每个训练实例的真实长度。
根据这两件事,您可以创建一个掩码,并让您的网络为您想要忽略的内容计算零梯度。
示例:
import tensorflow as tf
# pretend the longest data instance we will have is 5
MAX_SEQ_LEN = 5
# batch of indices indicating true length of each instance
idxs = tf.constant([3, 2, 1])
# batch of variable-length data
rt = tf.ragged.constant(
[
[0.234, 0.123, 0.654],
[0.111, 0.222],
[0.777],
], dtype=tf.float32)
t = rt.to_tensor(shape=[3, MAX_SEQ_LEN])
print(t)
# tf.Tensor(
# [[0.234 0.123 0.654 0. 0. ]
# [0.111 0.222 0. 0. 0. ]
# [0.777 0. 0. 0. 0. ]], shape=(3, 5), dtype=float32)
# use indices to create a boolean mask. We can use this mask in
# layers in our network to ignore gradients
mask = tf.sequence_mask(idxs, MAX_SEQ_LEN)
print(mask)
# <tf.Tensor: shape=(3, 5), dtype=bool, numpy=
# array([[ True, True, True, False, False],
# [ True, True, False, False, False],
# [ True, False, False, False, False]])>
此用例通常出现在 RNNs 中。您可以看到call() 方法中有一个mask 选项,您可以在其中为可变长度时间序列数据传递二进制掩码。