我在做一些数据科学工作的时候,我被困在这个问题上,我试图为一个有监督的任务建立一个模型,其中输入和输出都是可变长度的。
下面是关于输入和输出的示例:
Input[0]: [2.42, 0.43, -5.2, -54.9]
Output[0]: ['class1', 'class3', 'class12']问题是,在我所拥有的数据集中,输入和输出都是可变长度的,所以为了能够使用整个数据集,我需要找到一种编码这些数据的方法。
首先,我对输出类进行了编码,并在dataset中添加了一个填充,以等于所有输出长度(比方说length=(6,)):
Encoded_output[0]: [1, 3, 12, 0, 0, 0]但是我无法找到一种编码输入的方法,因为原始输入数据是浮动的,所以不能创建编码和添加填充。我不知道我还有什么选择,我想听听你怎么解决这个问题。
发布于 2021-02-21 19:36:04
解决这一问题的一个办法是:
从这两个方面,您可以创建一个掩码,并让您的网络为您想要忽略的内容计算零梯度。
示例
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中。您可以看到,在mask方法中有一个call()选项,可以为可变长度的时间序列数据传递二进制掩码。
https://stackoverflow.com/questions/66304420
复制相似问题