繁体   English   中英

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

[英]ValueError: only one element tensors can be converted to Python scalars when using torch.Tensor on list of tensors

我有一个张量列表:

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.as_tensor(object_ids, dtype=torch.float32)

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

您可以使用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.]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM