Issue
I want to convert a list of list to torch.LongTensor.
The element in a list of sequence means embedding index, and each list has different size.
For example,
tmp = [[7, 1], [8, 4, 0], [9]]
tmp = torch.LongTensor(tmp)
This occrus TypeError: not a sequence
How can I convert different sizes of a list in list to torch Tensor?
Solution
This will solve your issue:
tmp = torch.LongTensor(list(map(lambda x: x + [0] * (max(map(len, tmp)) - len(x)), tmp)))
Explanation:
# 1
map(lambda x: x + [0] * (max(map(len, tmp)) - len(x)), tmp)
# -> [[7, 1, 0], [8, 4, 0], [9, 0, 0]]
# 2
torch.LongTensor([[7, 1, 0], [8, 4, 0], [9, 0, 0]])
# -> tensor([[7, 1, 0],
# [8, 4, 0],
# [9, 0, 0]])
Answered By - Jiya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.