[Solved] ValueError: only one element tensors can be converted to Python scalars

This error occurred in Python.

At first, the reason is that I want to change the list with a tensor to a tensor type, that is, [tensor (), tensor ()] to a tensor, and then I write like this,

a = torch.randn(1,2) # tensor([[-0.4962,  0.6034]])
d = [a, a, a] # [tensor([[-0.4962,  0.6034]]), tensor([[-0.4962,  0.6034]]), tensor([[-0.4962,  0.6034]])]
d = torch.tensor(d)

It’s a mistake. ValueError: only one element tensors can be converted to Python scalars

I see a solution on the Internet,

val= torch.tensor([item.cpu().detach().numpy() for item in val]).cuda() 

This method is very unsophisticated and concise.

Another way is to use torch. Cat, which is very concise. If you want to expand dimensions, you can use operations such as unsqueeze on this basis.

d = torch.cat(d, 0) 

'''
Output: tensor([[-0.4962,  0.6034],
        [-0.4962,  0.6034],
        [-0.4962,  0.6034]])
'''


Read More: