【问题标题】:Using len() on TensorFlow ragged tensor在 TensorFlow 不规则张量上使用 len()
【发布时间】:2021-04-13 11:22:07
【问题描述】:

通常在 TensorFlow 中,您不能在参差不齐的张量上使用 len(),例如

import tensorflow as tf
x = tf.ragged.stack([[1],[1,2]])
print(len(x))

由于不规则张量没有实现长度方法,因此您会得到以下预期错误:

TypeError: object of type 'RaggedTensor' has no len()

但是,我发现当我创建一个映射到 tf 数据集的函数时,由于某种原因,您可以在不规则的张量上调用 len() 而不会出错。

dataset = dataset.map(lambda path, label: self._process_path(path, label, self.background_data)
...

def _process_path(path, label, background_data):
    ...
    x = tf.ragged.stack([[1],[1,2]])
    print(type(x))
    print(len(x))
    print((x.shape[0]))
    ...

那么在训练中使用时会正确打印出以下内容:

<class 'tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor'>
2
2

有什么明显的我错过了为什么会这样以及它是如何工作的。是否与将 tf 数据集映射函数转换为图形函数因此不急于运行有关?

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

    不规则张量通常包含可变大小的序列列表。确切的长度是很模糊的。我们需要迭代得到每个序列的长度。

    import tensorflow as tf
    x = tf.ragged.stack([[1],[1,2]])
    
    len(x.to_list())  # total 2 
    for i in x:
        print(len(i))
    

    如果我们将其传递给tf. data. Dataset. from_tensor_slices - 它会为输入的每个序列列表创建一个带有单独元素的迷你数据集:

    A =  tf.data.Dataset.from_tensor_slices(x)
    
    len(A) # total 2  
    for i in A:
        print(len(i))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      相关资源
      最近更新 更多