我正在尝试将列表转换为张量:
a = torch.rand((2,3))
a = [(b,2) for b in a]
print(a)
>>>[(tensor([0.2783, 0.4820, 0.8198]), 2), (tensor([0.9971, 0.6984, 0.5675]), 2)]
c = torch.Tensor(a)
但是我得到错误:
----> 4 c = torch.Tensor(a)
ValueError: only one element tensors can be converted to Python scalars
为什么这不起作用?
a = torch.rand((2,3))
print(a)
#output
tensor([[0.6604, 0.6619, 0.9028],
[0.5188, 0.5873, 0.9436]])
现在,a变成了一个元组列表:
a = [(b,2) for b in a]
#output
[(tensor([0.2783, 0.4820, 0.8198]), 2), (tensor([0.9971, 0.6984, 0.5675]), 2)]
type(a)
#list
[type(x) for x in a]
#[tuple, tuple]
如果你这样做:
a = torch.rand((2,3))
c = torch.Tensor(a)
print(c)
#output
tensor([[0.5947, 0.8291, 0.4436],
[0.0330, 0.4810, 0.5534]])