Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 229
John Mansell Avatar asked Jan 30 '26 03:01

John Mansell


1 Answers

In specific case where values are same per first dimension as are in your example. You can use:

digits = tf.ragged.constant([[1., 1., 1.],[2.],[3., 3., 3., 3.],[4., 4.]])
padded = digits.to_tensor(0.)
final_tensor = tf.reverse(padded, [-1])

output:

tf.Tensor(
    [[0. 1. 1. 1.]
     [0. 0. 0. 2.]
     [3. 3. 3. 3.]
     [0. 0. 4. 4.]], shape=(4, 4), dtype=float32)
like image 139
oktogen Avatar answered Feb 01 '26 17:02

oktogen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!