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

Introduction

When you play with pytorch, you rarely come across an unfamiliar error. This time, I will introduce how to deal with Value Error: only one element tensors can be converted to Python scalars that I encountered.

Cause

If you make torch.Tensor a list and put it in torch.tensor () or torch.as_tensor () entirely, the error as in the title will be spit out. However, it only occurs when the size of the Tensor is larger than 1 (probably). If you want to convert Tensor list to Tensor at once, use torch.stack. Below is a code example.

Code example

a = torch.ones([1])
b = torch.tensor([a])
c = torch.as_tensor([a]) #It's okay so far

a = torch.ones([2, 2])
b = torch.tensor([a]) #die
c = torch.tensor([b]) #die
d = torch.stack([a], dim=0) # size = (1, 2, 2)Tensor is created. dim by default=0

in conclusion

This method cannot be used for 2D lists.

Recommended Posts

ValueError: only one element tensors can be converted to Python scalars workaround
Only size-1 arrays can be converted to Python scalars
[Error] TypeError: only integer arrays with one element can be converted to an index
Have python check if the string can be converted / converted to int
[Python] Why immutable int types can be changed to different values