ValueError:只有一个元素张量可以转换为 Python 标量 - 关于在列表中使用 torch.Tensor

问题描述 投票:0回答:1

我正在尝试将列表转换为张量:

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

为什么这不起作用?

python tensorflow machine-learning pytorch tensor
1个回答
0
投票
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]])
© www.soinside.com 2019 - 2024. All rights reserved.