text_plain_output_1.png
from torchvision import models, transforms, datasets

import matplotlib.pyplot as plt

import numpy as np

import os

import torch

import torch.nn as nn

import torchvision

torch.__version__

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

data_dir = '../input/dogscats/dogscats/dogscats/'

normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
vgg_format = transforms.Compose([transforms.CenterCrop(224), transforms.ToTensor(), normalize])

dsets = {x: datasets.ImageFolder(os.path.join(data_dir, x), vgg_format) for x in ['train', 'valid']}

dset_classes = dsets['valid'].classes
dset_classes

load_train = torch.utils.data.DataLoader(dsets['train'], batch_size=64, shuffle=True, num_workers=6)

load_test = torch.utils.data.DataLoader(dsets['valid'], batch_size=5, shuffle=True, num_workers=6)

inputs_try.shape

def imshow(inp, title=None):
    inp = inp.numpy().transpose((1, 2, 0))
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    inp = np.clip(std * inp + mean, 0, 1)
    plt.pause(0.001)

out = torchvision.utils.make_grid(inputs_try)

inputs, classes = next(iter(load_train))
n_images = 8
out = torchvision.utils.make_grid(inputs[0:n_images])

inputs, classes = next(iter(load_test))
n_images = 8
out = torchvision.utils.make_grid(inputs[0:n_images])

model_vgg = models.vgg16(pretrained=True)

inputs_try, lables_try = (inputs_try.to(device), labels_try.to(device))
model_vgg = model_vgg.to(device)

outputs_try = model_vgg(inputs_try)

outputs_try.shape

m_softm = nn.Softmax(dim=1)
probs = m_softm(outputs_try)
vals_try, preds_try = torch.max(probs, dim=1)

torch.sum(probs, 1)

out = torchvision.utils.make_grid(inputs_try.data.cpu())

for param in model_vgg.parameters():
    param.requires_grad = False
model_vgg.classifier._modules['6'] = nn.Linear(4096, 2)
model_vgg.classifier._modules['7'] = torch.nn.LogSoftmax(dim=1)

model_vgg = model_vgg.to(device)

criterion = nn.NLLLoss()
lr = 0.001
optimizer_vgg = torch.optim.SGD(model_vgg.classifier[6].parameters(), lr=lr)

def train_model(model, dataloader, size, epochs=1, optimizer=None):
    model.train()
    for epoch in range(epochs):
        running_loss = 0.0
        running_corrects = 0
        for inputs, classes in dataloader:
            inputs = inputs.to(device)
            classes = classes.to(device)
            outputs = model(inputs)
            loss = criterion(outputs, classes)
            optimizer = optimizer
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            _, preds = torch.max(outputs.data, 1)
            running_loss += loss.data.item()
            running_corrects += torch.sum(preds == classes.data)
        epoch_loss = running_loss / size
        epoch_acc = running_corrects.data.item() / size

def test_model(model, dataloader, size):
    model.eval()
    predictions = np.zeros(size)
    all_classes = np.zeros(size)
    all_proba = np.zeros((size, 2))
    i = 0
    running_loss = 0.0
    running_corrects = 0
    for inputs, classes in dataloader:
        inputs = inputs.to(device)
        classes = classes.to(device)
        outputs = model(inputs)
        loss = criterion(outputs, classes)
        _, preds = torch.max(outputs.data, 1)
        running_loss += loss.data.item()
        running_corrects += torch.sum(preds == classes.data)
        predictions[i:i + len(classes)] = preds.to('cpu').numpy()
        all_classes[i:i + len(classes)] = classes.to('cpu').numpy()
        all_proba[i:i + len(classes)] = outputs.data.to('cpu').numpy()
        i += len(classes)
    epoch_loss = running_loss / size
    epoch_acc = running_corrects.data.item() / size
    return (predictions, all_proba, all_classes)

inputs, classes = next(iter(load_test))
out = torchvision.utils.make_grid(inputs[0:n_images])
imshow(out, title=[dset_classes[x] for x in classes[0:n_images]])