计算MSEloss时报错:RuntimeError: Boolean value of Tensor with more than one value is ambiguous

使用torch.nn.MSELoss()计算loss时发生如下错误:

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

原因

在torch.nn中,nn.MSELoss()是一个class,不是函数。因此在使用的时候需要先将其实例化。
计算MSEloss时报错:RuntimeError: Boolean value of Tensor with more than one value is ambiguous_第1张图片

解决方案

方案一:继续使用nn.MSELoss()

下述例子来自torch官网。

import torch
import torch.nn as nn
loss = nn.MSELoss() # 必须先进行实例化
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()

方案二:使用torch.nn.functional.mse_loss()

torch.nn.functional.mse_loss()是一个函数(官网),作用与nn.MSELoss()是一样的。
计算MSEloss时报错:RuntimeError: Boolean value of Tensor with more than one value is ambiguous_第2张图片

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()

你可能感兴趣的:(Pytorch学习,深度学习,pytorch)