【发布时间】:2020-08-06 07:50:45
【问题描述】:
表示多个自然语言字符串时,每个字符串中的字符数可能不相等。然后,可以将返回结果放在tf.RaggedTensor 中,其中最内层维度的长度取决于每个字符串中的字符数:
rtensor = tf.ragged.constant([
[1, 2],
[3, 4, 5],
[6]
])
rtensor
#<tf.RaggedTensor [[1, 2], [3, 4, 5], [6]]>
反过来,应用 to_tensor 方法,将 RaggedTensor 转换为常规 tf.Tensor 并因此应用填充操作:
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)>
【问题讨论】:
-
tf.math.not_equal(tensor, 0)?
标签: numpy tensorflow tensorflow2.0 tensorflow-datasets