LossFunction

nn.LiLoss()

  • 9_1.jpg
  • 可以取平均也可以取和

nn.MSELoss()

  • 比LiLoss()多了一个平方
  • 9_2.jpg

CrossEntropyLoss()

  • 9_3.jpg
  • 示例代码:
  1. import torch
  2. from torch.nn import L1Loss, MSELoss, CrossEntropyLoss
  3. input = torch.tensor([1,2,5],dtype=torch.float32)
  4. target = torch.tensor([1,2,3],dtype=torch.float32)
  5. input = torch.reshape(input,(1,1,1,3))
  6. target = torch.reshape(target,(1,1,1,3))
  7. # L1Loss()
  8. loss = L1Loss(reduction='sum')
  9. result = loss(input,target)
  10. # MSELoss()
  11. mse_loss = MSELoss()
  12. result_mse = mse_loss(input,target)
  13. print(result)
  14. print(result_mse)
  15. # CrossEntropyLoss()
  16. x = torch.tensor([0.1,0.2,0.3])
  17. y = torch.tensor([1])
  18. x = torch.reshape(x,(1,3))
  19. loss_cross = CrossEntropyLoss()
  20. result_cross = loss_cross(x,y)
  21. print(result_cross)

反向传播

  • 示例代码:
  1. from torch import nn
  2. import torchvision
  3. from torch.nn import Conv2d, Sequential, MaxPool2d, Flatten, Linear, CrossEntropyLoss
  4. from torch.utils.data import DataLoader
  5. dataset = torchvision.datasets.CIFAR10("./download_data",transform=torchvision.transforms.ToTensor(),
  6. train=False, download=True)
  7. dataloader = DataLoader(dataset,batch_size=1)
  8. class Liucy(nn.Module):
  9. def __init__(self):
  10. super(Liucy,self).__init__()
  11. self.modle = Sequential(
  12. Conv2d(3, 32, 5, padding=2),
  13. MaxPool2d(2),
  14. Conv2d(32, 32, 5, padding=2),
  15. MaxPool2d(2),
  16. Conv2d(32, 64, 5, padding=2),
  17. MaxPool2d(2),
  18. Flatten(),
  19. Linear(1024, 64),
  20. Linear(64, 10)
  21. )
  22. def forward(self,x):
  23. x = self.modle(x)
  24. return x
  25. liu = Liucy()
  26. cross = CrossEntropyLoss()
  27. for data in dataloader:
  28. img,label = data
  29. output = liu(img)
  30. # print(output) #最后会有十个分类
  31. result = cross(output,label)
  32. result.backward()
  33. print(result)