当前位置:   article > 正文

损失函数和反向传播

损失函数和反向传播

1. 损失函数的基础

  1. import torch
  2. from torch.nn import L1Loss
  3. from torch import nn
  4. inputs = torch.tensor([1, 2, 3], dtype=torch.float32)
  5. targets = torch.tensor([1, 2, 5], dtype=torch.float32)
  6. inputs = torch.reshape(inputs, (1, 1, 1, 3))
  7. targets = torch.reshape(targets, (1, 1, 1, 3))
  8. loss_l1 = L1Loss(reduction='sum') #默认为mean
  9. result_l1 = loss_l1(inputs,targets)
  10. loos_mse = nn.MSELoss()
  11. result_mes = loos_mse(inputs, targets)
  12. print(result_l1, result_mes)
  13. x = torch.tensor([0.1,0.2,0.3])
  14. y = torch.tensor([1])
  15. x = torch.reshape(x,(1,3)) #(N,C)
  16. loss_cross = nn.CrossEntropyLoss() #注意输入输出的维度 多看官网
  17. result_cross = loss_cross(x,y)
  18. print(result_cross)

2. 损失函数的运用

  1. import torchvision
  2. from torch import nn
  3. from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
  4. from torch.utils.data import DataLoader
  5. dataset = torchvision.datasets.CIFAR10('./dataset',train=False, transform=torchvision.transforms.ToTensor())
  6. dataloader = DataLoader(dataset, batch_size=1)
  7. class Tudui(nn.Module):
  8. def __init__(self):
  9. super().__init__()
  10. self.model1 = Sequential(
  11. Conv2d(3, 32, 5, padding=2),
  12. MaxPool2d(kernel_size=2),
  13. Conv2d(32, 32, 5, padding=2),
  14. MaxPool2d(2),
  15. Conv2d(32, 64, 5, padding=2),
  16. MaxPool2d(2),
  17. Flatten(),
  18. Linear(1024, 64),
  19. Linear(64, 10)
  20. )
  21. def forward(self, x):
  22. x = self.model1(x)
  23. return x
  24. loss = nn.CrossEntropyLoss()
  25. tudui = Tudui()
  26. for data in dataloader:
  27. imgs, targets = data
  28. outputs = tudui(imgs)
  29. result_loss = loss(outputs, targets)
  30. print(result_loss)
  31. result_loss.backward() #梯度
  32. print('ok')
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/242322
推荐阅读
相关标签
  

闽ICP备14008679号