PyTorch官方教程之3:PyTorch图像分类器

# 《PyTorch官方教程中文版》, PyTorch图像分类器
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

# # read cifar10 data from local files
# def unpickle(file):
#     import pickle
#     with open(file, 'rb') as fo:
#         dict = pickle.load(fo, encoding='bytes')
#     return dict
#
# meta_data = unpickle('./cifar-10-batches-py/batches.meta')
# print(meta_data)
# db1 = unpickle('./cifar-10-batches-py/data_batch_1')
# print(db1)
# print(db1[b'data'])


# # step 1: prepare data
# transform PILImage as Tensors
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# train data
# trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
# already downloaded, load directly
# torchvision.datasets 是用来进行数据加载的,PyTorch团队在这个包中帮我们提前处理好了很多很多图片数据集。
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=False, transform=transform)
# DataLoader 用于批量加载数据,你可以用他来加载任何来自 Dataset的数据,它使得数据的批量加载十分容易。
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=0)  # num_workers改为0,单进程加载

# test data
# testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=0)  # num_workers改为0,单进程加载

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')  # 元组类型才能使用下标


# display example images
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 images
dataiter = iter(trainloader)
images, labels = dataiter.next()

# show images
imshow(torchvision.utils.make_grid(images))
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))


# # step 2: define cnn model, LeNet-5
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()

# # step 3: define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

# # step 4: train
for epoch in range(2):  # loop over dataset multiple times, 训练2轮
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0): # i starts from 0
        inputs, labels = data
        # zero the parameter gradients
        # 每执行一次backward(),对应tensor的梯度都会自加1,即梯度自动累加,所以需要每个batch_size都执行梯度清零.zero_grad()操作。
        optimizer.zero_grad()
        # forward
        outputs = net(inputs)
        loss = criterion(outputs, labels)
        # backward
        loss.backward()
        # update
        optimizer.step()
        # print statistics
        running_loss += loss.item()
        # training batch size = 4, data size = 5w, so i max = 12k
        if i % 2000 == 1999:  # every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0
print('Finished Training')

# # step 5: test

# take random images above for example
outputs = net(images)
# output size 4*10, similarity between each class
# print(outputs)
# get the most similar
# torch.max(a,1)返回每一行中最大值的那个元素,及其索引(返回最大元素在这一行的列索引)
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))

# use test data instead
correct = 0
total =0
# torch.no_grad()是禁用梯度计算的上下文管理器,一般是在validate或者test会使用,只需要计算网络的输出,而无需计算梯度了。
# 主要是用于停止autograd模块的工作,以起到加速和节省显存的作用, 强制之后的内容不进行计算图构建, 没有grad_fn=属性
with torch.no_grad(): # 所有计算得出的tensor的requires_grad都自动设置为False。
    for data in testloader:
        images, labels = data
        outputs = net(images)
        _, predicted = torch.max(outputs, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

print('Accuracy of network on the 10000 test images: %d %%' % (100*correct/total)) #%%转义百分号

# accuracy for each class
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() #去除size为1的维度
        for i in range(4): #batch size=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]))

你可能感兴趣的:(PyTorch,pytorch,深度学习,python)