填充和屏蔽批处理数据集

问题描述 投票:1回答:1

表示自然语言的多个字符串时,每个字符串中的字符数可能不相等。然后,可以将返回结果放置在tf.RaggedTensor中,其中最里面的维的长度根据每个字符串中的字符数而变化:

tf.RaggedTensor

依次使用rtensor = tf.ragged.constant([ [1, 2], [3, 4, 5], [6] ]) rtensor #<tf.RaggedTensor [[1, 2], [3, 4, 5], [6]]> 方法,将to_tensor转换为常规to_tensor,并因此执行填充操作:

RaggedTensor

现在,有没有一种方法可以生成附加张量来显示什么是原始数据,什么是填充?对于上面的示例,它将是:

tf.Tensor
numpy tensorflow tensorflow2.0 tensorflow-datasets
1个回答
0
投票

batch_size=3 max_length=8 tensor = rtensor.to_tensor(default_value=0, shape=(batch_size, max_length)) #<tf.Tensor: shape=(3, 8), dtype=int32, numpy= #array([[1, 2, 0, 0, 0, 0, 0, 0], # [3, 4, 5, 0, 0, 0, 0, 0], # [6, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)> 所建议的,您只需检查非零值即可。它可以像转换为布尔值然后返回一样简单。

<tf.Tensor: shape=(3, 8), dtype=int32, numpy=
array([[1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)>

唯一可能的缺点是,您最初可能具有thusv89值。如果您知道数据总是非负的,则可以在转换为张量时使用其他一些值作为默认值,例如import tensorflow as tf rtensor = tf.ragged.constant([[1, 2], [3, 4, 5], [6]]) batch_size = 3 max_length = 8 tensor = rtensor.to_tensor(default_value=0, shape=(batch_size, max_length)) mask = tf.dtypes.cast(tf.dtypes.cast(tensor, tf.bool), tensor.dtype) print(mask.numpy()) # [[1 1 0 0 0 0 0 0] # [1 1 1 0 0 0 0 0] # [1 0 0 0 0 0 0 0]]

0

但是如果您想让蒙版适用于您拥有的任何值,也可以只将-1与参差不齐的张量一起使用:

tensor = rtensor.to_tensor(default_value=-1, shape=(batch_size, max_length))
mask = tf.dtypes.cast(tensor >= 0, tensor.dtype)

通过这种方式,tf.ones_like将始终是tf.ones_like具有值的精确位置。

© www.soinside.com 2019 - 2024. All rights reserved.