Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a ragged tensor from a list of tensors

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?

like image 546
Isaac Breen Avatar asked Aug 04 '19 12:08

Isaac Breen


People also ask

What is ragged tensor?

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.

How do I convert a list to TF tensor?

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.

What does TF unstack do?

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.

What is TF stack?

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.


2 Answers

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]]>
like image 175
Edward Loper Avatar answered Nov 06 '22 13:11

Edward Loper


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]]>
like image 20
jdehesa Avatar answered Nov 06 '22 11:11

jdehesa