[Solved] Error when calculating MSEloss: RuntimeError: Boolean value of Tensor with more than one value is ambiguous

The following error occurs when using torch.nn.MSELoss() to calculate loss:

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

Reason

In torch.nn, nn.MSELoss() is a class, not a function. Therefore, it needs to be instantiated first when using it.

Solution

Option 1: Continue to use nn.MSELoss()

The following example is from the torch official website.

import torch
import torch.nn as nn
loss = nn.MSELoss() # must be instantiated first
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()

Option 2: Use torch.nn.functional.mse_loss()

torch.nn.functional.mse_loss() is a function (official website), and its function is the same as nn.MSELoss().

import torch
import torch.nn.functional as F
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
loss = F.mse_loss(input, output)
output.backward()