list TO tensor
1 Problem Setting
import torch
d = []
a = torch.tensor([[0, 1], [3, 4]])
b = torch.tensor([[0, 7], [3, 48]])
d.append(a)
d.append(b)
d = torch.tensor(d)
报错如下:
TypeError: only integer tensors of a single element can be converted to an index
or
ValueError: only one element tensors can be converted to Python scalars
2 Solution
import torch
d = []
a = torch.tensor([[0, 1], [3, 4]])
b = torch.tensor([[0, 7], [3, 48]])
d.append(a)
d.append(b)
# d = torch.tensor(d)
d = torch.cat(d, dim=0)
print(d)
输出:
tensor([[ 0, 1],
[ 3, 4],
[ 0, 7],
[ 3, 48]])
3 Conclusion
-
包含tensor的list转tensor:list(tensors) → torc.cat(list, dim=0)
-
包含整数或浮点数的list转tensor:list(int/float) → torch.tensor(list)