Difficulties calculating mean square error between 2 tensors

2.7k views Asked by At

I'm trying to build a loss function which will calculate the mean squared error of 2 tenors of the same size. In other words I need a function that calcualtes the difference of every 2 cells (with the same row and column) cell on matrix A and matrix B, squares it and calculate the mean of the differences.

As far as I understand nn.MSELoss should do exactly that.

When I pass the 2 tensors to nn.MSELoss I'm getting the following error message:

RuntimeError: Boolean value of Tensor with more than one value is ambiguous

Here's my code

nn.MSELoss(stack_3[0,:],stack_7[0,:])

The tensors are floats of same shape.

stack_3.shape, stack_7.shape
(torch.Size([6131, 784]), torch.Size([6131, 784]))
1

There are 1 answers

0
jodag On BEST ANSWER

nn.MSELoss is a callable class, not a function. You need to first define an instance of nn.MSELoss, then you can call it. Alternatively you can directly use torch.nn.functional.mse_loss.

from torch import nn
criterion = nn.MSELoss()
loss = criterion(stack_3[0, :], stack_7[0, :])

or

import torch.nn.functional as F
loss = F.mse_loss(stack_3[0, :], stack_7[0, :])