[英]Creating a ragged tensor from a list of tensors
我想从 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 列表?
您可以使用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]]>
您可以构建衣衫褴褛的张量与不同from_*
的方法tf.RaggedTensor
。 对于您的情况,您可以使用例如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]]>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.