1. 程式人生 > 其它 >pytorch初學影象分類器

pytorch初學影象分類器

技術標籤:深度學習神經網路pytorch

訓練一個影象分類器

1.使用torchvision載入和正則化CIFAR10訓練集和測試集

2.構造一個CNN

3.構造損失函式

4.訓練網路

5.測試網路

1. 載入和正規化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'
)
Files already downloaded and verified
Files already downloaded and verified
import matplotlib.pyplot as plt
import numpy as np

def imshow(img):
    img = img / 2 + 0.5
    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(4)))

在這裡插入圖片描述

truck   car  bird  ship

2. 定義一個卷積神經網路

import torch.nn as nn
import torch.nn.functional as F

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
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()
net.to(device)
Net(
  (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (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)
)

3. 定義損失函式和優化器

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # momentum為動量,解決區域性最優解問題

4. 訓練CNN


for epoch in range(2):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # inputs, labels = data # 使用cpu訓練
        inputs, labels = data[0].to(device), data[1].to(device) # 使用gpu訓練

        optimizer.zero_grad()

        outputs = net(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 2000 == 1999: # 每兩千次,計算一下loss的總和,看總體的降低
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')
[1,  2000] loss: 2.139
[1,  4000] loss: 1.818
[1,  6000] loss: 1.678
[1,  8000] loss: 1.575
[1, 10000] loss: 1.523
[1, 12000] loss: 1.490
[2,  2000] loss: 1.417
[2,  4000] loss: 1.345
[2,  6000] loss: 1.356
[2,  8000] loss: 1.314
[2, 10000] loss: 1.291
[2, 12000] loss: 1.279
Finished Training
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)

5. 測試網路

dataiter = iter(testloader) # dataload迭代器
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
net = Net()
net.load_state_dict(torch.load(PATH))
outputs = net(images)
_, predicted = torch.max(outputs, 1) # dim = 1, 將維度壓縮為1
print(outputs) # 每一行代表一個圖片的輸出值
print(predicted) # 每張圖片最大輸出值的下邊

print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                              for j in range(4)))
tensor([[-2.5090, -3.2349,  1.7301,  2.9694,  3.0115,  2.8149,  3.4539,  0.7578,
         -3.6328, -3.4352],
        [-0.8140, -4.5701,  2.3966,  2.8336, -0.1575,  5.3245, -0.4004,  1.8420,
         -3.9213, -2.3566],
        [ 1.6518,  0.1281,  2.1819, -0.2296,  4.1228, -0.2814,  1.4106, -0.8388,
         -2.4360, -3.0393],
        [-1.2521, -3.1468,  0.3812,  0.9961,  4.1565,  1.7851,  0.2695,  6.6411,
         -5.3557, -1.3407]])
tensor([6, 5, 4, 7])
Predicted:   frog   dog  deer horse
correct = 0
total = 0
with torch.no_grad(): # 預測的話不需要計算gradient
    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: 56 %