[英]How to convert a list in list to torch tensor?
I want to convert a list of list to torch.LongTensor.我想将列表列表转换为 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
这个 occrus TypeError: not a sequence
How can I convert different sizes of a list in list to torch Tensor?如何将列表中不同大小的列表转换为火炬张量?
You are looking for nested tensors (see docs ).您正在寻找嵌套张量(请参阅文档)。
import torch
tmp = [[7, 1], [8, 4, 0], [9]]
tmp = list(map(torch.as_tensor, tmp))
tmp = tmp = torch.nested.as_nested_tensor(tmp, dtype=torch.long)
tmp
>>> nested_tensor([
tensor([7, 1]),
tensor([8, 4, 0]),
tensor([9])
])
Alternatively, you can also pad the tensor to the same length:或者,您也可以将张量填充到相同的长度:
tmp = torch.nested.to_padded_tensor(tmp, 0).long()
tmp
>>> tensor([
[7, 1, 0],
[8, 4, 0],
[9, 0, 0]
])
Welcome to StackOverflow欢迎来到 StackOverflow
tmp = torch.LongTensor(list(map(lambda x: x + [0] * (max(map(len, tmp)) - len(x)), tmp)))
# 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]])
import torch
import itertools
tmp = [[7, 1], [8, 4, 0], [9]]
tmp = torch.LongTensor(list(itertools.chain(*tmp)))
If you don't need to maintain the shape, this could be help.如果您不需要保持形状,这可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.