【Pytorch学习笔记】5.卷积神经网络

柔情只为你懂 2022-09-04 05:56 354阅读 0赞

文章目录

  • 32.卷积神经网络
  • 33.池化层&上/下采样
  • 34.批量正则化
  • 35.经典卷积网络
  • 36.残差网络
  • 37.nn.Module
  • 38.数据增强
  • 39.实战

根据龙良曲Pytorch学习视频整理,视频链接:
【计算机-AI】PyTorch学这个就够了!
(好课推荐)深度学习与PyTorch入门实战——主讲人龙良曲

32.卷积神经网络

基础知识还是得看ng

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. # 卷积层
  5. x = torch.rand(1, 1, 28, 28)
  6. layer = nn.Conv2d(1, 3, kernel_size=3, stride=1, padding=0)
  7. out = layer.forward(x)
  8. print(out.size()) # torch.Size([1, 3, 26, 26])
  9. layer = nn.Conv2d(1, 3, kernel_size=3, stride=1, padding=1)
  10. out = layer.forward(x)
  11. print(out.size()) # torch.Size([1, 3, 28, 28])
  12. layer = nn.Conv2d(1, 3, kernel_size=3, stride=2, padding=1)
  13. out = layer.forward(x)
  14. print(out.size()) # torch.Size([1, 3, 14, 14])
  15. out = layer(x) # __call__ 推荐使用,不推荐使用forward
  16. print(out.size()) # torch.Size([1, 3, 14, 14])
  17. # print(layer.weight)
  18. print(layer.weight.shape) # torch.Size([3, 1, 3, 3])
  19. print(layer.bias.shape) # torch.Size([3])
  20. w = torch.rand(16, 3, 5, 5)
  21. b = torch.rand(16)
  22. x = torch.randn(1, 3, 28, 28)
  23. out = F.conv2d(x, w, b, stride=2, padding=2)
  24. print(out.shape) # torch.Size([1, 16, 14, 14])

33.池化层&上/下采样

Pooling:feature map变小,与隔行采样(Down sample)不同

  • Max pooling
  • Avg pooling

    池化层

    x = out
    print(x.shape) # torch.Size([1, 16, 14, 14])

    layer = nn.MaxPool2d(2, stride=2)
    out = layer(x)
    print(out.shape) # torch.Size([1, 16, 7, 7])

    out = F.avg_pool2d(x, 2, stride=2)
    print(out.shape) # torch.Size([1, 16, 7, 7])

Up sample

  1. # 上采样
  2. x = out
  3. out = F.interpolate(x, scale_factor=2, mode='nearest')
  4. print(out.shape) # torch.Size([1, 16, 14, 14])

ReLU

  1. # ReLU
  2. print(x.shape) # torch.Size([1, 16, 7, 7])
  3. layer = nn.ReLU(inplace=True)
  4. out = layer(x)
  5. print(out.shape) # torch.Size([1, 16, 7, 7])
  6. out = F.relu(x)
  7. print(out.shape) # torch.Size([1, 16, 7, 7])

34.批量正则化

1d

  1. import torch
  2. import torch.nn as nn
  3. x = torch.randn(100, 16, 784)
  4. layer = nn.BatchNorm1d(16, momentum=0.1, affine=True) # affine自动更新beta、gama
  5. # layer.eval() # test时加上
  6. out = layer(x)
  7. print(layer.running_mean)
  8. print(layer.running_var)
  9. for i in range(100):
  10. out = layer(x)
  11. print(layer.running_mean)
  12. print(layer.running_var)
  13. """ tensor([-3.3207e-04, -2.9735e-04, 8.1316e-04, 9.3234e-05, 1.9049e-04, 6.9931e-04, 2.9378e-04, 3.1153e-05, 3.4325e-04, 3.2283e-04, -2.0425e-04, -4.0346e-04, 1.7246e-04, -1.9482e-04, -1.2086e-04, -8.4132e-04]) tensor([0.9999, 0.9999, 1.0002, 1.0006, 0.9997, 1.0003, 1.0000, 1.0002, 1.0003, 1.0000, 0.9998, 1.0000, 1.0005, 0.9996, 0.9997, 0.9999]) tensor([-0.0033, -0.0030, 0.0081, 0.0009, 0.0019, 0.0070, 0.0029, 0.0003, 0.0034, 0.0032, -0.0020, -0.0040, 0.0017, -0.0019, -0.0012, -0.0084]) tensor([0.9986, 0.9987, 1.0023, 1.0065, 0.9969, 1.0033, 0.9997, 1.0022, 1.0029, 1.0004, 0.9981, 0.9999, 1.0053, 0.9957, 0.9972, 0.9985]) """

