当前位置:   article > 正文

深度学习pytorch——基于CIFAR-10数据集的Lenet5、Resnet的实战(持续更新)

深度学习pytorch——基于CIFAR-10数据集的Lenet5、Resnet的实战(持续更新)

主函数main:

  1. import torch
  2. from torch.utils.data import DataLoader
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. import torch.optim as optim
  6. from torchvision import datasets,transforms
  7. # from Lenet5 import Lenet5
  8. from Resnet import ResNet18
  9. def main():
  10. batchsz = 128 # how to make sure?
  11. # load train data
  12. cifar_train = datasets.CIFAR10('cifar', True, transform=transforms.Compose([
  13. transforms.Resize((32, 32)),
  14. transforms.ToTensor(),
  15. transforms.Normalize(mean=[0.485, 0.456, 0.406],
  16. std=[0.229, 0.224, 0.225])
  17. ]), download=True)
  18. cifar_train = DataLoader(cifar_train, batch_size=batchsz, shuffle=True)
  19. cifar_test = datasets.CIFAR10('cifar', False, transform=transforms.Compose([
  20. transforms.Resize((32, 32)),
  21. transforms.ToTensor(),
  22. transforms.Normalize(mean=[0.485, 0.456, 0.406],
  23. std=[0.229, 0.224, 0.225])
  24. ]), download=True)
  25. cifar_test = DataLoader(cifar_test, batch_size=batchsz, shuffle=True)
  26. x, label = iter(cifar_train).__next__() # ?
  27. print('x:',x.shape,'label:',label.shape)
  28. device = torch.device('cuda')
  29. # model = Lenet5().to(device)
  30. model = ResNet18().to(device)
  31. criteon = nn.CrossEntropyLoss().to(device)
  32. optimizer = optim.Adam(model.parameters(), lr=1e-3)
  33. print(model)
  34. for epoch in range(1000):
  35. model.train()
  36. for batch_idx, (x, label) in enumerate(cifar_train):
  37. x, label = x.to(device), label.to(device)
  38. logits = model(x)
  39. loss = criteon(logits, label)
  40. optimizer.zero_grad()
  41. loss.backward()
  42. optimizer.step()
  43. # test
  44. model.eval()
  45. with torch.no_grad(): # test has no user for caculating grad.
  46. total_correct = 0
  47. total_num = 0
  48. for x, label in cifar_test:
  49. x, label = x.to(device), label.to(device)
  50. logits = model(x)
  51. pred = logits.argmax(dim=1)
  52. correct = torch.eq(pred, label).float().sum().item()
  53. total_correct += correct
  54. total_num += x.size(0)
  55. acc = total_correct/total_num
  56. print(epoch, acc)
  57. if __name__ == '__main__':
  58. main()

Lenet5类:

  1. import torch
  2. from torch import nn
  3. from torch.nn import functional as F
  4. class Lenet5(nn.Module):
  5. def __init__(self):
  6. super(Lenet5, self).__init__()
  7. self.conv_unit = nn.Sequential(
  8. nn.Conv2d(3, 16, kernel_size=5, stride=1, padding=0),
  9. nn.MaxPool2d(kernel_size=2, stride=2, padding=0),
  10. nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=0),
  11. nn.MaxPool2d(kernel_size=2, stride=2, padding=0),
  12. )
  13. # flatten
  14. self.fc_unit = nn.Sequential(
  15. nn.Linear(32*5*5, 32),
  16. nn.ReLU(),
  17. # nn.Linear(120, 84),
  18. # nn.ReLU(),
  19. nn.Linear(32, 10)
  20. )
  21. tmp = torch.randn(2, 3, 32, 32)
  22. out = self.conv_unit(tmp)
  23. print('con out:', out.shape)
  24. # con out: torch.Size([2, 32, 5, 5])
  25. def forward(self, x): # indent make no mistake
  26. batchsz = x.size(0)
  27. x = self.conv_unit(x)
  28. x = x.view(batchsz, 32 * 5 * 5)
  29. logits = self.fc_unit(x)
  30. return logits
  31. def main():
  32. net = Lenet5()
  33. tmp = torch.randn(2, 3, 32, 32) # ?
  34. out = net(tmp)
  35. print('lenet out:', out.shape)
  36. if __name__ == '__main__':
  37. main()

Resnet类:

  1. import torch
  2. from torch import nn
  3. from torch.nn import functional as F
  4. class ResBlk(nn.Module):
  5. def __init__(self, ch_in, ch_out, stride=1):
  6. super(ResBlk, self).__init__()
  7. self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
  8. self.bn1 = nn.BatchNorm2d(ch_out)
  9. self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
  10. self.bn2 = nn.BatchNorm2d(ch_out)
  11. self.extra = nn.Sequential()
  12. if ch_out != ch_in:
  13. self.extra = nn.Sequential(
  14. nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride),
  15. nn.BatchNorm2d(ch_out)
  16. )
  17. def forward(self, x):
  18. out = F.relu(self.bn1(self.conv1(x)))
  19. out = self.bn2(self.conv2(out))
  20. # short cut.
  21. out = self.extra(x) + out # aim:x is the same of out.
  22. out = F.relu(out)
  23. return out # the result of the final prediction
  24. class ResNet18(nn.Module):
  25. def __init__(self):
  26. super(ResNet18, self).__init__()
  27. self.conv1 = nn.Sequential(
  28. nn.Conv2d(3, 64, kernel_size=3, stride=3, padding=0),
  29. nn.BatchNorm2d(64)
  30. )
  31. self.blk1 = ResBlk(64, 128, stride=2)
  32. self.blk2 = ResBlk(128, 256, stride=2)
  33. self.blk3 = ResBlk(256, 512, stride=2)
  34. self.blk4 = ResBlk(512, 512, stride=2)
  35. self.outlayer = nn.Linear(512*1*1, 10)
  36. def forward(self, x):
  37. x = F.relu(self.conv1(x))
  38. x = self.blk1(x)
  39. x = self.blk2(x)
  40. x = self.blk3(x)
  41. x = self.blk4(x)
  42. x = F.adaptive_avg_pool2d(x, [1, 1])
  43. x = x.view(x.size(0), -1)
  44. x = self.outlayer(x)
  45. return x
  46. def main():
  47. blk = ResBlk(64, 128, stride=4)
  48. tmp = torch.randn(2, 64, 32, 32)
  49. out = blk(tmp)
  50. print('block:', out.shape)
  51. x = torch.randn(2, 3, 32, 32)
  52. model = ResNet18()
  53. out = model(x)
  54. print('resnet:', out.shape)
  55. if __name__ == '__main__':
  56. main()

想的时候都是困难,做的时候才是答案。 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/377089
推荐阅读
相关标签
  

闽ICP备14008679号