[go: up one dir, main page]

0% found this document useful (0 votes)
19 views7 pages

CV Lab Final AwaisKhan EE A

ffv

Uploaded by

Awais Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views7 pages

CV Lab Final AwaisKhan EE A

ffv

Uploaded by

Awais Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

College of Electrical & Mechanical Engineering, NUST

CS-477-Computer Vision DE-42 Department of Electrical Engineering

Computer Vision
LAB Final Report

Submitted To: Sir Kamran Aziz Bhatti

Ma’am Rozina

Submitted By:
AWAIS KHAN – 338272
DE-42-EE-Syndicate-A

Submission Date:
June 6th, 2024
TASK
Implement a code in Google Colab for CNN using ResNet model

Code
#CV LAB Final
#Awais Khan-338272-42-EE-A
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torchvision import models
import matplotlib.pyplot as plt

# Check for GPU


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Define transformations for the training and test sets


transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994,
0.2010)),
])

transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994,
0.2010)),
])

# Load CIFAR-10 dataset


trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,
shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False,


download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100,
shuffle=False, num_workers=2)

# Load ResNet model


model = models.resnet18(pretrained=False, num_classes=10)
model = model.to(device)

# Define loss function and optimizer


criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9,
weight_decay=5e-4)

# Initialize lists to store loss and accuracy


train_losses = []
test_losses = []
test_accuracies = []

# Define training function


def train(epoch):
model.train()
running_loss = 0.0
for batch_idx, (inputs, targets) in enumerate(trainloader):
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()

running_loss += loss.item()
if batch_idx % 100 == 99: # Print every 100 mini-batches
print(f'Epoch [{epoch + 1}], Step [{batch_idx + 1}], Loss:
{running_loss / 100:.4f}')
train_losses.append(running_loss / 100)
running_loss = 0.0

# Define test function


def test():
model.eval()
test_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for inputs, targets in testloader:
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += (predicted == targets).sum().item()

test_loss /= len(testloader)
accuracy = 100 * correct / total
test_losses.append(test_loss)
test_accuracies.append(accuracy)
print(f'Accuracy of the model on the test images: {accuracy} %')

# Train the model


num_epochs = 12
for epoch in range(num_epochs):
train(epoch)
test()

# Plotting the results


plt.figure(figsize=(18, 5))

plt.subplot(1, 3, 1)
plt.plot(train_losses, label='Training Loss')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.title('Training Loss')
plt.legend()

plt.subplot(1, 3, 2)
plt.plot(test_losses, label='Test Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Test Loss')
plt.legend()

plt.subplot(1, 3, 3)
plt.plot(test_accuracies, label='Test Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy (%)')
plt.title('Test Accuracy')
plt.legend()

plt.tight_layout()
plt.show()
Results

You might also like