pytorch 卷积神经网络笔记

忘是亡心i 2023-06-10 03:21 373阅读 0赞

pytorch 神经网络基本笔记中描述了神经网络中计算逻辑是什么,下面的例子来自官方,可以运行在cpu上。今天开始了解卷积神经网络是什么。
1 卷积
最容易理解的对卷积(convolution)的解释,虽然没有他说的那么容易理解,不过可以清楚卷积的意义:加权叠加.卷积神经网络之卷积计算、作用与思想这篇文章说的是将滤波器作为特征模板在图片上方匹配。那么数学意义是什么呢?
从深度学习实战教程(四):卷积神经网络,我找到卷积的计算公式: 其中 w b w_b wb​为偏置bias, f f f为激活函数,计算过程是feature_map=image*filter,拿着这个filter在图片上扫描,得到feature_map
a i , j = f ( ∑ m = 0 2 ∑ n = 0 2 w m , n ∗ x i + m , j + n + w b ) a_{i,j}=f(\sum_{m=0}^2\sum_{n=0}^2w_{m,n}*x_{i+m,j+n}+w_b) ai,j​=f(m=0∑2​n=0∑2​wm,n​∗xi+m,j+n​+wb​)
从这个公式可以看出卷积是将图片与卷积核中逐行对应位置的乘积之和。这个矩阵的乘法是不一样的,矩阵是行乘以列,而这个里是行×行
再看看别怕,”卷积”其实很简单
2 定义网络
定义了一个二维卷积,nn.Conv2d卷积从这个里面的说明,我知道了下面的语句,我定义了一个输入通道为3,输出通道为6,卷积核3×3的卷积层模型,通道也就是维度。RGB图像是3通道这个我可以理解,为什么要输出通道为6呢。

  1. self.conv1 = nn.Conv2d(3, 6, 5)
  2. self.conv2 = nn.Conv2d(6, 16, 5)

在工程化,我们一般不会自己定义网络,都使用成熟的网络模型,毕竟别人是科学家,而我是搞工程应用的。有分工,定位要清晰。
详解CNN卷积神经网络中描述常见的神经网络,M表示卷积、池化层的数量,而K则表示全连接层的数量,那么这个M、K怎么设定呢,他们靠什么调整出来的数量呢?

  1. INPUT -> [[CONV -> RELU]*N -> POOL?]*M -> [FC -> RELU]*K -> FC

再看看卷积神经网络的卷积核大小、个数,卷积层数如何确定呢?,这些跟学习率一样,都是超参,这里就要论经验的重要性了。
3 池化
CNN学习笔记:池化层,池化的目的很明确就是降采样,吴恩达深度学习笔记(79)-池化层讲解(Pooling layers)中描述Max Pooing最大池化最为常用,那么它的算法是什么呢?深度学习之卷积神经网络(六)中描述:MaxPooling就是去一定范围的最大值。
4 全连接
CNN入门讲解-为什么要有最后一层全连接?,全连接是一个分类器,卷积块为“特征提取器”而 NN 块为“决策分类器“,这个我觉得说明容易理解。
CNN 入门讲解:什么是全连接层(Fully Connected Layer)?这篇文章只是将cnn的识别用图来描述而已,还是特征提取到决策分类的工程化流程。浅谈线性多分类分类器(全连接层、SVM、Softmax classifier等),既然是分类那当是线性回归了。
4.1 Dropout
pytorch之Dropout,Dropout用于了防止或减轻过拟合而使用的函数,它一般用在全连接层.
pytorch Dropout过拟合,这篇文章中的代码,可以看到dropout作用的变化。
Dropout为何能防止过拟合?dropout是指在深度学习网络的训练过程中,对于神经网络单元,按照一定的概率将其暂时从网络中丢弃。故在随机梯度下降过程中,每个mini-batch都是在训练不同的网络。
虽然pytorch 神经网络基本笔记中介绍了通过风险函数和正则化防止过拟合,这里有多了个dropout,这篇文章讲的很好,我总结一下数学公式参考神经网络优化算法:Dropout、梯度消失/爆炸、Adam优化算法,一篇就够了!

