How can I fill a ragged tensor with zeros to make a square tensor

Issue

I want to transform A into B:

A = 
  [1, 1, 1]
  [2]
  [3, 3, 3, 3]
  [4, 4]

B =
  [
   [0, 1, 1, 1]
   [0, 0, 0, 2]
   [3, 3, 3, 3]
   [0, 0, 4, 4]
  ]

Input:
– a list of lists

Output:
– a single matrix or tensor
– right aligned
– Left fill with 0’s

Solution

A is a list, so we can for-loop and use tf.pad and tf.stack to get the output tensor.

max_len = max(len(e) for e in A)
res = tf.stack([tf.pad(e, [[max_len - len(e),0]]) for e in A], axis=0)
# array([[0, 1, 1, 1],
#        [0, 0, 0, 2],
#        [3, 3, 3, 3],
#        [0, 0, 4, 4]], dtype=int32)

Answered By – zihaozhihao

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published