nn.MESLoss:
- def mse_loss(x, y, reduction='mean'):
- dif = np.square(x - y)
- if reduction == 'mean':
- return np.mean(dif)
- elif reduction == 'sum':
- return np.sum(dif)
- return dif
- #--可使用下方代码测试:
- a=np.array([[1, 2], [3, 4]],dtype=np.float32)
- b=np.array([[3, 5], [8, 6]],dtype=np.float32)
-
- result=mse_loss(a,b,reduction='sum')
- print("result",result)
torch.nn.MSELoss(reduction='none')实际返回的只是上方代码中的dif向量,测试代码:
- a_t = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
- b_t = torch.tensor([[3, 5], [8, 6]], dtype=torch.float32)
- loss_fn1 = torch.nn.MSELoss(reduction='none')
- loss1 = loss_fn1(a_t, b_t)
- print("loss1",loss1)
- a_t = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
- b_t = torch.tensor([[3, 5], [8, 6]], dtype=torch.float32)
- result2=torch.dist(a_t,b_t,2)
- print("result2",result2)