ValueError:only one element tensors can be converted to Python scalars解决办法
2024-09-07 00:00:55  阅读数 10706

有时候我们在使用pytorch将一个list转换成为tensor的时候可能会遇到这个问题:

报错内容:
ValueError:only one element tensors can be converted to Python scalars
或者:
TypeError: only integer tensors of a single element can be converted to an index

x = torch.tensor([1,2,3])
a = [x,x]
print(torch.tensor(a))

修改为:

x = torch.tensor([1,2,3])
a = [x.tolist(),x.tolist()]
print(torch.tensor(a))

或者:

x = torch.tensor([1,2,3])
a = [x,x]
print(torch.tensor([item.numpy() for item in a]))

当然会带来一些性能问题。因为这样子转换是非常耗时间的。
他可能会发出警告:
UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor.

要尽量避免这样的操作。