美文网首页工作生活
(四) trainning a classifier

(四) trainning a classifier

作者: 狼无雨雪 | 来源:发表于2019-07-04 18:58 被阅读0次
    ### import torch and some packages, and downloading CIFAR10 dataset
    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
    
    testset = torchvision.datasets.CIFAR10(root="./data", train=False,
                                          download=True, transform=transform)
    
    
    Files already downloaded and verified
    
    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
    
    # functions to show an image
    
    
    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 training images
    dataiter = iter(trainloader)
    images, labels = dataiter.next()
    
    # show images
    imshow(torchvision.utils.make_grid(images))
    # print labels
    print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
    
    <Figure size 640x480 with 1 Axes>
    
    
    horse  bird  ship   cat
    
    ### show some images
    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]) for j in range(4))
    
    <generator object <genexpr> at 0x7f6d8dacde08>
    
    ### define a Convolutional Neural Network
    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()
    print(net)
    
    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)
    )
    
    ### define loss function as optimizer
    import torch.optim as optim
    
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
    
    ### Train the network
    for epoch in range(2):
        
        running_loss = 0.0
        for i, data in enumerate(trainloader, 0):
            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:
                print('[%d, %5d] loss : %.3f'%(epoch + 1, i + 1, running_loss / 2000))
        
    print('Finished Training')
    
    [1,  2000] loss : 2.212
    [1,  4000] loss : 4.095
    [1,  6000] loss : 5.784
    [1,  8000] loss : 7.361
    [1, 10000] loss : 8.859
    [1, 12000] loss : 10.343
    [2,  2000] loss : 1.413
    [2,  4000] loss : 2.789
    [2,  6000] loss : 4.143
    [2,  8000] loss : 5.459
    [2, 10000] loss : 6.777
    [2, 12000] loss : 8.078
    Finished Training
    
    ### test the network on the test data
    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
    
    outputs = net(images)
    
    _, predicted = torch.max(outputs, 1)
    
    print('Predicted : ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
    
    Predicted :    cat   car   car plane
    
    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))
            
    
    Accuracy of the network on the 10000 test images : 53 %
    
    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()
            for i in range(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]))
    
    Accuracy of plane : 67 %
    Accuracy of   car : 54 %
    Accuracy of  bird : 43 %
    Accuracy of   cat : 21 %
    Accuracy of  deer : 36 %
    Accuracy of   dog : 58 %
    Accuracy of  frog : 83 %
    Accuracy of horse : 47 %
    Accuracy of  ship : 56 %
    Accuracy of truck : 70 %
    
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    print(device)
    
    cuda:0
    
    net.to(device)
    inputs, labels = inputs.to(device), labels.to(device)
    

    相关文章

      网友评论

        本文标题:(四) trainning a classifier

        本文链接:https://www.haomeiwen.com/subject/gwxdhctx.html