-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimageclassification.py
More file actions
127 lines (106 loc) · 3.97 KB
/
Copy pathimageclassification.py
File metadata and controls
127 lines (106 loc) · 3.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# -*- coding: utf-8 -*-
"""imageclassification.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1e_k54pnlWm8MIKv1VWgWBzbUvf5_GDVA
"""
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
import numpy as np
class AdvancedCNN(nn.Module):
def __init__(self):
super(AdvancedCNN, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc1 = nn.Linear(256 * 4 * 4, 512)
self.fc2 = nn.Linear(512, 10)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(0.5)
def forward(self, x):
x = self.pool(self.relu(self.conv1(x)))
x = self.pool(self.relu(self.conv2(x)))
x = self.pool(self.relu(self.conv3(x)))
x = torch.flatten(x, 1)
x = self.relu(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return x
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = DataLoader(trainset, batch_size=64, shuffle=True)
classes = trainset.classes # CIFAR-10 class labels
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = DataLoader(testset, batch_size=64, shuffle=False)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = AdvancedCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))
losses, accuracies = [], []
epochs = 10
for epoch in range(epochs):
running_loss = 0.0
correct = 0
total = 0
for images, labels in trainloader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
losses.append(running_loss / len(trainloader))
accuracies.append(100 * correct / total)
# Update Plots
clear_output(wait=True)
ax1.clear()
ax2.clear()
ax3.clear()
# Loss Graph
ax1.plot(losses, label='Training Loss', color='blue')
ax1.set_title('Loss Progress')
ax1.set_xlabel('Epoch')
ax1.set_ylabel('Loss')
ax1.legend()
ax1.grid()
# Accuracy Graph
ax2.plot(accuracies, label='Training Accuracy', color='green')
ax2.set_title('Accuracy Progress')
ax2.set_xlabel('Epoch')
ax2.set_ylabel('Accuracy (%)')
ax2.legend()
ax2.grid()
# Simulated Feature Map Visualization
sample_img = images[0].cpu().detach().numpy().transpose(1, 2, 0)
ax3.imshow((sample_img * 0.5) + 0.5) # Denormalizing
ax3.set_title(f'Sample Input Image - {classes[labels[0].item()]}') # Display class label
ax3.axis('off')
display(fig)
print(f'Epoch {epoch+1}/{epochs}, Loss: {running_loss/len(trainloader):.4f}, Accuracy: {100 * correct / total:.2f}%')
print(f'Displaying image of: {classes[labels[0].item()]}')
correct = 0
total = 0
model.eval()
with torch.no_grad():
for images, labels in testloader:
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f'Final Test Accuracy: {100 * correct / total:.2f}%')