PyTorch MSELoss 均方误差 用法

PyTorch MSELoss 均方误差 用法

MSE:Mean Squared Error(均方误差
含义:均方误差,是预测值与真实值之差的平方和的平均值,即:

loss= nn.MSELoss(reduction=’mean’)

loss = nn.MSELoss()

import torch
from torch import nn
 
loss = nn.MSELoss()

y_pre = torch.Tensor([[1, 2, 3],
                      [2, 1, 3],
                      [3, 1, 2]])

# requires_grad参数指定是否记录对Tensor的操作以便计算梯度
y_pre.requires_grad_(True)

y_label = torch.Tensor([[1, 0, 0],
                        [0, 1, 0],
                        [0, 0, 1]])

output = loss(y_pre, y_label)
output.backward() # 反向传播
print('Loss: ', output.item())

输出:

Loss:  4.111111164093018

 

import torch
import torch.nn as nn
 
y_pre = torch.tensor([[1, 2, 3], [2, 1, 3], [3, 1, 2]], dtype=torch.float)
 
y_label = torch.tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=torch.float)
 
loss_fn = torch.nn.MSELoss(reduction='mean')
loss = loss_fn(y_pre.float(), y_label.float())
print(loss)
print(loss.item())
tensor(4.1111)
4.111111164093018

发表回复

您的电子邮箱地址不会被公开。