[英]How to convert a list in list to torch tensor?
我想將列表列表轉換為 torch.LongTensor。
序列列表中的元素表示嵌入索引,每個列表的大小不同。
例如,
tmp = [[7, 1], [8, 4, 0], [9]]
tmp = torch.LongTensor(tmp)
這個 occrus TypeError: not a sequence
如何將列表中不同大小的列表轉換為火炬張量?
您正在尋找嵌套張量(請參閱文檔)。
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])
])
或者,您也可以將張量填充到相同的長度:
tmp = torch.nested.to_padded_tensor(tmp, 0).long()
tmp
>>> tensor([
[7, 1, 0],
[8, 4, 0],
[9, 0, 0]
])
歡迎來到 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)))
如果您不需要保持形狀,這可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.