从张量列表创建参差不齐的张量 [英] Creating a ragged tensor from a list of tensors
问题描述
我想从 TensorFlow 2.0 中的张量列表中创建一个参差不齐的张量,如下所示:
I want to create a ragged tensor from a list of tensors in TensorFlow 2.0, something like this:
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()`
.另一方面,以下代码从列表列表中创建一个参差不齐的张量,效果很好.
But this throws ValueError: TypeError: Scalar tensor has no `len()`
. On the other hand, the following code, which creates a ragged tensor from a list of lists, works just fine.
a = [1,2]
b = [1,2,3]
tf.ragged.constant([a,b])
有没有办法直接从张量列表中创建一个参差不齐的张量,而无需先将张量转换为 python 列表?
Is there any way to create a ragged tensor directly from a list of tensors without first converting the tensors into python lists?
推荐答案
您可以使用 tf.RaggedTensor
.对于您的情况,您可以使用例如 from_row_lengths
:
You can construct ragged tensors with the different from_*
methods in tf.RaggedTensor
. For your case, you can use for example 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]]>
这篇关于从张量列表创建参差不齐的张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!