Pytorch BUG: ValueError:only one element tensors can be converted to Python scalars

Pytorch BUG: ValueError:only one element tensors can be converted to Python scalars

这是由于把包含tensor的列表直接转换tensor 导致的错误

# 错误例子:
import torch
a = torch.tensor([1.0,2,3])
b = torch.tensor([2.0,2,3])
c = torch.tensor([3.0,2,3])
arr = [a,b,c]
target = torch.tensor(arr)

说明一下,我目标是要把a,b,c 合并为

tensor([[1.0,2,3],
        [2.0,2,3],
        [3.0,2,3]])

解决思路是把a,b,c扩充一个维度,变成2维的,之后使用torch.cat合并

import torch
a = torch.tensor([1.0,2,3])
b = torch.tensor([2.0,2,3])
c = torch.tensor([3.0,2,3])
arr = [a,b,c]
arr = [torch.unsqueeze(t,dim=0) for t in arr]  # torch.unsqueeze增加一个维度
target = torch.cat(arr, dim=0)

# 结果
tensor([[1., 2., 3.],
        [2., 2., 3.],
        [3., 2., 3.]])

你可能感兴趣的:(python随笔,python,pytorch,bug)