abes
abes

Reputation: 53

How to convert back a ragged tensor with nested ragged dimension that was previously converted into a standard tensor

RaggedTensor has methods to_tensor() and from_tensor(). However it seems that applying tf.RaggedTensor.from_tensor(ragged_tensor.to_tensor(), padding=0) fails if ragged_tensor has nested dimensions

Example:

data = tf.ragged.constant([
    [[4,35,6,33], [7,2], [89,56,12]],
    [[2,11], [9]]
    ])

tf.RaggedTensor.from_tensor(data.to_tensor(), padding=0)

returns the error

Traceback (most recent call last):
    File "./src/tppmodel.py", line 34, in <module>
     tf.RaggedTensor.from_tensor(data.to_tensor(), padding=0)
    File "/opt/conda/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in    error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/opt/conda/lib/python3.8/site-packages/tensorflow/python/framework/tensor_shape.py", line 1307, in assert_is_compatible_with
    raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes () and (4,) are incompatible

Expected

tf.RaggedTensor.from_tensor(data.to_tensor(),..., padding=0) = data

Upvotes: 0

Views: 317

Answers (1)

abes
abes

Reputation: 53

I may have found an answer myself. Posting in case is useful to someone: Instead of using the padding parameter, pass the nested row lengths of the original tensor

tf.RaggedTensor.from_tensor(data.to_tensor(), lengths=data.nested_row_lengths())
data = tf.ragged.constant([
    [[4,35,6,33], [7,2], [89,56,12]],
    [[2,11], [9]]
    ])
data
tf.RaggedTensor.from_tensor(data.to_tensor(), lengths=data.nested_row_lengths())
> <tf.RaggedTensor [[[4, 35, 6, 33], [7, 2], [89, 56, 12]], [[2, 11], [9]]]>

Upvotes: 3

Related Questions