【问题标题】:How to measure (content) length of right padded Tensor in Tensorflow 2?如何在 Tensorflow 2 中测量右填充张量的(内容)长度?
【发布时间】:2020-05-11 15:49:27
【问题描述】:

我有一些不同长度的序列(例如编码为数字数据的文本数据)。为了将它们放入张量中,使用零将它们右填充到固定宽度。例如:

import tensorflow as tf
x = tf.constant([[12, 31,  7,  5,  0,  0],
                 [ 1,  1,  0,  0,  0,  0],
                 [ 44, 9, 11, 21, 20, 22],
                 [  0, 0,  0,  0,  0,  0]])

现在我的问题是:如何测量这些填充序列的(内容)长度?

我期望从上面的示例中得到的输出是:

x_len = tf.constant([4, 2, 6, 0])

【问题讨论】:

    标签: python tensorflow tensorflow2.x


    【解决方案1】:

    一种解决方案是计算零的数量并将其从张量的宽度中减去,但 Tensorflow 已经具有无论如何计算非零值的功能:tf.math.count_nonzero

    因此,解决方案就像以下一条线一样简单:

    x_len = tf.math.count_nonzero(x, axis=1)
    

    【讨论】:

      猜你喜欢
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多