pytorch实现Lenet

1.Lenet网络简介

        LeNet是一种经典的卷积神经网络(Convolutional Neural Network,CNN),也被称为LeNet-5。它由Yann LeCun等人在1998年提出,是用于手写数字识别任务的早期深度学习模型。

LeNet网络结构相对简单,主要由卷积层、池化层和全连接层组成。它的主要特点是通过多层卷积和池化操作对输入进行特征提取,并使用全连接层进行分类。具体来说,LeNet的结构如下:

  1. 输入层:接受图像输入。
  2. 卷积层:使用卷积核对输入进行卷积操作,并应用非线性激活函数(如sigmoid或tanh)。
  3. 池化层:对卷积输出进行下采样操作,通常使用平均池化或最大池化。
  4. 卷积层和池化层:可以重复几次,以提取更高级别的特征。
  5. 全连接层:将池化层的输出连接到一个或多个全连接层,最后输出预测结果。
  6. 输出层:根据任务需求确定输出层的激活函数,如softmax用于多类别分类问题。

LeNet在当时取得了很好的效果,奠定了卷积神经网络在计算机视觉领域的基础。它的设计和思想对之后更复杂的深度学习模型的发展有着重要影响。

值得一提的是,虽然LeNet网络在手写数字识别任务上表现出色,但在处理更复杂的图像任务(如物体识别)时可能效果较差。随着技术的发展,更深层次的卷积神经网络(如VGG、ResNet、Inception等)被提出并取得了显著的进展。

2.Lenet网络实现

        代码是参考某站博主“跟李沐学ai”,重写了d2l中的train_ch6方法,将测试集和训练集精度直接输出。

import torch
from d2l.torch import evaluate_accuracy_gpu
from torch import nn
from d2l import torch as d2l
import cv2


def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
    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()
    timer, num_batches = d2l.Timer(), len(train_iter)
    for epoch in range(num_epochs):
        # Sum of training loss, sum of training accuracy, no. of examples
        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]

        test_acc = evaluate_accuracy_gpu(net, test_iter)
        print(f'epoch {epoch},loss :{train_l:.3f}, train acc :{train_acc:.3f}, '
              f'test acc :{test_acc:.3f}, time :{timer.sum() / 60}m{int(timer.sum() % 60)}s')
    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__":
    # 模型训练
    net = nn.Sequential(nn.Conv2d(1, 6, kernel_size=5, padding=2), 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))
    # net.load_state_dict(torch.load('lenet/lenet15.pth'))
    batch_size = 256
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
    lr, num_epochs = 0.9, 50
    train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())

    # 模型保存
    torch.save(net.state_dict(), f'Lenet/Lenet{num_epochs}.pth')


    # 加载模型
    # net = nn.Sequential(nn.Conv2d(1, 6, kernel_size=5, padding=2), 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))
    # net.load_state_dict(torch.load('lenet.pth'))

    # 预测图片预处理
    def preprocess(image_path):
        image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2GRAY)
        image = torch.tensor(cv2.resize(image, (28, 28)), dtype=torch.float32).unsqueeze(0).unsqueeze(0)
        return image


    # 预测图片
    def predict(image_path):
        image = preprocess(image_path)
        # TODO 若是训练完直接预测,由于网络是在GPU上,因此需要将输入张量转到GPU上
        image = image.cuda()
        with torch.no_grad():
            outputs = net(image)
            _, predicted = torch.max(outputs)
        # 这里的class_label需要自己修改
        class_label = d2l.get_fashion_mnist_labels(predicted)
        return class_label


    image_path = 'Lenet/777.png'  # 待预测的图像路径
    predicted_class = predict(image_path)
    print('预测类别:', predicted_class)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安心不心安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值