layer.running_meanlayer.running_var得到的是全局的均值和方差,不是当前Batch上的,第一次只跑了一个Batch,现在还没有办法直接查看某个Batch上的这两个统计量的值。第一次只进行一次前向传播,在前向传播中来更新均值和方差的值: μ ′ = ( 1 − m ) μ + m μ t = ( 1 − 0.1 ) × 0 + 0.1 × 0.5 = 0.05 \mu ‘= (1-m) \mu + m \mu _t= ( 1 − 0.1 ) × 0 + 0.1 × 0.5 = 0.05 μ′=(1−m)μ+mμt​=(1−0.1)×0+0.1×0.5=0.05
默认动量m = 0.1, μ \mu μ是更新前的均值(初始值为0), μ t \mu_t μt​是当前batch的平均值。进行多次前向传播,均值和方差就会趋于数据真实分布

注:test时要加上layer.eval(),test不进行反向传播,即 β \beta β和 γ \gamma γ不更新

2d

  1. # 接卷积神经网络实例
  2. print(x.shape) # torch.Size([1, 16, 7, 7])
  3. layer = nn.BatchNorm2d(16)
  4. out = layer(x)
  5. print(out.shape) # torch.Size([1, 16, 7, 7])
  6. print(layer.weight.shape) # torch.Size([16])
  7. print(layer.bias.shape) # torch.Size([16])
  8. print(vars(layer)) # layer的参数

Advantages

  • Converge faster
  • Better performance
  • Robust
    stable
    larger learning rate

35.经典卷积网络

ImageNet: LeNet-5 → \rightarrow → AlexNet → \rightarrow → VGG → \rightarrow → GoogLeNet → \rightarrow → ResNet → \rightarrow → Inception

36.残差网络

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. class ResBlk(nn.Module):
  5. def __init__(self, ch_in, ch_out):
  6. self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
  7. self.bn1 = nn.BatchNorm2d(ch_out)
  8. self.conv2 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=1, padding=1)
  9. self.bn2 = nn.BatchNorm2d(ch_out)
  10. self.extra = nn.Sequential()
  11. if ch_out != ch_in:
  12. # [b, ch_in, h, w] => [b, ch_out, h, w]
  13. self.extra = nn.Sequential(
  14. nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=1),
  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. out = self.extra(x) + out
  21. return out

37.nn.Module

  • Every Layer is nn.Module
  • nn.Module nested in nn.Module
  1. embed current layers
    Linear ReLU Sigmoid Conv2d ConvTransposed2d Dropout etc.
  2. Container
    net(x)
  3. parameters
  4. modules
    modules: all nodes
    children: direct childrend
  5. to(device)
  6. save and load
    net.load_state_dict(torch.load('ckpt.mdl'))
    torch.save(net.state_dict(), 'ckpt.mdl')
  7. train / test
    net.train()
    net.eval()
  8. implement own layer

    class Flatten(nn.Module):

    1. def __init__(self):
    2. super(Flatten, self).__init__()
    3. def forward(self, input):
    4. return input.view(input.size(0), -1)

    class TestNet(nn.Module):

    1. def __init__(self):
    2. super(TestNet, self).__init__()
    3. self.net = nn.Sequential(nn.Conv2d(1, 16, stride=1, padding=1),
    4. nn.MaxPool2d(2, 2),
    5. Flatten(),
    6. nn.Linear(1*14*14, 10))
    7. def forward(self, x):
    8. return self.net(x)

38.数据增强

Limited Data

  • Small network capacity
  • Regularization
  • Data argumentation(will help but not much)

Data argumentation

  • Flip
    transforms.RandomHorizontalFlip() 随机水平翻转
    transforms.RandomVertialFlip() 随机垂直翻转
  • Rotate
    transforms.RandomRotation(15) 随机旋转,不超过15度
    transforms.RandomRotation([90, 180, 270]) 随机在指定角度中旋转
  • Scale
    transforms.Resize([32, 32])
  • Random Move & Crop
    transforms.RandomCrop([28, 28])
  • Noise
  • GAN

39.实战

