LeNet卷积神经网络——pytorch版

发布时间 2023-08-06 14:41:53作者: 不像话
import torch
from torch import nn
from d2l import torch as d2l

class Reshape(torch.nn.Module):
    def forward(self,x):
        # 批量大小默认,输出通道为1
        return x.view(-1,1,28,28)

net = torch.nn.Sequential(
    # 28+4-5+1=28输出通道为6
    Reshape(),nn.Conv2d(1,6,kernel_size=5,padding=2),nn.Sigmoid(),
    # 28/2=14通道是6
    nn.AvgPool2d(kernel_size=2,stride=2),
    # 14-5+1=10输出通道是16
    nn.Conv2d(6,16,kernel_size=5),nn.Sigmoid(),
    # 10/2=5通道是16
    nn.AvgPool2d(kernel_size=2,stride=2),nn.Flatten(),
    # 上面是卷积层,下面是两个隐藏层的多层感知机
    # 扁平化处理后16*5x5=400,输出通道120
    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)
# Sequential中每一层做迭代
for layer in net:
    x = layer(x)
    print(layer.__class__.__name__,'output shape: \t',x.shape)


print('**********************************************************')
# LeNet在Fashion-MNIST数据集上的表现
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):
    """使用GPU计算模型在数据集上的精度"""
    if isinstance(net,torch.nn.Module):
        net.eval()
        if not device:
            # 如果没有指定device则查看第一个parameteres所在的device
            device = next(iter(net.parameters())).device
    # 定义一个累加器
    metric = d2l.Accumulator(2)
    for X,y in data_iter:
        if isinstance(X,list):
            # 如果是一个list则依次挪到device上
            X=[x.to(device) for x in X]
        else:
            X=X.to(device)
        # y也挪到设备上
        y=y.to(device)
        metric.add(d2l.accuracy(net(X),y),y.numel())
    # 分类正确的元素个数/整个y大小
    return metric[0]/metric[1]

def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
    """用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()
            optimizer.zero_grad()
            X, y = X.to(device), y.to(device)
            y_hat = net(X)
            l = loss(y_hat, y)
            l.backward()
            optimizer.step()
            with torch.no_grad():
                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(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)}')

if __name__ == '__main__':
    lr, num_epochs = 0.9, 10
    train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())