I am looking for a good (efficient and preferably simple) way to create padded tensor from sequences of variable length / shape. The best way I can imagine so far is a naive approach like this:
import torch
seq = [1,2,3] # seq of variable length
max_len = 5 # maximum length of seq
t = torch.zeros(5) # padding value
for i, e in enumerate(seq):
t[i] = e
print(t)
Output:
tensor([ 1., 2., 3., 0., 0.])
Is there a better way to do so?
I haven't found something yet, but I guess there must be something better.
I'm thinking of some function to extend the sequence tensor to the desired shape with the desired padding. Or something to create the padded tensor directly from the sequence. But of course other approaches are welcome too.