优化器

  • step方法:利用梯度对参数进行更新
  • 示例代码:
  1. import torch
  2. from torch import nn
  3. import torchvision
  4. from torch.nn import Conv2d, Sequential, MaxPool2d, Flatten, Linear, CrossEntropyLoss
  5. from torch.utils.data import DataLoader
  6. dataset = torchvision.datasets.CIFAR10("./download_data",transform=torchvision.transforms.ToTensor(),
  7. train=False, download=True)
  8. dataloader = DataLoader(dataset,batch_size=1)
  9. class Liucy(nn.Module):
  10. def __init__(self):
  11. super(Liucy,self).__init__()
  12. self.modle = Sequential(
  13. Conv2d(3, 32, 5, padding=2),
  14. MaxPool2d(2),
  15. Conv2d(32, 32, 5, padding=2),
  16. MaxPool2d(2),
  17. Conv2d(32, 64, 5, padding=2),
  18. MaxPool2d(2),
  19. Flatten(),
  20. Linear(1024, 64),
  21. Linear(64, 10)
  22. )
  23. def forward(self,x):
  24. x = self.modle(x)
  25. return x
  26. liu = Liucy()
  27. cross = CrossEntropyLoss()
  28. # 设置优化器
  29. optim = torch.optim.SGD(liu.parameters(),lr=0.01) #lr为学习速率
  30. for i in range(10):
  31. lost_value = 0.0
  32. for data in dataloader:
  33. img,label = data
  34. output = liu(img)
  35. # print(output) #最后会有十个分类
  36. result = cross(output,label)
  37. optim.zero_grad()
  38. result.backward()
  39. optim.step()
  40. lost_value = lost_value + result
  41. print(lost_value)