main.py

  1. import torch
  2. import torch.nn as nn
  3. import torch.optim as optim
  4. from torch.utils.data import DataLoader
  5. from torchvision import transforms, datasets
  6. from Pytorch21_7_29.conv.lenet5 import Lenet5
  7. from Pytorch21_7_29.conv.resnet import ResNet18
  8. def main():
  9. batch_size = 32
  10. cifar_train = datasets.CIFAR10('cifar', train=True, transform=transforms.Compose([
  11. transforms.Resize([32, 32]),
  12. transforms.ToTensor()
  13. ]), download=True)
  14. cifar_train = DataLoader(cifar_train, batch_size=batch_size, shuffle=True)
  15. cifar_test = datasets.CIFAR10('cifar', train=False, transform=transforms.Compose([
  16. transforms.Resize([32, 32]),
  17. transforms.ToTensor(),
  18. transforms.Normalize(mean=[0.485, 0.456, 0.406],
  19. std=[0.229, 0.224, 0.225])
  20. ]), download=True)
  21. cifar_test = DataLoader(cifar_test, batch_size=batch_size, shuffle=True)
  22. x, label = iter(cifar_train).next()
  23. print("x:", x.shape, 'label:', label.shape) # x: torch.Size([32, 3, 32, 32]) label: torch.Size([32])
  24. device = torch.device('cuda')
  25. # model = Lenet5().to(device)
  26. model = ResNet18().to(device)
  27. criteon = nn.CrossEntropyLoss()
  28. optimizer = optim.Adam(model.parameters(), lr=1e-3)
  29. print(model)
  30. for epoch in range(1000):
  31. model.train()
  32. for batch_idx, (x, label) in enumerate(cifar_train):
  33. x, label = x.to(device), label.to(device)
  34. logits = model(x)
  35. # logits: [b, 10] label: [b]
  36. loss = criteon(logits, label) # tensor scalar
  37. # backward
  38. optimizer.zero_grad()
  39. loss.backward()
  40. optimizer.step()
  41. #
  42. print(epoch, loss.item())
  43. # 测试不需要构建计算图
  44. model.eval()
  45. with torch.no_grad():
  46. # test
  47. total_correct = 0
  48. total_num = 0
  49. for x, label in cifar_test:
  50. x, label = x.to(device), label.to(device)
  51. logits = model(x)
  52. pred = logits.argmax(dim=1)
  53. total_correct += torch.eq(pred, label).float().sum().item()
  54. total_num += x.size(0)
  55. acc = total_correct / total_num
  56. print(epoch, acc)
  57. if __name__ == '__main__':
  58. main()
  59. """ Lenet5( (conv_unit): Sequential( (0): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1)) (1): AvgPool2d(kernel_size=2, stride=2, padding=0) (2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1)) (3): AvgPool2d(kernel_size=2, stride=2, padding=0) ) (fc_unit): Sequential( (0): Linear(in_features=400, out_features=120, bias=True) (1): ReLU() (2): Linear(in_features=120, out_features=84, bias=True) (3): ReLU() (4): Linear(in_features=84, out_features=10, bias=True) ) (criteon): CrossEntropyLoss() ) ResNet18( (conv1): Sequential( (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(3, 3)) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) (blk1): ResBlk( (conv1): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (extra): Sequential( (0): Conv2d(64, 128, kernel_size=(1, 1), stride=(2, 2)) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (blk2): ResBlk( (conv1): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (extra): Sequential( (0): Conv2d(128, 256, kernel_size=(1, 1), stride=(2, 2)) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (blk3): ResBlk( (conv1): Conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (extra): Sequential( (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2)) (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (blk4): ResBlk( (conv1): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (extra): Sequential() ) (outlayer): Linear(in_features=512, out_features=10, bias=True) ) """

lenet5.py

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. class Lenet5(nn.Module):
  5. """ for cifar10 dataset. """
  6. def __init__(self):
  7. super(Lenet5, self).__init__()
  8. self.conv_unit = nn.Sequential(
  9. # x:[b, 3, 32, 32] => [b, 6, 28, 28]
  10. nn.Conv2d(3, 6, kernel_size=5, stride=1, padding=0),
  11. nn.AvgPool2d(kernel_size=2, stride=2, padding=0),
  12. # x:[b, 6, 14, 14] => [b, 16, 10, 10]
  13. nn.Conv2d(6, 16, kernel_size=5, stride=1, padding=0),
  14. nn.AvgPool2d(kernel_size=2, stride=2, padding=0),
  15. # x:[b, 16, 5, 5] => [b, 400]
  16. )
  17. # flatten
  18. # fc unit
  19. self.fc_unit = nn.Sequential(
  20. nn.Linear(16*5*5, 120),
  21. nn.ReLU(),
  22. nn.Linear(120, 84),
  23. nn.ReLU(),
  24. nn.Linear(84, 10)
  25. )
  26. # self.criteon = nn.MSELoss() # logistics问题使用
  27. self.criteon = nn.CrossEntropyLoss() # 一般分类问题使用
  28. def forward(self, x):
  29. """ :param x: [b, 3, 32, 32] :return: """
  30. batch_size = x.size(0)
  31. x = self.conv_unit(x)
  32. x = x.view(batch_size, -1) # -1指16*5*5
  33. logits = self.fc_unit(x)
  34. # pred = F.softmax(logits, dim=1) 交叉熵函数内包含了softmax
  35. # loss = self.criteon(logits, y)
  36. return logits
  37. def main():
  38. net = Lenet5()
  39. tmp = torch.randn(2, 3, 32, 32)
  40. out = net(tmp)
  41. print('lenet_out:', out.shape) # lenet_out: torch.Size([2, 10])
  42. if __name__ == '__main__':
  43. main()

