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

训练一个分类器

目录

  • 一、关于数据
  • 二、训练分类器
    • 1、加载并标准化CIFAR10
    • 2、定义卷积网络
    • 3、定义损失函数和优化器
    • 4、训练网络
    • 5、在测试数据上测试神经网络
  • 三、在GPU上训练

一、关于数据

通常,当你需要处理图像、文本、音频或视频数据时,你可以使用标准Python包来将数据加载到NumPy数组中。然后将数组转化为torch.*Tensor

  • 对于图像,可以使用包Pillow,OpenCV
  • 对于音频,可以使用包scipy,librosa
  • 对于文本,可以使用NLTK,SpaCy

特别是对于视觉,我们创建了一个名为torchvision的包,它包含用于常见数据集的数据加载器,如ImagenetCIFAR10MNIST等,以及用于图像的数据转换器,即torchvision.datasetstorch.utils.data.DataLoader

对于本教程,我们将使用CIFAR10数据集。它包含10个类: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’。图片的大小为3x32x32,即尺寸为32×32像素的3通道彩色图像。

二、训练分类器

我们将会依次执行以下步骤:

  • 使用torchvision加载和标准化CIFAR10训练和测试数据集
  • 定义卷积神经网络
  • 定义损失函数
  • 在训练数据上训练网络
  • 在测试数据上测试网络

1、加载并标准化CIFAR10

import torch import torchvision import torchvision.transforms as transforms

torchvision数据集的输出是范围[0,1]的PILImage图像。 我们将它们转换为归一化范围的tensor,[-1,1]。

transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

输出:

Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz Extracting ./data/cifar-10-python.tar.gz to ./data Files already downloaded and verified

让我们展示一些训练图片:

import matplotlib.pyplot as plt import numpy as np # functions to show an image def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show() # get some random training images dataiter = iter(trainloader) images, labels = dataiter.next() # show images imshow(torchvision.utils.make_grid(images)) # print labels print(' '.join('%5s' % classes[labels[j]] for j in range(4)))

输出:

frog ship cat plane

2、定义卷积网络

import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net()

3、定义损失函数和优化器

让我们使用分类交叉熵损失函数和带动量的SGD。

import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

4、训练网络

我们只需循环遍历数据迭代器,并将输入提供给神经网络并进行优化。

for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 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 = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 print('Finished Training')

输出:

[1, 2000] loss: 2.169 [1, 4000] loss: 1.808 [1, 6000] loss: 1.659 [1, 8000] loss: 1.553 [1, 10000] loss: 1.488 [1, 12000] loss: 1.455 [2, 2000] loss: 1.379 [2, 4000] loss: 1.346 [2, 6000] loss: 1.320 [2, 8000] loss: 1.305 [2, 10000] loss: 1.275 [2, 12000] loss: 1.262 Finished Training

5、在测试数据上测试神经网络

我们已经在训练数据集上训练了两次。 但我们需要检查神经网络是否已经学到了什么。

我们将通过预测神经网络输出的类标签来检查这一点,并根据真实情况进行检查。 如果预测正确,我们将样本添加到正确预测列表中。

我们首先展示测试集中的一些图片:

dataiter = iter(testloader) images, labels = dataiter.next() # print images imshow(torchvision.utils.make_grid(images)) print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

输出:

GroundTruth: cat ship ship plane

现在我们来看一看神经网络认为这些图片是什么。outputs是10个类的能量。 一个类的能量越高,网络认为图像是特定类的可能性越大。 那么,让我们得到最高能量的索引:

outputs = net(images) _, predicted = torch.max(outputs, 1) print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))

输出:

Predicted: cat plane plane ship

查看神经网络在整个数据集上的表现:

correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total))

输出:

Accuracy of the network on the 10000 test images: 54 %

查看表现最好的类和最坏的类:

class_correct = list(0. for i in range(10)) class_total = list(0. for i in range(10)) with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs, 1) c = (predicted == labels).squeeze() for i in range(4): label = labels[i] class_correct[label] += c[i].item() class_total[label] += 1 for i in range(10): print('Accuracy of %5s : %2d %%' % ( classes[i], 100 * class_correct[i] / class_total[i]))

输出:

Accuracy of plane : 46 % Accuracy of car : 63 % Accuracy of bird : 50 % Accuracy of cat : 37 % Accuracy of deer : 40 % Accuracy of dog : 51 % Accuracy of frog : 70 % Accuracy of horse : 48 % Accuracy of ship : 76 % Accuracy of truck : 64 %

三、在GPU上训练

如果我们有可用的CUDA,我们首先将我们的设备定义为第一个可见的cuda设备:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Assuming that we are on a CUDA machine, this should print a CUDA device: print(device)

输出:

cuda:0

本节的其余部分假定设备是CUDA设备。

然后这些方法将递归遍历所有模块并将其参数和缓冲区转换为CUDA tensor:

net.to(device)

还必须将每一步的输入和目标发送到GPU:

inputs, labels = data[0].to(device), data[1].to(device)
http://www.cnnetsun.cn/news/3710418.html

相关文章:

  • SMS凭据中枢架构与落地路线图:四阶段推进
  • 【计算机JAVA毕业设计案例】基于 B/S 架构的养老机构智能管理系统 康养中心老人档案与医疗服务管理系统(程序+文档+讲解+定制)
  • BZOJ3003 LED题解(状压DP+最短路+差分)
  • ajax 详解(GET,POST方式传输以其封装)
  • 超强盘点!2026年适配各学科的AI论文工具,精准输出不套壳
  • 实测揭秘!2026 年适配多学科的 AI 论文写作工具究竟有哪些
  • C#转C++实战:内存管理、RAII与面向对象编程核心差异解析
  • Claude Opus登顶AA-Briefcase:AI智能体如何突破复杂知识工作瓶颈
  • Adobe-GenP 3.0:终极Adobe全家桶免费激活指南
  • 告别演讲超时!这款智能PPT计时器让你精准掌控演示时间
  • CPO-RBF分类算法:优化RBF神经网络的故障检测方法
  • 9种字重完整指南:Outfit字体免费开源几何无衬线字体库
  • 为什么Input Leap是跨设备控制的终极解决方案:3分钟掌握多电脑无缝切换
  • 090、YOLOv8改进实战:Focal Loss与Varifocal Loss在YOLOv8中的集成与效果对比
  • NBM5100A与PIC18F86K90在低功耗物联网中的协同设计
  • PyQt5桌面开发:从环境搭建到性能优化全指南
  • 微信/QQ/TIM防撤回神器:揭秘消息永久保存的三大核心技术
  • 企业高效经营分析会:数据驱动决策与执行闭环
  • OpenCode Opus 5 AI编程助手:安装配置与核心功能实战指南
  • 银河麒麟桌面任务栏配置指南:从基础布局到高级定制
  • 幻兽帕鲁存档转换终极指南:轻松修改游戏数据的安全方案
  • WorkBuddy 连接外部系统前,为什么先要确认使用哪个账号?
  • Unity工厂方法模式实战:从对象创建到Addressables资源管理
  • 分布式系统的六个经典脑裂场景:从选举到数据分片的避坑实战
  • three.js 编辑器的开源社区与文档
  • 如何参与 three.js 编辑器开源项目
  • 研究生论文AIGC检测挑战与千笔降AI率工具解析
  • three.js 编辑器提供哪些商业服务
  • 动态IP技术解析:成本优势与网络优化实战
  • 篮球口袋教练 HarmonyOS 学习应用(06):测验结果页的解释型反馈