Angad Sandhu
Search
Browse
On this page

ch2

Chapter 2 : Image Clasification with Pytorch

Making outr first Neural Network in PyTorch

# imports
import torch, torchvision
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torch.nn.functional as F

from torchvision import transforms
from PIL import Image, ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True
# checking for GPU
if torch.cuda.is_available():
    device = torch.device("cuda")
else:
    device = torch.device("cpu")

Importing Data

train_data_path = "./train/"
val_data_path = "./val/"
test_data_path = "./test/"

# creating transformation pipeline
transformation = transforms.Compose([
    transforms.Resize((64, 64)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
def check_image(path):
    try:
        im = Image.open(path)
        return True
    except:
        return False
# getting datasets
train_data = torchvision.datasets.ImageFolder(root=train_data_path, transform=transformation, is_valid_file=check_image)
val_data = torchvision.datasets.ImageFolder(root=val_data_path, transform=transformation, is_valid_file=check_image)
test_data = torchvision.datasets.ImageFolder(root=test_data_path, transform=transformation, is_valid_file=check_image)
# building Data Loaders
batch_size=128
train_data_loader = data.DataLoader(train_data, batch_size=batch_size)
val_data_loader = data.DataLoader(val_data, batch_size=batch_size)
test_data_loader = data.DataLoader(test_data, batch_size=batch_size)

Creating Model

# Creating Networf
class SimpleNet(nn.Module):
    
    # Initializing Layers and variables
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(12288, 84)
        self.fc2 = nn.Linear(84, 50)
        self.fc3 = nn.Linear(50, 2)

    # forward function
    def forward(self, x):
        x = x.view(-1, 12288)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)

        return x
# initiating model
simplenet = SimpleNet()

# adding model to GPU
simplenet.to(device)
SimpleNet(
  (fc1): Linear(in_features=12288, out_features=84, bias=True)
  (fc2): Linear(in_features=84, out_features=50, bias=True)
  (fc3): Linear(in_features=50, out_features=2, bias=True)
)
optimizer = optim.Adam(simplenet.parameters(), lr=0.001)

Training

def train(model, optimizer, loss_fn, train_loader, val_loader, epochs=20, device="cpu"):
    for epoch in range(1, epochs+1):
        
        model.train()
        train_loss = 0.0

        for batch in train_loader:
            optimizer.zero_grad()
            inputs, targets = batch

            inputs = inputs.to(device)
            targets = targets.to(device)

            output = model(inputs)
            loss = loss_fn(output, targets)
            loss.backward()
            optimizer.step()

            train_loss += loss.data.item()

        train_loss /= len(train_loader.dataset)

        model.eval()
        val_loss = 0.0
        
        num_correct = 0
        num_examples = 0

        for batch in val_loader:
            # NO : optimizer.zero_grad()
            inputs, targets = batch

            inputs = inputs.to(device)
            targets = targets.to(device)

            output = model(inputs)
            loss = loss_fn(output, targets)

            val_loss += loss.data.item() * inputs.size(0)
            
            correct = torch.eq(torch.max(F.softmax(output, dim=1), dim=1)[1], targets)
            num_correct += torch.sum(correct).item()
            num_examples += correct.shape[0] 

            # loss.backward()
            # optimizer.step()
            # train_loss += loss.data.item()

        val_loss /= len(val_loader.dataset)

        # printing statememnt per epoch
        print(f"Epoch: {epoch}, Training Loss: {train_loss:.4f}, Validation Loss: {val_loss:.3f}, Accuracy: {(num_correct/num_examples):.2f}")
# Calling Training Function
train(simplenet, optimizer, torch.nn.CrossEntropyLoss(), train_data_loader, val_data_loader, epochs=3, device=device)
Epoch: 1, Training Loss: 0.0000, Validation Loss: 1.177, Accuracy: 0.72
Epoch: 2, Training Loss: 0.0000, Validation Loss: 1.272, Accuracy: 0.71
Epoch: 3, Training Loss: 0.0000, Validation Loss: 1.261, Accuracy: 0.71

Inference

labels = ['cat','fish']

img = Image.open("./val/fish/100_1422.JPG") 
img = transformation(img).to(device)
img = torch.unsqueeze(img, 0)

simplenet.eval()
prediction = F.softmax(simplenet(img), dim=1)
prediction = prediction.argmax()
print(labels[prediction]) 
fish
labels = ['cat','fish']

for batch in test_data_loader:
    inputs, targets = batch
    inputs = inputs.to(device)
    targets = targets.to(device)

    predictions = simplenet(inputs)

    for i, prediction in enumerate(predictions):
        prediction = prediction.argmax()
        print(f"#{i+1} === Prediction: {labels[prediction]}, Actual Label: {labels[targets[i]]}")
#1 === Prediction: cat, Actual Label: cat
#2 === Prediction: cat, Actual Label: cat
#3 === Prediction: cat, Actual Label: cat
#4 === Prediction: cat, Actual Label: cat
#5 === Prediction: cat, Actual Label: cat
#6 === Prediction: fish, Actual Label: cat
#7 === Prediction: cat, Actual Label: cat
#8 === Prediction: cat, Actual Label: cat
#9 === Prediction: cat, Actual Label: cat
#10 === Prediction: cat, Actual Label: cat
#11 === Prediction: cat, Actual Label: cat
#12 === Prediction: cat, Actual Label: cat
#13 === Prediction: cat, Actual Label: cat
#14 === Prediction: cat, Actual Label: cat
#15 === Prediction: cat, Actual Label: cat
#16 === Prediction: cat, Actual Label: cat
#17 === Prediction: fish, Actual Label: cat
#18 === Prediction: cat, Actual Label: cat
#19 === Prediction: cat, Actual Label: cat
#20 === Prediction: cat, Actual Label: cat
#21 === Prediction: cat, Actual Label: cat
#22 === Prediction: cat, Actual Label: cat
#23 === Prediction: cat, Actual Label: cat
#24 === Prediction: cat, Actual Label: cat
#25 === Prediction: cat, Actual Label: cat
#26 === Prediction: cat, Actual Label: cat
#27 === Prediction: fish, Actual Label: cat
#28 === Prediction: cat, Actual Label: cat
#29 === Prediction: fish, Actual Label: cat
#30 === Prediction: cat, Actual Label: cat
#31 === Prediction: cat, Actual Label: cat
#32 === Prediction: cat, Actual Label: cat
#33 === Prediction: cat, Actual Label: cat
#34 === Prediction: cat, Actual Label: cat
#35 === Prediction: cat, Actual Label: cat
#36 === Prediction: fish, Actual Label: cat
#37 === Prediction: cat, Actual Label: cat
#38 === Prediction: cat, Actual Label: cat
#39 === Prediction: cat, Actual Label: cat
#40 === Prediction: fish, Actual Label: cat
#41 === Prediction: cat, Actual Label: cat
#42 === Prediction: cat, Actual Label: cat
#43 === Prediction: cat, Actual Label: cat
#44 === Prediction: cat, Actual Label: cat
#45 === Prediction: cat, Actual Label: cat
#46 === Prediction: cat, Actual Label: cat
#47 === Prediction: cat, Actual Label: cat
#48 === Prediction: fish, Actual Label: cat
#49 === Prediction: cat, Actual Label: cat
#50 === Prediction: fish, Actual Label: cat
#51 === Prediction: cat, Actual Label: cat
#52 === Prediction: cat, Actual Label: cat
#53 === Prediction: fish, Actual Label: cat
#54 === Prediction: cat, Actual Label: cat
#55 === Prediction: cat, Actual Label: cat
#56 === Prediction: cat, Actual Label: cat
#57 === Prediction: fish, Actual Label: cat
#58 === Prediction: cat, Actual Label: cat
#59 === Prediction: cat, Actual Label: cat
#60 === Prediction: cat, Actual Label: cat
#61 === Prediction: fish, Actual Label: cat
#62 === Prediction: cat, Actual Label: cat
#63 === Prediction: cat, Actual Label: cat
#64 === Prediction: cat, Actual Label: cat
#65 === Prediction: fish, Actual Label: cat
#66 === Prediction: cat, Actual Label: cat
#67 === Prediction: fish, Actual Label: cat
#68 === Prediction: cat, Actual Label: cat
#69 === Prediction: cat, Actual Label: cat
#70 === Prediction: cat, Actual Label: cat
#71 === Prediction: cat, Actual Label: cat
#72 === Prediction: cat, Actual Label: cat
#73 === Prediction: cat, Actual Label: cat
#74 === Prediction: fish, Actual Label: cat
#75 === Prediction: fish, Actual Label: cat
#76 === Prediction: cat, Actual Label: cat
#77 === Prediction: cat, Actual Label: cat
#78 === Prediction: cat, Actual Label: cat
#79 === Prediction: cat, Actual Label: cat
#80 === Prediction: cat, Actual Label: cat
#81 === Prediction: cat, Actual Label: cat
#82 === Prediction: cat, Actual Label: cat
#83 === Prediction: cat, Actual Label: cat
#84 === Prediction: cat, Actual Label: cat
#85 === Prediction: cat, Actual Label: cat
#86 === Prediction: fish, Actual Label: cat
#87 === Prediction: cat, Actual Label: cat
#88 === Prediction: fish, Actual Label: cat
#89 === Prediction: cat, Actual Label: cat
#90 === Prediction: fish, Actual Label: cat
#91 === Prediction: cat, Actual Label: cat
#92 === Prediction: fish, Actual Label: fish
#93 === Prediction: fish, Actual Label: fish
#94 === Prediction: fish, Actual Label: fish
#95 === Prediction: fish, Actual Label: fish
#96 === Prediction: fish, Actual Label: fish
#97 === Prediction: fish, Actual Label: fish
#98 === Prediction: fish, Actual Label: fish
#99 === Prediction: fish, Actual Label: fish
#100 === Prediction: cat, Actual Label: fish
#101 === Prediction: fish, Actual Label: fish
#102 === Prediction: fish, Actual Label: fish
#103 === Prediction: fish, Actual Label: fish
#104 === Prediction: fish, Actual Label: fish
#105 === Prediction: fish, Actual Label: fish
#106 === Prediction: cat, Actual Label: fish
#107 === Prediction: cat, Actual Label: fish
#108 === Prediction: fish, Actual Label: fish
#109 === Prediction: fish, Actual Label: fish
#110 === Prediction: cat, Actual Label: fish
#111 === Prediction: fish, Actual Label: fish
#112 === Prediction: fish, Actual Label: fish
#113 === Prediction: fish, Actual Label: fish
#114 === Prediction: fish, Actual Label: fish
#115 === Prediction: fish, Actual Label: fish
#116 === Prediction: fish, Actual Label: fish
#117 === Prediction: fish, Actual Label: fish
#118 === Prediction: cat, Actual Label: fish
#119 === Prediction: cat, Actual Label: fish
#120 === Prediction: cat, Actual Label: fish
#121 === Prediction: cat, Actual Label: fish
#122 === Prediction: fish, Actual Label: fish
#123 === Prediction: fish, Actual Label: fish
#124 === Prediction: cat, Actual Label: fish
#125 === Prediction: fish, Actual Label: fish
#126 === Prediction: fish, Actual Label: fish
#127 === Prediction: fish, Actual Label: fish
#128 === Prediction: cat, Actual Label: fish
#1 === Prediction: fish, Actual Label: fish
#2 === Prediction: fish, Actual Label: fish
#3 === Prediction: cat, Actual Label: fish
#4 === Prediction: fish, Actual Label: fish
#5 === Prediction: cat, Actual Label: fish
#6 === Prediction: cat, Actual Label: fish
#7 === Prediction: cat, Actual Label: fish
#8 === Prediction: fish, Actual Label: fish
#9 === Prediction: fish, Actual Label: fish
#10 === Prediction: cat, Actual Label: fish
#11 === Prediction: fish, Actual Label: fish
#12 === Prediction: fish, Actual Label: fish
#13 === Prediction: fish, Actual Label: fish
#14 === Prediction: fish, Actual Label: fish
#15 === Prediction: fish, Actual Label: fish
#16 === Prediction: fish, Actual Label: fish
#17 === Prediction: fish, Actual Label: fish
#18 === Prediction: fish, Actual Label: fish
#19 === Prediction: fish, Actual Label: fish
#20 === Prediction: fish, Actual Label: fish
#21 === Prediction: fish, Actual Label: fish
#22 === Prediction: fish, Actual Label: fish
#23 === Prediction: fish, Actual Label: fish
#24 === Prediction: cat, Actual Label: fish
#25 === Prediction: fish, Actual Label: fish
#26 === Prediction: fish, Actual Label: fish
#27 === Prediction: fish, Actual Label: fish
#28 === Prediction: fish, Actual Label: fish
#29 === Prediction: fish, Actual Label: fish
#30 === Prediction: cat, Actual Label: fish
#31 === Prediction: fish, Actual Label: fish
#32 === Prediction: fish, Actual Label: fish
labels = ['cat','fish']
correct = 0
total = 0

with torch.no_grad():
    for batch in test_data_loader:
        inputs, targets = batch
        inputs = inputs.to(device)
        targets = targets.to(device)

        predictions = simplenet(inputs)

        for i, prediction in enumerate(predictions):
            prediction = prediction.argmax()
            if prediction == targets[i]:
                correct += 1
            total += 1
        
        accuracy = correct / total
        print(f"Accuracy of this Batch {i+1} : {accuracy}")

Saving & Loading Model

torch.save(simplenet, "./model/simplenet")
simplenet = torch.load("./model/simplenet")
torch.save(simplenet.state_dict(), "./model/simplenet-state-dict")
simplenet = SimpleNet()
simplenet_state_dict = torch.load("./model/simplenet-state-dict")
simplenet.load_state_dict(simplenet_state_dict)
<All keys matched successfully>

Browse the library