ValueError:在张量列表上使用 torch.Tensor 时,只能将一个元素张量转换为 Python 标量

use*_*180 5 python pytorch

我有一个张量列表:

object_ids = [tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.])]
Run Code Online (Sandbox Code Playgroud)

直观上,我似乎应该能够由此创建一个新的张量:

torch.as_tensor(object_ids, dtype=torch.float32)
Run Code Online (Sandbox Code Playgroud)

但这不起作用。显然, torch.as_tensor 和 torch.Tensor 只能将标量列表转换为新的张量。它无法将 d-dim 张量列表转换为 d+1 dim 张量。

Goo*_*eds 4

您可以使用torch.stack

在你的例子中:

>>> object_ids = [tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.]), tensor([2., 3.])]
>>> torch.stack(object_ids)
tensor([[2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.],
        [2., 3.]])
Run Code Online (Sandbox Code Playgroud)