在上一篇博客中我们自己动手搭建了入门级别的分类网络架构,有了它,我们只需简单几步就可以训练自己的分类模型了~~
这是我的哔哩哔哩讲解视频,欢迎大家一键三连~~~
Bilibili主页:https://space.bilibili.com/481802918
PyTorch对计算机视觉任务非常的友好,特地创建了一个torchvision
库来供Cvers使用。具体的使用方法可以参考我的另一篇博客torch:)——torchvision pytorch图形库详解
首先,我们先利用torchvision
库来载入数据集,这里我们使用的是CIFAR10
数据集,并作归一化处理。
import torch
import torchvision
import torchvision.transforms as transforms
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')
其中,有关torchvision.transforms
有不懂的地方,也可以参考我的另一篇博客torch:)——PyTorch:transforms用法详解
这里,我们可以将入门级别的卷积网络稍微改改拿来使用。注意:
数据集为灰度图时,Input
的通道数为1,为正常的RGB图像时,Input
通道数为3(也就是R红,G绿,B蓝)。
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()
这里我们可以使用经典的交叉熵损失函数,以及随机梯度下降SGD来作为优化器。
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
大体流程:
for epoch in range(2): # 在训练集上循环训练2次
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# 归零参数梯度
optimizer.zero_grad()
# 向前传播 + 反向传播 + 优化
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')
保存模型:
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
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))
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)))
net = Net()
net.load_state_dict(torch.load(PATH))#装载模型
outputs = net(images)#将images传入模型中进行处理,得到outputs
_, predicted = torch.max(outputs, 1)#将outputs中概率最大的种类打印输出
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
这里我们也可以对自己的图片进行预测,将images读取自己的图片就可以。