【问题标题】:ValueError: only one element tensors can be converted to Python scalars when using torch.Tensor on list of tensorsValueError:在张量列表上使用 torch.Tensor 时,只能将一个元素张量转换为 Python 标量
【发布时间】:2021-07-23 10:57:05
【问题描述】:

我有张量列表:

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 张量。

【问题讨论】:

标签: python pytorch


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 2022-01-19
    • 2019-02-04
    • 2021-03-16
    • 2021-03-04
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多