Search code examples
pythonpytorchtensorbackpropagation

Reduce dimensions of a tensor (to a scalar)


In:

a = torch.tensor([[2.4]])
torch.squeeze(a, 1)
a.size(), a

Out:

(torch.Size([1, 1]), tensor([[2.4000]]))

During computations using nn.MSELoss, I got a mismatch of dimensions. Input had size ([1,1]) and target ([]). The functions reshape and squeeze haven't worked. I would be grateful for a solution, to this embarassingly simple problem. : ]

Edit: there was a simple mistake of not assigning a= the squeezed value. Thank You for Your answer.


Solution

  • Function torch.squeeze will not modify input a. Either reassign it:

    a = a.squeeze(1)
    

    or use the in-place version of the function torch.squeeze_

    a.squeeze_(1)