9.9 KiB
9.9 KiB
None
<html>
<head>
</head>
</html>
Question 4 (10 marks)¶
In [1]:
import torch
from ca_utils import ResNet, BasicBlock
In [2]:
model = ResNet(block=BasicBlock, layers=[1, 1, 1], num_classes=10)
Load the Model¶
In [3]:
checkpoint = torch.load("data/weights_resnet.pth")
model.load_state_dict(checkpoint)
model.eval()
Out[3]:
Question 5 (15 marks)¶
In [4]:
import torchvision
from torch.utils.data import DataLoader
from torchvision import transforms
In [5]:
image_transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
test_data = torchvision.datasets.ImageFolder('data/EXCV10/val/', transform=image_transform)
test_loader = DataLoader(test_data, batch_size=64, shuffle=False, num_workers=4, pin_memory=True)
Method 1¶
In [6]:
import numpy as np
In [7]:
def m1_test_cnn(model, test_loader):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
model.eval()
correct = 0
total = 0
all_predicted_labels = []
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
all_predicted_labels.append(predicted.cpu().numpy())
accuracy = 100 * correct / total
all_predicted_labels = np.concatenate(all_predicted_labels)
return all_predicted_labels, accuracy
In [8]:
m1_predicted_labels, m1_test_accuracy = m1_test_cnn(model, test_loader)
print(f'Test Accuracy: {m1_test_accuracy}%')
Put Students' implementations here¶
In [9]:
def test_cnn(model, test_loader):
all_predicted_labels, accuracy = 0, 0
return all_predicted_labels, accuracy
In [10]:
predicted_labels, test_accuracy = test_cnn(model, test_loader)
print(f'Test Accuracy: {test_accuracy}%')
Question 6 (6 marks)¶
In [11]:
true_labels = []
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
true_labels.extend(labels.cpu().numpy())
true_labels = np.array(true_labels)
In [12]:
def compute_confusion_matrix(true, predictions):
unique_labels = np.unique(np.concatenate((true, predictions)))
confusion_mat = np.zeros((len(unique_labels), len(unique_labels)), dtype=np.int64)
label_to_index = {label: index for index,
label in enumerate(unique_labels)}
for t, p in zip(true, predictions):
t_index = label_to_index[t]
p_index = label_to_index[p]
confusion_mat[t_index][p_index] += 1
return confusion_mat
In [14]:
compute_confusion_matrix(true_labels, m1_predicted_labels)
Out[14]:
In [ ]: