300 - Convolution network, gradient, tweaks, with pytorch

Links: notebook, html ., PDF, python, slides ., GitHub

Object detection on CIFAR10.

Note: install tqdm if not installed: !pip install tqdm

%matplotlib inline
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
print("torch", torch.__version__)
from torchvision import datasets, transforms
from tqdm import tqdm
torch 0.4.0
BATCH_SIZE = 64
TEST_BATCH_SIZE = 64
DATA_DIR = 'data/'
USE_CUDA = False  # switch to True if you have GPU
N_EPOCHS = 5
train_loader = torch.utils.data.DataLoader(
    datasets.CIFAR10(DATA_DIR, train=True, download=True,
                   transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=BATCH_SIZE, shuffle=True)
test_loader = torch.utils.data.DataLoader(
    datasets.CIFAR10(DATA_DIR, train=False, transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=TEST_BATCH_SIZE, shuffle=True)
Files already downloaded and verified
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conv2_drop = nn.Dropout2d()
        self.fc1 = nn.Linear(500, 50)
        self.fc2 = nn.Linear(50, 64)

    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
        x = x.view(-1, 500)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return F.log_softmax(x, dim=-1)
model = Net()
if USE_CUDA: model = model.cuda()
optimizer = optim.Adam(model.parameters())
def train(epoch, verbose=True):
    model.train()
    losses = []
    loader = tqdm(train_loader, total=len(train_loader))
    for batch_idx, (data, target) in enumerate(loader):
        if USE_CUDA:
            data, target = data.cuda(), target.cuda()
        data, target = Variable(data), Variable(target)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        losses.append(float(loss.item()))
        if verbose and batch_idx % 100 == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
    return np.mean(losses)
def test(verbose=True):
    model.eval()
    test_loss = 0
    correct = 0
    for data, target in test_loader:
        if USE_CUDA: data, target = data.cuda(), target.cuda()
        with torch.no_grad():
            data = Variable(data)
        target = Variable(target)
        output = model(data)
        test_loss += F.nll_loss(output, target, size_average=False).item() # sum up batch loss
        pred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability
        correct += pred.eq(target.data.view_as(pred)).cpu().sum().item()

    test_loss /= len(test_loader.dataset)
    if verbose:
        print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
            test_loss, correct, len(test_loader.dataset),
            100. * correct / len(test_loader.dataset)))
    return [float(test_loss), correct]
perfs = []
for epoch in range(1, N_EPOCHS + 1):
    t0 = time.time()
    train_loss = train(epoch, verbose=False)
    test_loss, correct = test(verbose=False)
    perfs.append([epoch, train_loss, test_loss, correct, len(test_loader.dataset), time.time() - t0])
    print("epoch {}: train loss {:.4f}, test loss {:.4f}, accuracy {}/{} in {:.2f}s".format(*perfs[-1]))
100%|██████████| 782/782 [00:39<00:00, 20.01it/s]
epoch 1: train loss 2.1790, test loss 1.7208, accuracy 3707/10000 in 43.71s
100%|██████████| 782/782 [00:35<00:00, 21.85it/s]
epoch 2: train loss 1.8284, test loss 1.6156, accuracy 4257/10000 in 40.39s
100%|██████████| 782/782 [00:35<00:00, 22.31it/s]
epoch 3: train loss 1.7536, test loss 1.5357, accuracy 4468/10000 in 39.60s
100%|██████████| 782/782 [00:49<00:00, 15.93it/s]
epoch 4: train loss 1.6901, test loss 1.4749, accuracy 4673/10000 in 57.17s
100%|██████████| 782/782 [00:52<00:00, 14.85it/s]
epoch 5: train loss 1.6613, test loss 1.4650, accuracy 4728/10000 in 60.06s
df_perfs = pd.DataFrame(perfs, columns=["epoch", "train_loss", "test_loss", "accuracy", "n_test", "time"])
df_perfs
epoch train_loss test_loss accuracy n_test time
0 1 2.178991 1.720826 3707 10000 43.710512
1 2 1.828428 1.615563 4257 10000 40.387807
2 3 1.753622 1.535746 4468 10000 39.603589
3 4 1.690147 1.474856 4673 10000 57.165565
4 5 1.661258 1.465005 4728 10000 60.060167
df_perfs[["train_loss", "test_loss"]].plot();
../_images/300_Convolution_CIFAR10_12_0.png