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.

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.

```
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
```

This method cannot be used for 2D lists.

Recommended Posts