ValueError: only one element tensors can be converted to Python scalars
a =[0, 4, 4, 4, 1, 4, 2, 2, 0, 3, 2, 2, 3, 4, 2, 0, 4, 0, 1, 3, 0, 4, 1, 1, 4, 1, 0, 1, 2, 0, 2, 4]
a=torch.tensor(a)
a是一个’torch.LongTensor’类型的数据
当我想重新得到a的列表或者numpy数据怎么办呢?
当我尝试使用item时
a.item()
报错
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-7-cd1bda83583f>", line 1, in <module>
a.item()
ValueError: only one element tensors can be converted to Python scalars
查询官方文档描述
解决
根据需求使用下面解决方法
- 使用numpy()
a.numpy()
array([0, 4, 4, 4, 1, 4, 2, 2, 0, 3, 2, 2, 3, 4, 2, 0, 4, 0, 1, 3, 0, 4,
1, 1, 4, 1, 0, 1, 2, 0, 2, 4], dtype=int64)
- 使用tolist()
a.tolist()
[0,
4,
4,
4,
1,
4,
2,
2,
0,
3,
2,
2,
3,
4,
2,
0,
4,
0,
1,
3,
0,
4,
1,
1,
4,
1,
0,
1,
2,
0,
2,
4]