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])
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])
Is there any way to create a ragged tensor directly from a list of tensors without first converting the tensors into python lists?
Ragged tensors are the TensorFlow equivalent of nested variable-length lists. They make it easy to store and process data with non-uniform shapes, including: Variable-length features, such as the set of actors in a movie. Batches of variable-length sequential inputs, such as sentences or video clips.
To convert a Python list to a tensor, we are going to use the tf. convert_to_tensor() function and this function will help the user to convert the given object into a tensor. In this example, the object can be a Python list and by using the function will return a tensor.
Used in the notebooks. Unpacks tensors from value by chipping it along the axis dimension. This is the opposite of stack. The shape of each result tensor is equal to the shape of the input tensor, with the target axis removed.
tf.stack( values, axis=0, name='stack' ) Defined in tensorflow/python/ops/array_ops.py. Stacks a list of rank- R tensors into one rank- (R+1) Packs the list of tensors in values into a tensor with rank one higher than each tensor in values , by packing them along the dimension.
You can use 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]]>
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]]>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With