当前位置:   article > 正文

笔记:现代卷积神经网络之VGG

笔记:现代卷积神经网络之VGG

本文为李沐老师《动手学深度学习》笔记小结,用于个人复习并记录学习历程,适用于初学者

神经网络架构设计的模块化

AlexNet证明深层神经网络卓有成效,但它没有提供一个通用的模板来指导后续的研究人员设计新的网络。 在下面的几个章节中,我们将介绍一些常用于设计深层神经网络的启发式概念。

与芯片设计中工程师从放置晶体管到逻辑元件再到逻辑块的过程类似,神经网络架构的设计也逐渐变得更加抽象。研究人员开始从单个神经元的角度思考问题,发展到整个层,现在又转向块,重复层的模式。

使用块的想法首先出现在牛津大学的视觉几何组(visual geometry group)的VGG网络中。通过使用循环和子程序,可以很容易地在任何现代深度学习框架的代码中实现这些重复的架构。

VGG架构

VGG块

经典卷积神经网络的基本组成部分是下面的这个序列:

  1. 带填充以保持分辨率的卷积层;
  2. 非线性激活函数,如ReLU;
  3. 汇聚层,如最大汇聚层。

而一个VGG块与之类似,由一系列卷积层组成,后面再加上用于空间下采样的最大汇聚层。在最初的VGG论文中 ,作者了带有3×3卷积核、填充为1(保持高度和宽度)的卷积层,和带有2×2汇聚窗口、步幅为2(每个块后的分辨率减半)的最大汇聚层。

  1. import torch
  2. from torch import nn
  3. def vgg_block(num_convs, in_channels, out_channels):
  4. layers = []
  5. for _ in range(num_convs):
  6. layers.append(nn.Conv2d(in_channels, out_channels,
  7. kernel_size=3, padding=1))
  8. layers.append(nn.ReLU())
  9. in_channels = out_channels
  10. layers.append(nn.MaxPool2d(kernel_size=2,stride=2))
  11. return nn.Sequential(*layers)
VGG网络

与AlexNet、LeNet一样,VGG网络可以分为两部分:第一部分主要由卷积层和汇聚层组成,第二部分由全连接层组成。

原始VGG网络有5个卷积块,其中前两个块各有一个卷积层,后三个块各包含两个卷积层。 第一个模块有64个输出通道,每个后续模块将输出通道数量翻倍,直到该数字达到512。由于该网络使用8个卷积层和3个全连接层,因此它通常被称为VGG-11。

这里我们构建比书上还要小的网络用于训练。 

  1. def vgg(conv_arch):
  2. conv_blks = []
  3. in_channels = 1
  4. # 卷积层部分
  5. for (num_convs, out_channels) in conv_arch:
  6. conv_blks.append(vgg_block(num_convs, in_channels, out_channels))
  7. in_channels = out_channels
  8. return nn.Sequential(
  9. *conv_blks, nn.Flatten(),
  10. # 全连接层部分
  11. nn.Linear(out_channels * 5 * 5, 1024), nn.ReLU(), nn.Dropout(0.5),
  12. nn.Linear(1024, 128), nn.ReLU(), nn.Dropout(0.5),
  13. nn.Linear(128, 10))
  14. conv_arch = ((1, 64), (1, 128), (2, 256), (2, 512), (2, 512)) #这里(22562指重复两次
  15. net = vgg(conv_arch)

接下来,我们将构建一个高度和宽度为160的单通道数据样本,以[观察每个层输出的形状]。

  1. X = torch.randn(size=(1, 1, 160, 160))
  2. for blk in net:
  3. X = blk(X)
  4. print(blk.__class__.__name__,'output shape:\t',X.shape)

输出:

Sequential output shape:	 torch.Size([1, 64, 80, 80])
Sequential output shape:	 torch.Size([1, 128, 40, 40])
Sequential output shape:	 torch.Size([1, 256, 20, 20])
Sequential output shape:	 torch.Size([1, 512, 10, 10])
Sequential output shape:	 torch.Size([1, 512, 5, 5])
Flatten output shape:	 torch.Size([1, 12800])
Linear output shape:	 torch.Size([1, 1024])
ReLU output shape:	 torch.Size([1, 1024])
Dropout output shape:	 torch.Size([1, 1024])
Linear output shape:	 torch.Size([1, 128])
ReLU output shape:	 torch.Size([1, 128])
Dropout output shape:	 torch.Size([1, 128])
Linear output shape:	 torch.Size([1, 10])

训练模型

缩小模型

