## 1. LeNet简介

LeNet网络 [1] 由时任AT&T贝尔实验室的研究员Yann LeCun提出，可以被看作是卷积神经网络的开山之作。之所以选用LeNet作为尝试复现的第一个神经网络，是因为该网络本身的结构简单清晰，便于理解。作为早期成功应用于银行和邮政系统的实用型卷积神经网络，LeNet的结构足够经典，其中很多思想传承至今。因此，LeNet作为深度网络代码复现的一个经典案例，十分恰当。

## 2. LeNet实现

#### LeNet的网络搭建如下：

```import torch
from torch import nn
from d2l import torch as s2l
class Reshape(torch.nn.Module):
def forward(self, x):
return x.view(-1,1,28,28)
net = torch.nn.Sequential(Reshape(),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2,stride=2),
nn.Conv2d(6,16,kernel_size=5),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2,stride=2),
nn.Flatten(),
nn.Linear(16*5*5, 120),
nn.Sigmoid(),
nn.Linear(120, 84),
nn.Sigmoid(),
nn.Linear(84, 10))
X = torch.rand(size = (1,1,28,28),dtype=torch.float32)
for layer in net:
X = layer(X)
print(layer.__class__.__name__,'output shape:\t',X.shape)```

Reshape output shape:        torch.Size([1, 1, 28, 28])

Conv2d output shape:          torch.Size([1, 6, 28, 28])

Sigmoid output shape:         torch.Size([1, 6, 28, 28])

AvgPool2d output shape:     torch.Size([1, 6, 14, 14])

Conv2d output shape:          torch.Size([1, 16, 10, 10])

Sigmoid output shape:         torch.Size([1, 16, 10, 10])

AvgPool2d output shape:     torch.Size([1, 16, 5, 5])

Flatten output shape:           torch.Size([1, 400])

Linear output shape:            torch.Size([1, 120])

Sigmoid output shape:         torch.Size([1, 120])

Linear output shape:            torch.Size([1, 84])

Sigmoid output shape:         torch.Size([1, 84])

Linear output shape:            torch.Size([1, 10])

```batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size = batch_size)```

```def evaluate_accuracy_gpu(net, data_iter,device=None):
if isinstance(net, torch.nn.Module):
net.eval()
if not device:
device = next(iter(net.parameters())).device
metric = d2l.Accumulator(2)
for X,y in data_iter:
if isinstance(X,list):
X = [x.to(device) for x in X]
else:
X = X.to(device)
y = y.to(device)
return metric[0]/metric[1]```

```import torch
from torch import nn
from d2l import torch as d2l
class Reshape(torch.nn.Module):
def forward(self, x):
return x.view(-1,1,28,28)
def evaluate_accuracy_gpu(net, data_iter,device=None):
if isinstance(net, torch.nn.Module):
net.eval()
if not device:
device = next(iter(net.parameters())).device
metric = d2l.Accumulator(2)
for X,y in data_iter:
if isinstance(X,list):
X = [x.to(device) for x in X]
else:
X = X.to(device)
y = y.to(device)
return metric[0]/metric[1]
def train_ch6(net, train_iter, test_iter, num_epochs, lr ,device):#lr: learning rate
"""train a model woth GPU"""
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
print('training on', device)
net.to(device)
optimizer = torch.optim.SGD(net.parameters(),lr=lr)
loss = nn.CrossEntropyLoss()
animator = d2l.Animator(xlabel = 'epoch', xlim = [1, num_epochs],
legend = ['train loss', 'train acc', 'test acc'])
timer, num_batches = d2l.Timer(),len(train_iter)
for epoch in range(num_epochs):
metric = d2l.Accumulator(3)
net.train()
for i, (X, y) in enumerate(train_iter):
timer.start()
X, y = X.to(device), y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
optimizer.step()
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
timer.stop()
train_l = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
if(i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1)/ num_batches,(train_l, train_acc, None))
test_acc = evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
print('Epoch:', epoch)
print(f'loss {train_l:.3f}, train acc {train_acc:,.3f},' f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec' f'on {str(device)}')
print(f'loss {train_l:.3f}, train acc {train_acc:,.3f},' f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs/timer.sum():.1f} examples/sec' f'on {str(device)}')
print('finished')
def main():
net = torch.nn.Sequential(Reshape(),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(6, 16, kernel_size=5),
nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.Linear(16 * 5 * 5, 120),
nn.Sigmoid(),
nn.Linear(120, 84),
nn.Sigmoid(),
nn.Linear(84, 10))
batch_size = 256
lr, num_epochs = 0.9, 10
train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
if __name__ == '__main__':
main()```

## 3. 实验结果

training on cuda:0

Epoch: 0

loss 2.317, train acc 0.102,test acc 0.100

174566.9 examples/secon cuda:0

Epoch: 1

loss 1.383, train acc 0.459,test acc 0.580

139471.3 examples/secon cuda:0

Epoch: 2

loss 0.857, train acc 0.661,test acc 0.652

115809.0 examples/secon cuda:0

Epoch: 3

loss 0.718, train acc 0.716,test acc 0.701

99568.9 examples/secon cuda:0

Epoch: 4

loss 0.648, train acc 0.748,test acc 0.752

87336.1 examples/secon cuda:0

Epoch: 5

loss 0.590, train acc 0.770,test acc 0.776

77399.1 examples/secon cuda:0

Epoch: 6

loss 0.550, train acc 0.787,test acc 0.781

69605.1 examples/secon cuda:0

Epoch: 7

loss 0.515, train acc 0.800,test acc 0.793

63230.5 examples/secon cuda:0

Epoch: 8

loss 0.485, train acc 0.816,test acc 0.799

57836.1 examples/secon cuda:0

Epoch: 9

loss 0.459, train acc 0.829,test acc 0.761

53456.0 examples/secon cuda:0

loss 0.459, train acc 0.829,test acc 0.761

53456.0 examples/secon cuda:0

## Reference

[1] LeCun Y, Bottou L, Bengio Y, et al. Gradient-based learning applied to document recognition[J]. Proceedings of the IEEE, 1998, 86(11): 2278-2324.