torch.nn 里的 loss function 衡量误差。
loss衡量的是 实际神经网络输出output与真实结果target的差距,越小越好。
作用:
1.实际输出和目标之间的差距
2.更新输出提供依据(反向传播):卷积核参数提供了梯度grad。反向传播时,每一个更新的参数有对应的梯度。优化过程中对梯度参数进行优化。达到loss降低。
一,L1Loss
①求平均:
#求平均方式:
import torch
from torch.nn import L1Loss, MSELoss, CrossEntropyLoss
#计算时要求数据类型是浮点数,不能是整型的long
inputs = torch.tensor([1, 6, 3], dtype=torch.float32)
targets = torch.tensor([1, 5, 8], dtype=torch.float32)
#修改一下维度1行3列
inputs = torch.reshape(inputs, (1, 1, 1, 3))
targets = torch.reshape(targets, (1, 1, 1, 3))
#求平均(1-1+6-5+8-3)/3 = 2
loss = L1Loss()
result = loss(inputs, targets)
print(result)
#求和方式:上述代码添加(1-1+6-5+8-3)=6
loss = L1Loss(reduction='sum')
print(result)
二。求平方差MSELOSS
import torch
from torch.nn import L1Loss, MSELoss, CrossEntropyLoss
#计算时要求数据类型是浮点数,不能是整型的long
inputs = torch.tensor([1, 2, 3], dtype=torch.float32)
targets = torch.tensor([1, 2, 5], dtype=torch.float32)
#修改一下维度1行3列
inputs = torch.reshape(inputs, (1, 1, 1, 3))
targets = torch.reshape(targets, (1, 1, 1, 3))
loss_mse = MSELoss()
result_mse = loss_mse(inputs, targets)
print(result_mse)
三CrossEntropyLoss()适应于训练分类的问题,有C个类别。
x = torch.tensor([0.1, 0.2, 0.3])
y = torch.tensor([1])
x = torch.reshape(x, (1, 3))
loss_cross = CrossEntropyLoss()
result_cross = loss_cross(x, y)
print(result_cross)
在之间写的神经网络用到Loss Function(损失函数)
import torch
import torchvision
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential, CrossEntropyLoss
from torch.utils.data import DataLoader
dataset = torchvision.datasets.CIFAR10(root="./dataset", train=False, transform=torchvision.transforms.ToTensor(),
download=True)
# 加载数据集
dataloader = DataLoader(dataset, batch_size=64)
class net(nn.Module):
def __init__(self):
super(net, self).__init__()
self.model1 = Sequential(
Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
MaxPool2d(kernel_size=2),
Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
MaxPool2d(kernel_size=2),
Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
MaxPool2d(kernel_size=2),
Flatten(),
Linear(in_features=1024, out_features=64),
Linear(in_features=64, out_features=10)
)
def forward(self, x):
x = self.model1(x)
return x
loss = CrossEntropyLoss()
wang = net()
for data in dataloader:
img, target = data
outputs = wang(img)
result = loss(outputs, target)
result.backward()
print(result)
backward反向传播
result.backward()
计算出每一个节点参数的梯度。