当前位置:   article > 正文

pytorch实现GoogLeNet_googlenet pytorch

googlenet pytorch

1.GoogLeNet简介

GoogLeNet(也称为Inception)是由谷歌公司的研究团队于2014年提出的深度卷积神经网络模型。它在ImageNet大规模视觉识别竞赛(ILSVRC)中取得了突出的成绩,在计算机视觉领域引起了广泛的关注。

GoogLeNet的名字来源于其创新的Inception模块,该模块采用多个不同尺寸的卷积核进行特征提取,并将这些特征在通道维度上进行拼接,从而能够捕捉多尺度的图像特征。相比于传统的串行结构,Inception模块的并行操作大大减少了参数数量,提高了网络的效率和性能。

除了Inception模块之外,GoogLeNet还采用了以下几种策略来改进网络的性能:

  1. 1x1卷积:通过使用1x1大小的卷积核,GoogLeNet可以在减少特征图的尺寸的同时改变通道数,从而控制网络的复杂度,并促进信息的交流和整合。

  2. 辅助分类器:GoogLeNet在中间层添加了辅助分类器,可以在训练过程中引入额外的监督信号,帮助梯度的向后传播,缓解梯度消失问题。

  3. 平均池化:在全局平均池化层中,GoogLeNet将整个特征图转换为单个数值,从而实现了对空间结构的整合,提取出更高级别的语义特征。

  4. 动态调整网络深度和宽度:GoogLeNet通过堆叠Inception模块以及调整每个模块的通道数和层数的方式,灵活地构建出不同复杂度和规模的网络模型。

GoogLeNet网络结构相对较深,但参数量相对较小,使得其具有较高的计算效率。它的设计理念和创新思路在后续的深度学习模型中得到了广泛的应用和发展。

2.GoogLeNet实现

  1. import torch
  2. from torch import nn
  3. from torch.nn import functional as F
  4. from d2l import torch as d2l
  5. from d2l.torch import evaluate_accuracy_gpu
  6. if __name__ == "__main__":
  7. def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
  8. def init_weights(m):
  9. if type(m) == nn.Linear or type(m) == nn.Conv2d:
  10. nn.init.xavier_uniform_(m.weight)
  11. net.apply(init_weights)
  12. print('training on', device)
  13. net.to(device)
  14. optimizer = torch.optim.SGD(net.parameters(), lr=lr)
  15. loss = nn.CrossEntropyLoss()
  16. timer, num_batches = d2l.Timer(), len(train_iter)
  17. for epoch in range(num_epochs):
  18. # Sum of training loss, sum of training accuracy, no. of examples
  19. metric = d2l.Accumulator(3)
  20. net.train()
  21. for i, (X, y) in enumerate(train_iter):
  22. timer.start()
  23. optimizer.zero_grad()
  24. X, y = X.to(device), y.to(device)
  25. y_hat = net(X)
  26. l = loss(y_hat, y)
  27. l.backward()
  28. optimizer.step()
  29. with torch.no_grad():
  30. metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
  31. timer.stop()
  32. train_l = metric[0] / metric[2]
  33. train_acc = metric[1] / metric[2]
  34. test_acc = evaluate_accuracy_gpu(net, test_iter)
  35. print(f'epoch {epoch},loss :{train_l:.3f}, train acc :{train_acc:.3f}, '
  36. f'test acc :{test_acc:.3f}, time :{int(timer.sum() / 60)}m{int(timer.sum() % 60)}s')
  37. print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
  38. f'test acc {test_acc:.3f}')
  39. print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
  40. f'on {str(device)}')
  41. class Inception(nn.Module):
  42. # c1--c4是每条路径的输出通道数
  43. def __init__(self, in_channels, c1, c2, c3, c4, **kwargs):
  44. super(Inception, self).__init__(**kwargs)
  45. # 线路1,单1x1卷积层
  46. self.p1_1 = nn.Conv2d(in_channels, c1, kernel_size=1)
  47. # 线路2,1x1卷积层后接3x3卷积层
  48. self.p2_1 = nn.Conv2d(in_channels, c2[0], kernel_size=1)
  49. self.p2_2 = nn.Conv2d(c2[0], c2[1], kernel_size=3, padding=1)
  50. # 线路3,1x1卷积层后接5x5卷积层
  51. self.p3_1 = nn.Conv2d(in_channels, c3[0], kernel_size=1)
  52. self.p3_2 = nn.Conv2d(c3[0], c3[1], kernel_size=5, padding=2)
  53. # 线路4,3x3最大汇聚层后接1x1卷积层
  54. self.p4_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
  55. self.p4_2 = nn.Conv2d(in_channels, c4, kernel_size=1)
  56. def forward(self, x):
  57. p1 = F.relu(self.p1_1(x))
  58. p2 = F.relu(self.p2_2(F.relu(self.p2_1(x))))
  59. p3 = F.relu(self.p3_2(F.relu(self.p3_1(x))))
  60. p4 = F.relu(self.p4_2(self.p4_1(x)))
  61. # 在通道维度上连结输出
  62. return torch.cat((p1, p2, p3, p4), dim=1)
  63. b1 = nn.Sequential(nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3),
  64. nn.ReLU(),
  65. nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
  66. b2 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=1),
  67. nn.ReLU(),
  68. nn.Conv2d(64, 192, kernel_size=3, padding=1),
  69. nn.ReLU(),
  70. nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
  71. b3 = nn.Sequential(Inception(192, 64, (96, 128), (16, 32), 32),
  72. Inception(256, 128, (128, 192), (32, 96), 64),
  73. nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
  74. b4 = nn.Sequential(Inception(480, 192, (96, 208), (16, 48), 64),
  75. Inception(512, 160, (112, 224), (24, 64), 64),
  76. Inception(512, 128, (128, 256), (24, 64), 64),
  77. Inception(512, 112, (144, 288), (32, 64), 64),
  78. Inception(528, 256, (160, 320), (32, 128), 128),
  79. nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
  80. b5 = nn.Sequential(Inception(832, 256, (160, 320), (32, 128), 128),
  81. Inception(832, 384, (192, 384), (48, 128), 128),
  82. nn.AdaptiveAvgPool2d((1, 1)),
  83. nn.Flatten())
  84. net = nn.Sequential(b1, b2, b3, b4, b5, nn.Linear(1024, 10))
  85. lr, num_epochs, batch_size = 0.1, 10, 128
  86. train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, resize=96)
  87. train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
  88. # 模型保存
  89. torch.save(net.state_dict(), f'GoogleNet/GoogleNet{num_epochs}.pth')

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

闽ICP备14008679号