当前位置: 首页 > article >正文

深度学习-图像处理篇1.3pytorch神经网络例子

在这里插入图片描述
batch:一批·图像·数量
官方例子

#model
import torch.nn as nn
import torch.nn.functional as F


class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()
        self.conv1 = nn.Conv2d(3,16,5)
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(16, 32, 5)
        self.pool2 = nn.MaxPool2d(2, 2)
        self.fc1 = nn.Linear(32*5*5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))    # input(3, 32, 32) output(16, 28, 28)
        x = self.pool1(x)            # output(16, 14, 14)
        x = F.relu(self.conv2(x))    # output(32, 10, 10)
        x = self.pool2(x)            # output(32, 5, 5)
        x = x.view(-1, 32*5*5)       # output(32*5*5)
        x = F.relu(self.fc1(x))      # output(120)
        x = F.relu(self.fc2(x))      # output(84)
        x = self.fc3(x)              # output(10)
        return x



import torch
import torchvision
import torch.nn as nn
from model import LeNet
import torch.optim as optim
import torchvision.transforms as transforms


def main():
    transform = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

    # 50000张训练图片
    # 第一次使用时要将download设置为True才会自动去下载数据集
    train_set = torchvision.datasets.CIFAR10(root='./data', train=True,
                                             download=True, transform=transform)
    train_loader = torch.utils.data.DataLoader(train_set, batch_size=36,
                                               shuffle=True, num_workers=0)

    # 10000张验证图片
    # 第一次使用时要将download设置为True才会自动去下载数据集
    val_set = torchvision.datasets.CIFAR10(root='./data', train=False,
                                           download=True, transform=transform)
    val_loader = torch.utils.data.DataLoader(val_set, batch_size=5000,
                                             shuffle=False, num_workers=0)
    val_data_iter = iter(val_loader)
    val_image, val_label = next(val_data_iter)
    
    classes = ('plane', 'car', 'bird', 'cat',
               'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

    net = LeNet()
    loss_function = nn.CrossEntropyLoss()#损失函数
    optimizer = optim.Adam(net.parameters(), lr=0.001)#优化器

    for epoch in range(5):  # loop over the dataset multiple times

        running_loss = 0.0
        for step, data in enumerate(train_loader, start=0):
            # get the inputs; data is a list of [inputs, labels]
            inputs, labels = data

            # zero the parameter gradients
            optimizer.zero_grad()#将历史损失梯度清零
            # forward + backward + optimize
            outputs = net(inputs)
            loss = loss_function(outputs, labels)
            loss.backward()#反向传播
            optimizer.step()

            # print statistics
            running_loss += loss.item()
            if step % 500 == 499:    # print every 500 mini-batches
                with torch.no_grad():#接下来计算过程中不计算损失梯度,更好分配内存
                    outputs = net(val_image)  # [batch, 10]
                    predict_y = torch.max(outputs, dim=1)[1]
                    accuracy = torch.eq(predict_y, val_label).sum().item() / val_label.size(0)

                    print('[%d, %5d] train_loss: %.3f  test_accuracy: %.3f' %
                          (epoch + 1, step + 1, running_loss / 500, accuracy))
                    running_loss = 0.0

    print('Finished Training')

    save_path = './Lenet.pth'
    torch.save(net.state_dict(), save_path)


if __name__ == '__main__':
    main()
import torch
import torchvision.transforms as transforms
from PIL import Image

from model import LeNet


def main():
    transform = transforms.Compose(
        [transforms.Resize((32, 32)),
         transforms.ToTensor(),
         transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

    classes = ('plane', 'car', 'bird', 'cat',
               'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

    net = LeNet()
    net.load_state_dict(torch.load('Lenet.pth'))

    # im = Image.open('cat.jpg')

    im = Image.open('airplane.png').convert('RGB')  # 转换为RGB图像
    im = transform(im)  # [C, H, W]
    im = torch.unsqueeze(im, dim=0)  # [N, C, H, W]

    with torch.no_grad():
        outputs = net(im)
        predict = torch.max(outputs, dim=1)[1].numpy()
        predict = predict.item()  # 从数组中提取标量值
    print(classes[int(predict)])


if __name__ == '__main__':
    main()

测试结果
在这里插入图片描述


http://www.kler.cn/a/314453.html

相关文章:

  • vwmare虚拟机繁忙的解决办法
  • MySQL数据库:SQL语言入门 【上】(学习笔记)
  • WorkFlow源码剖析——Communicator之TCPServer(下)
  • vue2面试题6|[2024-11-11]
  • 如何使用 OpenSubtitles.com 下载字幕?以及如何用 SRT to TXT Converter 转换字幕格式!
  • 数据库MySQL索引详解
  • 【数据仓库】数据仓库层次化设计
  • vue3(整合版)
  • docker入门总结(附错误处理,持续更新)
  • 如何使用 Python 的 sqlite3 模块操作 SQLite 数据库?
  • mac命令行分卷压缩与合并
  • 长列表加载性能优化
  • python画图1
  • springboot实战学习(6)(用户模块的登录认证)(初识令牌)(JWT)
  • python:给1个整数,你怎么判断是否等于2的幂次方?
  • java.nio.ByteBuffer的 capacity, limit, position, mark
  • 如何打造高效的远程开发团队:最佳实践与挑战
  • 大话C++:第11篇 类的定义与封装
  • Redis——redispluspls库通用命令以及String类型相关接口使用
  • 每日一题--打印闰年
  • 如何使用 Python 连接 MySQL 数据库?什么是 ORM(对象关系映射),如何使用
  • fasterRCNN模型实现飞机类目标检测
  • 果蔬识别系统架构+流程图
  • Hadoop的安装
  • JVM 调优篇7 调优案例2-元空间的优化解决
  • 使用Diskgenius系统迁移