1

for example. I have a tensor like a = tf.constant([4,2,1,3]).

if I want to create a tensor with size [4, 5]

A tensor I need will contain following elements..


[[1,1,1,1,0],

[1,1,0,0,0],

[1,0,0,0,0],

[1,1,1,0,0] ] 

How can I create this tensor?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • This could help - [`Fill mask efficiently based on start indices`](https://stackoverflow.com/questions/58595650/fill-mask-efficiently-based-on-start-indices). – Divakar Oct 29 '19 at 16:18
  • Thanks Devakar, after I search on the tf documentation I found this function to solve my problem.. https://www.tensorflow.org/api_docs/python/tf/sequence_mask – Chalita Joomseema Oct 31 '19 at 09:22

1 Answers1

1

You can first create ones tensor and then pad to the same length. At the end, stack all tensors together.

a = tf.constant([4,2,1,3], dtype=tf.int32)

def pad_to_same(t):
    return tf.pad(tf.ones(t, dtype=tf.int32), [[0,5-t]], constant_values=0)

res = tf.stack([pad_to_same(t) for t in a])

# <tf.Tensor: id=35571, shape=(4, 5), dtype=float32, numpy=
# array([[1., 1., 1., 1., 0.],
#        [1., 1., 0., 0., 0.],
#        [1., 0., 0., 0., 0.],
#        [1., 1., 1., 0., 0.]], dtype=float32)>

Update If you want to avoid for-loop, you can use tf.map_fn,

def pad_to_same(t):
    return tf.pad(tf.ones(t, dtype=tf.int32), [[0,5-t]], constant_values=0)

res = tf.map_fn(pad_to_same, a)
zihaozhihao
  • 4,197
  • 2
  • 15
  • 25