当前位置:   article > 正文

4--卷积神经网络(LeNet)_x, y = x.to(device), y.to(device)

x, y = x.to(device), y.to(device)

        LeNet,它是最早发布的卷积神经网络之一,被广泛用于自动取款机(ATM)机中,帮助识别处理支票的数字。 总体来看,LeNet(LeNet-5)由两个部分组成:

  • 卷积编码器:由两个卷积层组成;

  • 全连接层密集块:由三个全连接层组成。

        每个卷积块中的基本单元是一个卷积层、一个sigmoid激活函数和平均汇聚层。每个卷积层使用5×5卷积核和一个sigmoid激活函数。这些层将输入映射到多个二维特征输出,通常同时增加通道的数量。第一卷积层有6个输出通道,而第二个卷积层有16个输出通道。每个2×2池操作(步幅2)通过空间下采样将维数减少4倍。卷积的输出形状由批量大小、通道数、高度、宽度决定。

        将这个四维输入转换成全连接层所期望的二维输入。这里的二维表示的第一个维度索引小批量中的样本,第二个维度给出每个样本的平面向量表示。LeNet的稠密块有三个全连接层,分别有120、84和10个输出。因为在执行分类任务,所以输出层的10维对应于最后输出结果的数量。

        用深度学习框架实现该模型,只需要实例化一个Sequential块并将需要的层连接在一起。具体代码如下:

  1. import torch
  2. from torch import nn
  3. from d2l import torch as d2l
  4. net = nn.Sequential(
  5. nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),
  6. nn.AvgPool2d(2),#默认kernel_size=stride=2
  7. nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),
  8. nn.AvgPool2d(2),
  9. nn.Flatten(),
  10. nn.Linear(16 * 5 * 5, 120), nn.Sigmoid(),
  11. nn.Linear(120, 84), nn.Sigmoid(),
  12. nn.Linear(84, 10))

        在数据集fashion_mnist上的运行结果,(epochs=10  lr=0.9):

         对LeNet模型进行修改,将激活函数从sigmoid改为relu(这里其实是可能存在过拟合的)(lr=0.09,epochs=10):

完整代码:

  1. !pip install git+https://github.com/d2l-ai/d2l-zh@release # installing d2l
  2. !pip install matplotlib_inline
  3. !pip install matplotlib==3.0.0
  4. import torch
  5. from torch import nn
  6. from d2l import torch as d2l
  7. net = nn.Sequential(nn.Conv2d(1,6,kernel_size=5,padding=2),nn.ReLU(),
  8. nn.AvgPool2d(2),nn.Conv2d(6,16,kernel_size=5),nn.ReLU(),
  9. nn.AvgPool2d(2),nn.Flatten(),
  10. nn.Linear(16*5*5,120),nn.ReLU(),
  11. nn.Linear(120,84),nn.ReLU(),
  12. nn.Linear(84,10)
  13. )
  14. batch_size = 256
  15. train_iter,test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
  16. def evaluate_accuracy_gpu(net,data_iter,device=None):
  17. if isinstance(net,nn.Module):
  18. net.eval()## 设置为评估模式 表示接下来要开始训练了
  19. if not device:
  20. device = next(iter(net.parameters())).device
  21. metric = d2l.Accumulator(2)
  22. with torch.no_grad():
  23. for X,y in data_iter:
  24. if isinstance (X,list):
  25. x = [x.to(device)for x in X]
  26. else:
  27. X = X.to(device)
  28. y = y.to(device)
  29. metric.add(d2l.accuracy(net(X),y),y.numel())
  30. return metric[0]/metric[1]
  31. def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
  32. """用GPU训练模型(在第六章定义)"""
  33. def init_weights(m):
  34. if type(m) == nn.Linear or type(m) == nn.Conv2d:
  35. nn.init.xavier_uniform_(m.weight)
  36. net.apply(init_weights)
  37. print('training on', device)
  38. net.to(device)
  39. optimizer = torch.optim.SGD(net.parameters(), lr=lr)
  40. loss = nn.CrossEntropyLoss()
  41. animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
  42. legend=['train loss', 'train acc', 'test acc'])
  43. timer, num_batches = d2l.Timer(), len(train_iter)
  44. for epoch in range(num_epochs):
  45. # 训练损失之和,训练准确率之和,样本数
  46. metric = d2l.Accumulator(3)
  47. net.train()
  48. for i, (X, y) in enumerate(train_iter):
  49. timer.start()
  50. optimizer.zero_grad()
  51. X, y = X.to(device), y.to(device)
  52. y_hat = net(X)
  53. l = loss(y_hat, y)
  54. l.backward()
  55. optimizer.step()
  56. with torch.no_grad():
  57. metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
  58. timer.stop()
  59. train_l = metric[0] / metric[2]
  60. train_acc = metric[1] / metric[2]
  61. if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
  62. animator.add(epoch + (i + 1) / num_batches,
  63. (train_l, train_acc, None))
  64. test_acc = evaluate_accuracy_gpu(net, test_iter)
  65. animator.add(epoch + 1, (None, None, test_acc))
  66. print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
  67. f'test acc {test_acc:.3f}')
  68. print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
  69. f'on {str(device)}')
  70. lr,num_epochs = 0.01,30
  71. train_ch6(net,train_iter,test_iter,num_epochs,lr,d2l.try_gpu())
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号