5 官方实例

  1. # 1. 将数据加载到numpy数组里,然后将数组专程torch.*Tensor
  2. # 1.1 对于图片,有Pillow,OpenCV等包可以使用
  3. # 1.2 对于音频,有scipy和librosa等包可以使用
  4. # 1.3 对于文本,不管是原生的python还是基于cpython的文本,可以使用NLTK和SpaSy
  5. # 2 计算机视觉包torchvision,其中包含了针对Imagenet,CIFAR10,MINIST等数据集的数据加载器data loaders
  6. # 还有对图片数据变形的操作,即torchvision.datasets,torch.utils.data.Dataloader
  7. import time
  8. import torch
  9. import torchvision
  10. import torchvision.transforms as transforms
  11. import matplotlib.pyplot as plt
  12. import numpy as np
  13. # 定义卷积神经网络
  14. import torch.nn as nn
  15. import torch.nn.functional as F
  16. # 定义损失函数和优化器
  17. import torch.optim as optim
  18. transform = transforms.Compose(
  19. [transforms.ToTensor(),
  20. transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
  21. trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
  22. trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
  23. testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
  24. testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
  25. classes = ('plane', 'car', 'bird', 'cat',
  26. 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
  27. # 定义卷积网络
  28. class Net(nn.Module):
  29. def __init__(self):
  30. super(Net,self).__init__()
  31. self.conv1 = nn.Conv2d(3, 6, 5)
  32. self.pool = nn.MaxPool2d(2, 2)
  33. self.conv2 = nn.Conv2d(6, 16, 5)
  34. # 全连接层,16*5*5个节点连接到120个节点上
  35. self.fc1 = nn.Linear(16 * 5 * 5, 120)
  36. # 全连接层,将120个节点将120个节点连接到84个节点上
  37. self.fc2 = nn.Linear(120, 84)
  38. # 全连接层,将84个节点连接到10个节点上
  39. self.fc3 = nn.Linear(84, 10)
  40. def forward(self, x):
  41. x = self.pool(F.relu(self.conv1(x)))
  42. x = self.pool(F.relu(self.conv2(x)))
  43. x = x.view(-1, 16 * 5 * 5)
  44. x = F.relu(self.fc1(x))
  45. x = F.relu(self.fc2(x))
  46. x = self.fc3(x)
  47. return x
  48. # 随机获取训练图片
  49. dataiter = iter(trainloader)
  50. images, labels = dataiter.next()
  51. FMT='%Y-%m-%d %H:%M:%S'
  52. net = Net()
  53. # 交叉熵损失
  54. criterion = nn.CrossEntropyLoss()
  55. # 随机梯度下降SGD
  56. # (使用标准动量优化算法momentum)
  57. optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
  58. print('训练开始时间:%s' % time.strftime(FMT,time.localtime(time.time())))
  59. for epoch in range(2): # loop over the dataset multiple times
  60. running_loss = 0.0
  61. for i, data in enumerate(trainloader, 0):
  62. # get the inputs
  63. inputs, labels = data
  64. # zero the parameter gradients
  65. # 将梯度置为0,也就是把loss关于weight的导数变成0
  66. optimizer.zero_grad()
  67. # forward + backward + optimize
  68. outputs = net(inputs)
  69. loss = criterion(outputs, labels)
  70. loss.backward()
  71. optimizer.step()
  72. # print statistics
  73. running_loss += loss.item()
  74. if i % 2000 == 1999: # print every 2000 mini-batches
  75. print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
  76. running_loss = 0.0
  77. print('训练结束时间:%s' % time.strftime(FMT,time.localtime(time.time())))
  78. print('Finished Training')
  79. print('总体预测开始时间:%s' % time.strftime(FMT,time.localtime(time.time())))
  80. correct = 0
  81. total = 0
  82. with torch.no_grad():
  83. for data in testloader:
  84. images, labels = data
  85. outputs = net(images)
  86. _, predicted = torch.max(outputs.data, 1)
  87. total += labels.size(0)
  88. correct += (predicted == labels).sum().item()
  89. print('总体预测结束时间:%s' % time.strftime(FMT,time.localtime(time.time())))
  90. print('Accuracy of the network on the 10000 test images: %d %%' % (
  91. 100 * correct / total))
  92. print('每类预测开始时间:%s' % time.strftime(FMT,time.localtime(time.time())))
  93. class_correct = list(0. for i in range(10))
  94. class_total = list(0. for i in range(10))
  95. with torch.no_grad():
  96. for data in testloader:
  97. images, labels = data
  98. outputs = net(images)
  99. _, predicted = torch.max(outputs, 1)
  100. c = (predicted == labels).squeeze()
  101. for i in range(4):
  102. label = labels[i]
  103. class_correct[label] += c[i].item()
  104. class_total[label] += 1
  105. for i in range(10):
  106. print('Accuracy of %5s : %2d %%' % (
  107. classes[i], 100 * class_correct[i] / class_total[i]))
  108. print('每类预测结束时间:%s' % time.strftime(FMT,time.localtime(time.time())))
  109. Files already downloaded and verified
  110. Files already downloaded and verified
  111. 训练开始时间:2019-10-22 11:32:03
  112. [1, 2000] loss: 2.199
  113. [1, 4000] loss: 1.863
  114. [1, 6000] loss: 1.665
  115. [1, 8000] loss: 1.589
  116. [1, 10000] loss: 1.533
  117. [1, 12000] loss: 1.493
  118. [2, 2000] loss: 1.405
  119. [2, 4000] loss: 1.365
  120. [2, 6000] loss: 1.354
  121. [2, 8000] loss: 1.346
  122. [2, 10000] loss: 1.303
  123. [2, 12000] loss: 1.294
  124. 训练结束时间:2019-10-22 11:33:49
  125. Finished Training
  126. 总体预测开始时间:2019-10-22 11:33:49
  127. 总体预测结束时间:2019-10-22 11:33:53
  128. Accuracy of the network on the 10000 test images: 53 %
  129. 每类预测开始时间:2019-10-22 11:33:53
  130. Accuracy of plane : 53 %
  131. Accuracy of car : 81 %
  132. Accuracy of bird : 8 %
  133. Accuracy of cat : 30 %
  134. Accuracy of deer : 60 %
  135. Accuracy of dog : 32 %
  136. Accuracy of frog : 65 %
  137. Accuracy of horse : 75 %
  138. Accuracy of ship : 66 %
  139. Accuracy of truck : 55 %
  140. 每类预测结束时间:2019-10-22 11:33:57

发表评论

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

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

相关阅读

    相关 pytorch-神经网络基础

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

    相关 神经网络-神经网络

    卷积神经网络最基本的操作:卷积、池化、全连接 1、卷积操作 什么是卷积操作?我们先定义一个目的,让卷积神经网络去识别数字 “17” 和字母 “L”。 有三张图片,

    相关 神经网络

    [卷积神经网络][Link 1]     在上篇中介绍的输入层与隐含层的连接称为全连接,如果输入数据是小块图像,比如8×8,那这种方法是可行的,但是如果输入图像是96×96,