实现对CIFAR-10的分类,步骤如下:
import torchvision as tv
import torch as t
import torchvision.transforms as transforms
from torchvision.transforms import ToPILImage
show = ToPILImage() #将Tensor转成Image,方面可视化
# 第一次运行程序torchvision会自动下载CIFAR-10数据集。
# 如果已经下载有CIFAR-10,可通过root参数指定
# 定义对数据的预处理,Compose这个类是用来管理各个transform的
transform = transforms.Compose([transforms.ToTensor(), # 转为Tensor
transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))]) # 归一化
# 训练集
trainset = tv.datasets.CIFAR10(root='D:\\Workspace\\Python\\CIFAR-10\\', train = True, download=True, transform=transform)
trainloader = t.utils.data.DataLoader(trainset, batch_size=4, shuffle=True,num_workers=2)
#测试集
testset = tv.datasets.CIFAR10(root='D:\\Workspace\\Python\\CIFAR-10\\', train = False, download=True, transform=transform)
testloader = t.utils.data.DataLoader(testset, batch_size=4, shuffle=False,num_workers=2)
classes = ('plane','car','bird','cat','deer','dog','frog','horse','ship','truck')
Files already downloaded and verified
Files already downloaded and verified
1.1 ToTensor类是实现:Convert a PIL Image or numpy.ndarray to tensor的过程,在PyTorch中常用PIL库来读取图像数据,因此这个方法相当于搭建了PIL Image和Tensor的桥梁。另外要强调的是在做数据归一化之前必须要把PIL Image转成Tensor,而其他resize或crop操作则不需要。
transform1 = transforms.Compose([
transforms.ToTensor(), # range [0, 255] -> [0.0,1.0]
])
# Converts a PIL Image or numpy.ndarray (H x W x C) in the range
# [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].
1.2 transforms.Compose归一化到[-1.0, 1.0]
将上面的transform1改为如下所示:
transform2 = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean = (0.5, 0.5, 0.5), std = (0.5, 0.5, 0.5))
])
transforms.Normalize使用如下公式进行归一化:
channel=(channel-mean)/std (因为transforms.ToTensor()已经把数据处理成[0,1],那么(x-0.5)/0.5就是[-1.0, 1.0])
这样一来,我们的数据中的每个值就变成了[-1,1]的数了。
1.3 torch.utils.data.DataLoader()
如果对数据的输入有特殊要求,可以设置参数:
1.4 Dataset对象是一个数据集,可以按下标访问,返回形如(data,label)的数据。
(data, label) = trainset[100]
print(classes[label])
#(data+1)/2 是为了还原被归一化的数据,程序输出的图片如图
show((data+1)/2).resize((100,100))
Out: ship
1.5 Dataloder是一个可迭代的对象,它将dataset返回的每一条数据样本拼接成一个batch,并提供多线程加速优化和数据打乱等操作。当程序对dataset的所有数据遍历完一遍之后,对Dataloader也完成了一次迭代。
dataiter = iter(trainloader)
images,labels = dataiter.next() #返回4张图片及标签,如下图
print(''.join('%11s'%classes[labels[j]] for j in range(4)))
show(tv.utils.make_grid((images+1)/2)).resize((400,100))
Out: horse plane frog deer
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
#nn.Module子类必须在构造函数中执行父类的构造函数
#下式等价于nn.Module.__init__(self)
super(Net,self).__init__()
#卷积层'3'表示输入图片为3通道,'6'表示输出通道数,'5'表示卷积核为5*5
self.conv1 = nn.Conv2d(3,6,5)
#卷积层
self.conv2 = nn.Conv2d(6,16,5)
#仿射层/全连接层,y=Wx+b
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 = F.max_pool2d(F.relu(self.conv1(x)),(2,2))
x = F.max_pool2d(F.relu(self.conv2(x)),2)
# reshape, '-1'表示自适应
x = x.view(x.size()[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
print(net)
# Out: Net(
# (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
# (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
# (fc1): Linear(in_features=400, out_features=120, bias=True)
# (fc2): Linear(in_features=120, out_features=84, bias=True)
# (fc3): Linear(in_features=84, out_features=10, bias=True)
# )
from torch import optim
criterion = nn.CrossEntropyLoss() #交叉熵损失函数
optimizer = optim.SGD(net.parameters(),lr=0.001, momentum = 0.9)
所有网络的训练流程都是类似的,不断地执行如下流程。
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
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')
此处仅训练了2个epoch(遍历完一遍数据集称为一个epoch)。我们来看看网络有没有效果。将测试图片输入网络,计算它的label,然后与实际的label进行比较。
dataiter = iter(testloader)
images,labels = dataiter.next() #一个batch返回4张图片
# print images
print('GroundTruth: ', ' '.join('%08s' % classes[labels[j]] for j in range(4)))
show(tv.utils.make_grid(images/2-0.5)).resize((400,100))
Out: GroundTruth: cat ship ship plane
接着计算网络预测的label:
#计算图片在每个类别上的分类
outputs = net(images)
#得分最高的那个类
_, predicted = t.max(outputs.data, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
Out: Predicted: dog ship car plane
我们再来看看在整个测试集上的效果。
correct = 0 #预测正确的图片数
total = 0 #总图片数
with t.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = t.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))
Out: Accuracy of the network on the 10000 test images: 61 %
if t.cuda.is_available():
net.cuda()
images = images.cuda()
labels = labels.cuda()
output = net(images)
loss = criterion(output, labels)