Training A Classifier训练一个分类器
数据来源
图像:一般有Pillow,OpenCV
声音:scipy和librosa
文本:row Python ,Cpython, NLTK, SpaCy
pytorch对于视觉有torchvision包,包含CIFAR10,MNIST,ImageNet等数据集,本示例使用CIFAR10。
CIFAR10包含 ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’十种类型的图片,大小为3x32x32。
训练图像分类器
步骤:
- 使用torchvision加载并标准化CIFAR10训练集和测试集
- 定义一个卷积神经网络
- 定义损失函数
- 通过训练集训练神经网络
- 通过测试机测试神经网络
1.加载和标准化CIFAR10
import torch
import torchvision
import torchvision.transforms as transforms
数据集中为数字在0-1的PILImage,需要转换到-1到1
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
batch_size = 4
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
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=batch_size,
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
# 定义显示图片的函数
def imshow(img):
img = img / 2 + 0.5 # 去标准化:将图片的数值从-1~1转换到0~1
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# 随机获取一些训练图片
dataiter = iter(trainloader)
images, labels = dataiter.next()
# 显示图片
imshow(torchvision.utils.make_grid(images))
# 显示图片标签
print(' '.join('%5s' % classes[labels[j]] for j in range(batch_size)))
输出为:
cat plane bird ship
2.定义一个卷积神经网络
与Pytorch Tutorial学习笔记(3)不同的是,这里的图片有RGB三个通道,所以第一个卷积层稍有不同。
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__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 = torch.flatten(x, 1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
3.定义损失函数和优化器
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): # 在数据集上训练多次,训练一次称为一个epoch
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# 获取输入; 数据为一个列表 [inputs, labels]
inputs, labels = data
# 梯度归零
optimizer.zero_grad()
# 前向传递+反向传递+优化
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 输出统计结果
running_loss += loss.item()
if i % 2000 == 1999: # 每2000个batch输出一次
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
输出:
[1, 2000] loss: 2.128
[1, 4000] loss: 1.793
[1, 6000] loss: 1.649
[1, 8000] loss: 1.555
[1, 10000] loss: 1.504
[1, 12000] loss: 1.444
[2, 2000] loss: 1.379
[2, 4000] loss: 1.344
[2, 6000] loss: 1.336
[2, 8000] loss: 1.327
[2, 10000] loss: 1.294
[2, 12000] loss: 1.280
Finished Training
保存模型:
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
更多保存方式参考:Pytorch模型保存
5.测试神经网络
展示测试集的图片:
dataiter = iter(testloader)
images, labels = dataiter.next()
# 输出图片
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
GroundTruth: cat ship ship plane
加载刚刚保存的模型
net = Net()
net.load_state_dict(torch.load(PATH))
查看模型在整个数据集的正确率:
correct = 0
total = 0
with torch.no_grad(): # 这里是测试,不需要计算梯度了
for data in testloader:
images, labels = data
outputs = net(images) # 输入图片给net,得到输出
# 输出的概率中最大的那一个为该模型所预测的图片种类
_, 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))
附录
在GPU上训练
定义GPU设备:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
输出:
cuda:0
模型移动到GPU设备上:
net.to(device)
在训练和测试的循环中,把获取输入和标签那一行改成给到GPU设备的形式:
inputs, labels = data[0].to(device), data[1].to(device)
- 参考网址:Pytorch官网:训练一个图像分类器