【问题标题】:Creating a ragged tensor from a list of tensors从张量列表中创建一个参差不齐的张量
【发布时间】:2019-08-04 12:28:53
【问题描述】:

我想从 TensorFlow 2.0 中的张量列表创建一个参差不齐的张量,如下所示:

a = tf.convert_to_tensor([1,2])
b = tf.convert_to_tensor([1,2,3])
tf.ragged.constant([a, b])

但这会抛出ValueError: TypeError: Scalar tensor has no `len()`。另一方面,以下代码从列表列表中创建一个不规则张量,工作得很好。

a = [1,2]
b = [1,2,3]
tf.ragged.constant([a,b])

有没有什么方法可以直接从张量列表中创建一个参差不齐的张量,而无需先将张量转换为 python 列表?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    你可以使用tf.ragged.stack:

    >>> a = tf.convert_to_tensor([1,2])
    >>> b = tf.convert_to_tensor([1,2,3])
    >>> tf.ragged.stack([a, b])
    <tf.RaggedTensor [[1, 2], [1, 2, 3]]>
    

    【讨论】:

      【解决方案2】:

      您可以使用tf.RaggedTensor 中的不同from_* 方法构造不规则张量。对于您的情况,您可以使用例如 from_row_lengths:

      import tensorflow as tf
      
      def stack_ragged(tensors):
          values = tf.concat(tensors, axis=0)
          lens = tf.stack([tf.shape(t, out_type=tf.int64)[0] for t in tensors])
          return tf.RaggedTensor.from_row_lengths(values, lens)
      
      a = tf.convert_to_tensor([1, 2])
      b = tf.convert_to_tensor([1, 2, 3])
      print(stack_ragged([a, b]))
      # <tf.RaggedTensor [[1, 2], [1, 2, 3]]>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多