resnet.py

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. class ResBlk(nn.Module):
  5. """ resnet block """
  6. def __init__(self, ch_in, ch_out, stride=1):
  7. """ :param ch_in: :param ch_out: """
  8. super(ResBlk, self).__init__()
  9. # we add stride support for resblk, which is distinct from tutorials.
  10. self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
  11. self.bn1 = nn.BatchNorm2d(ch_out)
  12. self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
  13. self.bn2 = nn.BatchNorm2d(ch_out)
  14. self.extra = nn.Sequential()
  15. if ch_out != ch_in:
  16. # [b, ch_in, h, w] => [b, ch_out, h, w]
  17. self.extra = nn.Sequential(
  18. nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride),
  19. nn.BatchNorm2d(ch_out)
  20. )
  21. def forward(self, x):
  22. """ :param x: [b, ch, h, w] :return: """
  23. out = F.relu(self.bn1(self.conv1(x)))
  24. out = self.bn2(self.conv2(out))
  25. # short cut
  26. out = self.extra(x) + out
  27. out = F.relu(out)
  28. return out
  29. class ResNet18(nn.Module):
  30. def __init__(self):
  31. super(ResNet18, self).__init__()
  32. self.conv1 = nn.Sequential(
  33. nn.Conv2d(3, 64, kernel_size=3, stride=3, padding=0),
  34. nn.BatchNorm2d(64)
  35. )
  36. # followed 4 blocks
  37. # [b, 64, h, w] => [b, 128, h, w]
  38. self.blk1 = ResBlk(64, 128, stride=2)
  39. # [b, 128, h, w] => [b, 256, h, w]
  40. self.blk2 = ResBlk(128, 256, stride=2)
  41. # [b, 256, h, w] => [b, 512, h, w]
  42. self.blk3 = ResBlk(256, 512, stride=2)
  43. # [b, 512, h, w] => [b, 1024, h, w]
  44. self.blk4 = ResBlk(512, 512, stride=2)
  45. self.outlayer = nn.Linear(512*1*1, 10)
  46. def forward(self, x):
  47. """ :param x: :return: """
  48. x = F.relu(self.conv1(x))
  49. x = self.blk1(x)
  50. x = self.blk2(x)
  51. x = self.blk3(x)
  52. x = self.blk4(x)
  53. # print("after_conv:", x.shape) # torch.Size([32, 512, 2, 2])
  54. # [b, 512, h, w] => [b, 512, 1, 1]
  55. x = F.adaptive_avg_pool2d(x, [1, 1])
  56. # print("after_pool:", x.shape) # torch.Size([32, 512, 1, 1])
  57. x = x.view(x.size(0), -1)
  58. x = self.outlayer(x)
  59. return x
  60. def main():
  61. blk = ResBlk(64, 128, stride=2)
  62. tmp = torch.randn(2, 64, 32, 32)
  63. out = blk(tmp)
  64. print("block:", out.shape) # torch.Size([2, 128, 16, 16])
  65. x = torch.randn(2, 3, 32, 32)
  66. model = ResNet18()
  67. out = model(x)
  68. print("resnet:", out.shape) # torch.Size([2, 10])
  69. if __name__ == '__main__':
  70. main()

发表评论

表情:
评论列表 (有 0 条评论,354人围观)

还没有评论,来说两句吧...

相关阅读

    相关 pytorch-神经网络基础

    卷积神经网络基础 本节我们介绍卷积神经网络的基础概念,主要是卷积层和池化层,并解释填充、步幅、输入通道和输出通道的含义。 二维卷积层 本节介绍的是最常见的二维卷积