拿Fashion-MNIST数据集,我们可以再次减小通道数。

  1. ratio = 4
  2. small_conv_arch = [(pair[0], pair[1] // ratio) for pair in conv_arch]
  3. net = vgg(small_conv_arch)
  4. X = torch.randn(size=(1, 1, 160, 160))
  5. for blk in net:
  6. X = blk(X)
  7. print(blk.__class__.__name__,'output shape:\t',X.shape)

输出:

Sequential output shape:	 torch.Size([1, 16, 80, 80])
Sequential output shape:	 torch.Size([1, 32, 40, 40])
Sequential output shape:	 torch.Size([1, 64, 20, 20])
Sequential output shape:	 torch.Size([1, 128, 10, 10])
Sequential output shape:	 torch.Size([1, 128, 5, 5])
Flatten output shape:	 torch.Size([1, 3200])
Linear output shape:	 torch.Size([1, 1024])
ReLU output shape:	 torch.Size([1, 1024])
Dropout output shape:	 torch.Size([1, 1024])
Linear output shape:	 torch.Size([1, 128])
ReLU output shape:	 torch.Size([1, 128])
Dropout output shape:	 torch.Size([1, 128])
Linear output shape:	 torch.Size([1, 10])
预备工作
  1. from IPython import display
  2. import torchvision
  3. from torch.utils import data
  4. from torchvision import transforms
  5. import matplotlib.pyplot as plt
  6. def load_data_fashion_mnist(batch_size, resize=None):
  7. """下载Fashion-MNIST数据集,然后将其加载到内存中"""
  8. trans = [transforms.ToTensor()]
  9. if resize:
  10. trans.insert(0, transforms.Resize(resize))
  11. trans = transforms.Compose(trans)
  12. mnist_train = torchvision.datasets.FashionMNIST(
  13. root="../data", train=True, transform=trans, download=0)
  14. mnist_test = torchvision.datasets.FashionMNIST(
  15. root="../data", train=False, transform=trans, download=0)
  16. return (data.DataLoader(mnist_train, batch_size, shuffle=True,
  17. num_workers=get_dataloader_workers()),
  18. data.DataLoader(mnist_test, batch_size, shuffle=False,
  19. num_workers=get_dataloader_workers()))
  20. def get_dataloader_workers():
  21. """使用4个进程来读取数据"""
  22. return 4
  23. batch_size = 128
  24. train_iter, test_iter = load_data_fashion_mnist(batch_size, resize=160)
  25. def accuracy(y_hat, y): #@save
  26. """计算预测正确的数量"""
  27. if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
  28. y_hat = y_hat.argmax(axis=1) #找出输入张量(tensor)中最大值的索引
  29. cmp = y_hat.type(y.dtype) == y
  30. return float(cmp.type(y.dtype).sum())
  31. class Accumulator: #@save
  32. """在n个变量上累加"""
  33. def __init__(self, n):
  34. self.data = [0.0] * n
  35. def add(self, *args):
  36. self.data = [a + float(b) for a, b in zip(self.data, args)]
  37. def reset(self):
  38. self.data = [0.0] * len(self.data)
  39. def __getitem__(self, idx):
  40. return self.data[idx]
  41. import matplotlib.pyplot as plt
  42. from matplotlib_inline import backend_inline
  43. def use_svg_display():
  44. """使⽤svg格式在Jupyter中显⽰绘图"""
  45. backend_inline.set_matplotlib_formats('svg')
  46. def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
  47. """设置matplotlib的轴"""
  48. axes.set_xlabel(xlabel)
  49. axes.set_ylabel(ylabel)
  50. axes.set_xscale(xscale)
  51. axes.set_yscale(yscale)
  52. axes.set_xlim(xlim)
  53. axes.set_ylim(ylim)
  54. if legend:
  55. axes.legend(legend)
  56. axes.grid()
  57. class Animator: #@save
  58. """在动画中绘制数据"""
  59. def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
  60. ylim=None, xscale='linear', yscale='linear',
  61. fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
  62. figsize=(3.5, 2.5)):
  63. # 增量地绘制多条线
  64. if legend is None:
  65. legend = []
  66. use_svg_display()
  67. self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize)
  68. if nrows * ncols == 1:
  69. self.axes = [self.axes, ]
  70. # 使用lambda函数捕获参数
  71. self.config_axes = lambda: set_axes(
  72. self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
  73. self.X, self.Y, self.fmts = None, None, fmts
  74. def add(self, x, y):
  75. # 向图表中添加多个数据点
  76. if not hasattr(y, "__len__"):
  77. y = [y]
  78. n = len(y)
  79. if not hasattr(x, "__len__"):
  80. x = [x] * n
  81. if not self.X:
  82. self.X = [[] for _ in range(n)]
  83. if not self.Y:
  84. self.Y = [[] for _ in range(n)]
  85. for i, (a, b) in enumerate(zip(x, y)):
  86. if a is not None and b is not None:
  87. self.X[i].append(a)
  88. self.Y[i].append(b)
  89. self.axes[0].cla()
  90. for x, y, fmt in zip(self.X, self.Y, self.fmts):
  91. self.axes[0].plot(x, y, fmt)
  92. self.config_axes()
  93. display.display(self.fig)
  94. display.clear_output(wait=True)
  95. def evaluate_accuracy_gpu(net, data_iter, device=None): #@save
  96. """使用GPU计算模型在数据集上的精度"""
  97. if isinstance(net, nn.Module):
  98. net.eval() # 设置为评估模式
  99. if not device:
  100. device = next(iter(net.parameters())).device
  101. # 正确预测的数量,总预测的数量
  102. metric = Accumulator(2)
  103. with torch.no_grad():
  104. for X, y in data_iter:
  105. if isinstance(X, list):
  106. # BERT微调所需的(之后将介绍)
  107. X = [x.to(device) for x in X]
  108. else:
  109. X = X.to(device)
  110. y = y.to(device)
  111. metric.add(accuracy(net(X), y), y.numel())
  112. return metric[0] / metric[1]
  113. import time
  114. class Timer: #@save
  115. """记录多次运行时间"""
  116. def __init__(self):
  117. self.times = []
  118. self.start()
  119. def start(self):
  120. """启动计时器"""
  121. self.tik = time.time()
  122. def stop(self):
  123. """停止计时器并将时间记录在列表中"""
  124. self.times.append(time.time() - self.tik)
  125. return self.times[-1]
  126. def avg(self):
  127. """返回平均时间"""
  128. return sum(self.times) / len(self.times)
  129. def sum(self):
  130. """返回时间总和"""
  131. return sum(self.times)
  132. def cumsum(self):
  133. """返回累计时间"""
  134. return np.array(self.times).cumsum().tolist()
  135. def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
  136. """用GPU训练模型(在第六章定义)"""
  137. def init_weights(m):
  138. if type(m) == nn.Linear or type(m) == nn.Conv2d:
  139. nn.init.xavier_uniform_(m.weight)
  140. net.apply(init_weights)
  141. print('training on', device)
  142. net.to(device)
  143. optimizer = torch.optim.SGD(net.parameters(), lr=lr)
  144. loss = nn.CrossEntropyLoss()
  145. animator = Animator(xlabel='epoch', xlim=[1, num_epochs],
  146. legend=['train loss', 'train acc', 'test acc'])
  147. timer, num_batches = Timer(), len(train_iter)
  148. for epoch in range(num_epochs):
  149. # 训练损失之和,训练准确率之和,样本数
  150. metric = Accumulator(3)
  151. net.train()
  152. for i, (X, y) in enumerate(train_iter):
  153. timer.start()
  154. optimizer.zero_grad()
  155. X, y = X.to(device), y.to(device)
  156. y_hat = net(X)
  157. l = loss(y_hat, y)
  158. l.backward()
  159. optimizer.step()
  160. with torch.no_grad():
  161. metric.add(l * X.shape[0], accuracy(y_hat, y), X.shape[0])
  162. timer.stop()
  163. train_l = metric[0] / metric[2]
  164. train_acc = metric[1] / metric[2]
  165. if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
  166. animator.add(epoch + (i + 1) / num_batches,
  167. (train_l, train_acc, None))
  168. test_acc = evaluate_accuracy_gpu(net, test_iter)
  169. animator.add(epoch + 1, (None, None, test_acc))
  170. print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
  171. f'test acc {test_acc:.3f}')
  172. print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
  173. f'on {str(device)}')
  174. def try_gpu(i=0): #@save
  175. """如果存在,则返回gpu(i),否则返回cpu()"""
  176. if torch.cuda.device_count() >= i + 1:
  177. return torch.device(f'cuda:{i}')
  178. return torch.device('cpu')
模型训练
  1. lr, num_epochs, batch_size = 0.05, 10, 128
  2. train_iter, test_iter = load_data_fashion_mnist(batch_size, resize=160)
  3. begin = time.time()
  4. train_ch6(net, train_iter, test_iter, num_epochs, lr, try_gpu())
  5. end = time.time()
  6. print(end - begin)

这个结果可以说相当不错,对比我完全没调整参数的AlexNet,不仅训练速度更快,并且效果更好。

 小结

  • VGG-11使用可复用的卷积块构造网络。不同的VGG模型可通过每个块中卷积层数量和输出通道数量的差异来定义。
  • 块的使用导致网络定义的非常简洁。使用块可以有效地设计复杂的网络。
  • 在VGG论文中,Simonyan和Ziserman尝试了各种架构。特别是他们发现深层且窄的卷积(即3×3)比较浅层且宽的卷积更有效。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/866095
推荐阅读
相关标签
  

闽ICP备14008679号