pythontensorflowtensorragged

How to pre-pad tensorflow ragged tensor with beginning values


This question is similar to this question:

pad last dimension of tensor

with the exception that I would like to pre-pad this tensor with the beginning values. Given the ragged tensor:

 [[1],
 [4, 2],
 [1, 2, 3]]

I would expect the output to be:

[[1 1 1],
 [4 4 2],
 [1 2 3]]

I would like to be able to apply the solution to a larger ragged tensor.


Solution

  • Just use the properties of a ragged tensor:

    import tensorflow as tf
    
    x = tf.ragged.constant([[1],
                            [4, 2],
                            [1, 2, 3]])
    
    rows_to_pad = tf.abs(x.row_lengths() - tf.reduce_max(x.row_lengths()))
    
    padded_x = tf.concat([tf.RaggedTensor.from_row_lengths(
        values=tf.repeat(tf.gather(x.merge_dims(0, -1), x.row_starts()), rows_to_pad, axis=0),
        row_lengths=rows_to_pad), x], axis=-1).to_tensor()
    
    [[1 1 1]
     [4 4 2]
     [1 2 3]]
    

    A different ragged tensor:

    x = tf.ragged.constant([[1, 4, 5, 6, 7, 8, 3],
                            [4, 2],
                            [1, 2, 3], 
                            [1, 2, 3, 4, 5], 
                            [1]])
    

    Pre-padded:

    [[1 4 5 6 7 8 3]
     [4 4 4 4 4 4 2]
     [1 1 1 1 1 2 3]
     [1 1 1 2 3 4 5]
     [1 1 1 1 1 1 1]]