Ubuntu
commited on
Commit
·
d759493
1
Parent(s):
5005854
Added graphs for top-1 and top-5 training and test accuracies. Added displaying of misclassified samples.
Browse files- resnet_execute.py +92 -21
resnet_execute.py
CHANGED
@@ -8,6 +8,8 @@ from resnet_model import ResNet50
|
|
8 |
from tqdm import tqdm
|
9 |
from torchvision import datasets
|
10 |
from checkpoint import save_checkpoint, load_checkpoint
|
|
|
|
|
11 |
|
12 |
# Define transformations
|
13 |
transform = transforms.Compose([
|
@@ -35,12 +37,12 @@ optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e
|
|
35 |
|
36 |
# Training function
|
37 |
from torch.amp import autocast
|
38 |
-
from tqdm import tqdm
|
39 |
|
40 |
def train(model, device, train_loader, optimizer, criterion, epoch, accumulation_steps=4):
|
41 |
model.train()
|
42 |
running_loss = 0.0
|
43 |
-
|
|
|
44 |
total = 0
|
45 |
pbar = tqdm(train_loader)
|
46 |
|
@@ -58,24 +60,28 @@ def train(model, device, train_loader, optimizer, criterion, epoch, accumulation
|
|
58 |
optimizer.zero_grad()
|
59 |
|
60 |
running_loss += loss.item() * accumulation_steps
|
61 |
-
_, predicted = outputs.
|
62 |
total += targets.size(0)
|
63 |
-
|
|
|
64 |
|
65 |
-
pbar.set_description(desc=f'Epoch {epoch} | Loss: {running_loss / (batch_idx + 1):.4f} |
|
66 |
|
67 |
if (batch_idx + 1) % 50 == 0:
|
68 |
torch.cuda.empty_cache()
|
69 |
|
70 |
-
return 100. *
|
71 |
-
|
72 |
|
73 |
# Testing function
|
74 |
def test(model, device, test_loader, criterion):
|
75 |
model.eval()
|
76 |
test_loss = 0
|
77 |
-
|
|
|
78 |
total = 0
|
|
|
|
|
|
|
79 |
|
80 |
with torch.no_grad():
|
81 |
for inputs, targets in test_loader:
|
@@ -84,13 +90,22 @@ def test(model, device, test_loader, criterion):
|
|
84 |
loss = criterion(outputs, targets)
|
85 |
|
86 |
test_loss += loss.item()
|
87 |
-
_, predicted = outputs.
|
88 |
total += targets.size(0)
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
94 |
|
95 |
# Main execution
|
96 |
if __name__ == '__main__':
|
@@ -107,14 +122,16 @@ if __name__ == '__main__':
|
|
107 |
|
108 |
# Store results for each epoch
|
109 |
results = []
|
|
|
110 |
|
111 |
for epoch in range(1, 6): # 20 epochs
|
112 |
-
|
113 |
-
|
114 |
-
print(f'Epoch {epoch} | Train
|
115 |
|
116 |
# Append results for this epoch
|
117 |
-
results.append((epoch,
|
|
|
118 |
|
119 |
if test_loss < best_loss:
|
120 |
best_loss = test_loss
|
@@ -127,7 +144,61 @@ if __name__ == '__main__':
|
|
127 |
print("Early stopping triggered. Training terminated.")
|
128 |
break
|
129 |
|
130 |
-
# Print the results in a tab-separated format
|
131 |
-
print("\nEpoch\tTrain Accuracy\tTest Accuracy")
|
132 |
-
for epoch,
|
133 |
-
print(f"{epoch}\t{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
from tqdm import tqdm
|
9 |
from torchvision import datasets
|
10 |
from checkpoint import save_checkpoint, load_checkpoint
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
from torchvision.utils import make_grid
|
13 |
|
14 |
# Define transformations
|
15 |
transform = transforms.Compose([
|
|
|
37 |
|
38 |
# Training function
|
39 |
from torch.amp import autocast
|
|
|
40 |
|
41 |
def train(model, device, train_loader, optimizer, criterion, epoch, accumulation_steps=4):
|
42 |
model.train()
|
43 |
running_loss = 0.0
|
44 |
+
correct1 = 0
|
45 |
+
correct5 = 0
|
46 |
total = 0
|
47 |
pbar = tqdm(train_loader)
|
48 |
|
|
|
60 |
optimizer.zero_grad()
|
61 |
|
62 |
running_loss += loss.item() * accumulation_steps
|
63 |
+
_, predicted = outputs.topk(5, 1, True, True)
|
64 |
total += targets.size(0)
|
65 |
+
correct1 += predicted[:, :1].eq(targets.view(-1, 1).expand_as(predicted[:, :1])).sum().item()
|
66 |
+
correct5 += predicted.eq(targets.view(-1, 1).expand_as(predicted)).sum().item()
|
67 |
|
68 |
+
pbar.set_description(desc=f'Epoch {epoch} | Loss: {running_loss / (batch_idx + 1):.4f} | Top-1 Acc: {100. * correct1 / total:.2f} | Top-5 Acc: {100. * correct5 / total:.2f}')
|
69 |
|
70 |
if (batch_idx + 1) % 50 == 0:
|
71 |
torch.cuda.empty_cache()
|
72 |
|
73 |
+
return 100. * correct1 / total, 100. * correct5 / total, running_loss / len(train_loader)
|
|
|
74 |
|
75 |
# Testing function
|
76 |
def test(model, device, test_loader, criterion):
|
77 |
model.eval()
|
78 |
test_loss = 0
|
79 |
+
correct1 = 0
|
80 |
+
correct5 = 0
|
81 |
total = 0
|
82 |
+
misclassified_images = []
|
83 |
+
misclassified_labels = []
|
84 |
+
misclassified_preds = []
|
85 |
|
86 |
with torch.no_grad():
|
87 |
for inputs, targets in test_loader:
|
|
|
90 |
loss = criterion(outputs, targets)
|
91 |
|
92 |
test_loss += loss.item()
|
93 |
+
_, predicted = outputs.topk(5, 1, True, True)
|
94 |
total += targets.size(0)
|
95 |
+
correct1 += predicted[:, :1].eq(targets.view(-1, 1).expand_as(predicted[:, :1])).sum().item()
|
96 |
+
correct5 += predicted.eq(targets.view(-1, 1).expand_as(predicted)).sum().item()
|
97 |
+
|
98 |
+
# Collect misclassified samples
|
99 |
+
for i in range(inputs.size(0)):
|
100 |
+
if targets[i] not in predicted[i, :1]:
|
101 |
+
misclassified_images.append(inputs[i].cpu())
|
102 |
+
misclassified_labels.append(targets[i].cpu())
|
103 |
+
misclassified_preds.append(predicted[i, :1].cpu())
|
104 |
|
105 |
+
test_accuracy1 = 100. * correct1 / total
|
106 |
+
test_accuracy5 = 100. * correct5 / total
|
107 |
+
print(f'Test Loss: {test_loss/len(test_loader):.4f}, Top-1 Accuracy: {test_accuracy1:.2f}, Top-5 Accuracy: {test_accuracy5:.2f}')
|
108 |
+
return test_accuracy1, test_accuracy5, test_loss / len(test_loader), misclassified_images, misclassified_labels, misclassified_preds
|
109 |
|
110 |
# Main execution
|
111 |
if __name__ == '__main__':
|
|
|
122 |
|
123 |
# Store results for each epoch
|
124 |
results = []
|
125 |
+
learning_rates = []
|
126 |
|
127 |
for epoch in range(1, 6): # 20 epochs
|
128 |
+
train_accuracy1, train_accuracy5, train_loss = train(model, device, trainloader, optimizer, criterion, epoch)
|
129 |
+
test_accuracy1, test_accuracy5, test_loss, misclassified_images, misclassified_labels, misclassified_preds = test(model, device, testloader, criterion)
|
130 |
+
print(f'Epoch {epoch} | Train Top-1 Acc: {train_accuracy1:.2f} | Train Top-5 Acc: {train_accuracy5:.2f} | Test Top-1 Acc: {test_accuracy1:.2f} | Test Top-5 Acc: {test_accuracy5:.2f}')
|
131 |
|
132 |
# Append results for this epoch
|
133 |
+
results.append((epoch, train_accuracy1, train_accuracy5, test_accuracy1, test_accuracy5, train_loss, test_loss))
|
134 |
+
learning_rates.append(optimizer.param_groups[0]['lr'])
|
135 |
|
136 |
if test_loss < best_loss:
|
137 |
best_loss = test_loss
|
|
|
144 |
print("Early stopping triggered. Training terminated.")
|
145 |
break
|
146 |
|
147 |
+
# Print the Top-1 accuracy results in a tab-separated format
|
148 |
+
print("\nEpoch\tTrain Top-1 Accuracy\tTest Top-1 Accuracy")
|
149 |
+
for epoch, train_acc1, test_acc1, *_ in results:
|
150 |
+
print(f"{epoch}\t{train_acc1:.2f}\t{test_acc1:.2f}")
|
151 |
+
|
152 |
+
# Plotting
|
153 |
+
epochs = [r[0] for r in results]
|
154 |
+
train_acc1 = [r[1] for r in results]
|
155 |
+
train_acc5 = [r[2] for r in results]
|
156 |
+
test_acc1 = [r[3] for r in results]
|
157 |
+
test_acc5 = [r[4] for r in results]
|
158 |
+
train_losses = [r[5] for r in results]
|
159 |
+
test_losses = [r[6] for r in results]
|
160 |
+
|
161 |
+
plt.figure(figsize=(12, 8))
|
162 |
+
plt.subplot(2, 2, 1)
|
163 |
+
plt.plot(epochs, train_acc1, label='Train Top-1 Acc')
|
164 |
+
plt.plot(epochs, test_acc1, label='Test Top-1 Acc')
|
165 |
+
plt.xlabel('Epoch')
|
166 |
+
plt.ylabel('Accuracy')
|
167 |
+
plt.legend()
|
168 |
+
plt.title('Top-1 Accuracy')
|
169 |
+
|
170 |
+
plt.subplot(2, 2, 2)
|
171 |
+
plt.plot(epochs, train_acc5, label='Train Top-5 Acc')
|
172 |
+
plt.plot(epochs, test_acc5, label='Test Top-5 Acc')
|
173 |
+
plt.xlabel('Epoch')
|
174 |
+
plt.ylabel('Accuracy')
|
175 |
+
plt.legend()
|
176 |
+
plt.title('Top-5 Accuracy')
|
177 |
+
|
178 |
+
plt.subplot(2, 2, 3)
|
179 |
+
plt.plot(epochs, train_losses, label='Train Loss')
|
180 |
+
plt.plot(epochs, test_losses, label='Test Loss')
|
181 |
+
plt.xlabel('Epoch')
|
182 |
+
plt.ylabel('Loss')
|
183 |
+
plt.legend()
|
184 |
+
plt.title('Loss')
|
185 |
+
|
186 |
+
plt.subplot(2, 2, 4)
|
187 |
+
plt.plot(epochs, learning_rates, label='Learning Rate')
|
188 |
+
plt.xlabel('Epoch')
|
189 |
+
plt.ylabel('Learning Rate')
|
190 |
+
plt.legend()
|
191 |
+
plt.title('Learning Rate')
|
192 |
+
|
193 |
+
plt.tight_layout()
|
194 |
+
plt.show()
|
195 |
+
|
196 |
+
# Display some misclassified samples
|
197 |
+
if misclassified_images:
|
198 |
+
print("\nDisplaying some misclassified samples from the last epoch:")
|
199 |
+
misclassified_grid = make_grid(misclassified_images[:16], nrow=4, normalize=True, scale_each=True)
|
200 |
+
plt.figure(figsize=(8, 8))
|
201 |
+
plt.imshow(misclassified_grid.permute(1, 2, 0))
|
202 |
+
plt.title("Misclassified Samples")
|
203 |
+
plt.axis('off')
|
204 |
+
plt.show()
|