-
Notifications
You must be signed in to change notification settings - Fork 0
/
EE782_A2_20d170033.py
1687 lines (1350 loc) · 63.8 KB
/
EE782_A2_20d170033.py
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# %% [markdown]
# # EE 782 Assignment 2
# ## Name: Rohan Rajesh Kalbag
# ## Roll No: 20d170033
# %% [markdown]
# ## Importing Libraries
# %%
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
import numpy as np
import PIL
import torchvision
import matplotlib.pyplot as plt
# %% [markdown]
# ## Q1 : Getting the labelled face dataset from specified source
# %%
# running this locally on my CUDA enabled machine which has Nvidia RTX 2070
!nvidia-smi # check GPU
# %%
%%bash
# download the dataset if not already downloaded
if [ ! -d "lfw" ]; then
wget http://vis-www.cs.umass.edu/lfw/lfw.tgz # download the dataset
tar -xzf lfw.tgz # extract the dataset
rm lfw.tgz # remove the tar file
fi
# %% [markdown]
# ## Q2 : Getting the names of people with more than one image and also the number
# %%
import os
# list to hold people with more than one image
people_with_more_than_one_image = []
# Define the root directory
root_directory = "./lfw"
# Create a dictionary to store subfolder file counts
subfolder_counts = {}
# Walk through the directory and count files in subfolders
for dirpath, _, filenames in os.walk(root_directory):
subfolder_name = os.path.basename(dirpath) # get the subfolder name
if(subfolder_name in subfolder_counts.keys()): # check if key exists
subfolder_counts[subfolder_name] += len(filenames) # add count to existing key
else:
subfolder_counts[subfolder_name] = len(filenames) # add new key and count
# Get subfolders with more than one file
people_with_more_than_one_image = [folder for folder, count in subfolder_counts.items() if count > 1]
# %%
print(len(people_with_more_than_one_image)) # print number of people with more than one image
print(people_with_more_than_one_image[:30]) # print first 30 people with more than one image for reference
# %% [markdown]
# Thus we see that there are 1680 people in the dataset who have more than one image, and the first 30 of their names are printed below
# %% [markdown]
# # Part A
# %% [markdown]
# ## Q3 : Splitting into Test, Train and Validation by Person
#
# ### We initially split the dataset into 70% train and 15% test and 15% validation
# %%
import numpy as np
import random
# shuffle the names
random.shuffle(people_with_more_than_one_image)
# Defining the proportions for train, validation, and test sets
# for now assuming
train_ratio = 0.7
validation_ratio = 0.15
test_ratio = 0.15
# Calculate the sizes for each set
total_samples = len(people_with_more_than_one_image)
train_size = int(train_ratio * total_samples)
validation_size = int(validation_ratio * total_samples)
test_size = total_samples - train_size - validation_size
# Use NumPy to split the data
train_data_names = people_with_more_than_one_image[:train_size]
validation_data_names = people_with_more_than_one_image[train_size:train_size + validation_size]
test_data_names = people_with_more_than_one_image[train_size + validation_size:]
# Now you have your data split into train, validation, and test sets
print("Number of People in Train Data:", len(train_data_names))
print("Number of People in Validation Data:", len(validation_data_names))
print("Number of People in Test Data:", len(test_data_names))
# %%
class SiameseNetworkDataset(Dataset):
def __init__(self, personNames, dataset_size, transform=None, should_invert = False):
self.personNames = personNames # list of people names
self.transform = transform # transform to apply to images
self.should_invert = should_invert # whether to invert images
self.dataset_size = dataset_size
def __getitem__(self, index):
person1 = random.choice(self.personNames) # get a random person name
person2 = random.choice(self.personNames) # get another random person name
while person1 == person2: # make sure the two names are not the same
person2 = random.choice(self.personNames)
should_get_same_class = random.randint(0, 1) # randomly decide whether to get images of same person or not
if should_get_same_class: # if same person
img0_name = random.choice(os.listdir(root_directory + f'/{person1}'))
img1_name = random.choice(os.listdir(root_directory + f'/{person1}'))
person2 = person1 # set person2 to person1
else: # if different person
img0_name = random.choice(os.listdir(root_directory + f'/{person1}'))
img1_name = random.choice(os.listdir(root_directory + f'/{person2}'))
img0 = PIL.Image.open(root_directory + f'/{person1}' + f'/{img0_name}')
img1 = PIL.Image.open(root_directory + f'/{person2}' + f'/{img1_name}')
img0 = img0.convert("RGB") # convert to RGB
img1 = img1.convert("RGB")
if self.should_invert: # invert images if specified
img0 = PIL.ImageOps.invert(img0)
img1 = PIL.ImageOps.invert(img1)
if self.transform is not None: # apply transform if specified
img0 = self.transform(img0)
img1 = self.transform(img1)
if person1 == person2:
label = 1.0 # if same person
else:
label = -1.0 # if different person
return img0, img1, torch.from_numpy(np.array(label, dtype=np.float32)) # return images and label
def __len__(self):
return self.dataset_size
# %% [markdown]
# ### Let us visualize the working of the Custom Dataset created to train our Siaamese Network
# %%
visualize_dataset = SiameseNetworkDataset(personNames = train_data_names, dataset_size = 1000, transform = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor()]))
# %%
visualize_dataloader = DataLoader(visualize_dataset, shuffle=True, batch_size=8)
# %%
number_of_batches_visualized = 5
for batch in range(number_of_batches_visualized):
print(f"Batch : {batch}") # print batch number
dataiter = iter(visualize_dataloader) # get a batch
batch = next(dataiter) # get a batch
print(batch[2].numpy().T) # print labels
concatenated = torch.cat((batch[0], batch[1]), 0)
img = torchvision.utils.make_grid(concatenated) # concatenate images
npimg = img.numpy()
# visualize the batch
plt.figure(figsize = (16, 8))
plt.axis("off")
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# %% [markdown]
# Thus we see that our dataset is creating similar and dissimilar pairs of images and also the labels for them correctly. It creates a label of 1 for similar images and -1 for dissimilar images.
# %% [markdown]
# ## Q4: Selecting a pre trained model trained on ImageNet keeping in mind the tradeoff of computational resources as well as accuracy
#
# - We will be using Pytorch's ResNet-18 which is pre trained on ImageNet for this application
# %%
resnet50_model = models.resnet50(weights='ResNet50_Weights.DEFAULT') # load the ResNet50 model which has been trained on ImageNet for Transfer Learning
# %% [markdown]
# ## Q5: Appropriately crop and resize the images based on your computational resources
# - We reshape our images to 224x224x3 using the transform operation which we defined earlier for the dataset class
# - We also choose the batch sizes, dataset sizes for the train, test and validation datasets
# %%
train_dataset = SiameseNetworkDataset(personNames=train_data_names, dataset_size=1000, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=48)
valid_dataset = SiameseNetworkDataset(personNames=validation_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=8)
test_dataset = SiameseNetworkDataset(personNames=test_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
test_dataloader = DataLoader(test_dataset, shuffle=False, batch_size=8)
# %% [markdown]
# ## Q6: Defining the Siamese Network
# - We use the ResNet model as the base model for our Siamese Network
# - We drop the softmax layer of the ResNet model and add a fully connected layer with three hidden layers, we also use RELU activation for the hidden layers, the last layer output will not have any activation function and will serve as embedding for the images
# - We use transfer learning to train the model, we freeze the weights of the ResNet model and only train the weights of the fully connected layers
# %%
class SiameseNetwork(nn.Module):
def __init__(self, base_model):
super(SiameseNetwork, self).__init__()
self.base_model = nn.Sequential(*list(base_model.children())[:-1]) # get the base model ResNet50
# remove the last layer of ResNet50 which is the Softmax layer
for wt in self.base_model.parameters():
wt.requires_grad_(False) # freeze the weights of the base model ResNet50
# fully connected layer
self.fc = nn.Sequential(
nn.Linear(2048, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 128), # 128 dimensional embedding
)
def forward_one(self, x):
# forward pass of one image
x = self.base_model(x)
x = x.view(x.size()[0], -1)
x = self.fc(x)
return x
def forward(self, input1, input2):
output1 = self.forward_one(input1) # forward pass of first image
output2 = self.forward_one(input2) # forward pass of second image
return output1, output2 # return the two embeddings
# %% [markdown]
# ## Q6: Metric Learning Scheme (cosine similarity or Euclidean distance, paired with cross-entropy or hinge loss with a margin)
# - We use PyTorch's [`CosineEmbeddingLoss`](https://pytorch.org/docs/stable/generated/torch.nn.CosineEmbeddingLoss.html) as our loss function, which internally handles both cosine similarity paired with a hinge with user defined margin as the loss function.
# %%
if torch.cuda.is_available():
model = SiameseNetwork(resnet50_model).cuda() # use GPU if available
else:
model = SiameseNetwork(resnet50_model)
criterion = torch.nn.CosineEmbeddingLoss() # use Cosine Embedding Loss
optimizer = optim.Adagrad(model.parameters(), lr=0.01) # use Adagrad optimizer
# %% [markdown]
# ## Training the Model
# - we track the running training loss, and in order to perform the validation we choose a threshold 0.8 for the cosine similarity, if the cosine similarity is greater than 0.8 we consider the images to be similar, else we consider them to be dissimilar, and thus we track the running validation accuracy
# %%
def train_model(model, number_of_epochs, visualize=False):
threshold = 0.8 # threshold for cosine similarity above which two images are considered to be of the same person
curr_epoch = 0
counter = []
train_loss_history = []
valid_accuracy_history = []
for epoch in range(number_of_epochs):
avg_train_loss = 0.0 # average training loss
for i, data in enumerate(train_dataloader):
img0, img1, label = data
optimizer.zero_grad() # zero the gradients
if torch.cuda.is_available():
output1, output2 = model(img0.cuda(), img1.cuda())
else:
output1, output2 = model(img0, img1)
if torch.cuda.is_available():
loss = criterion(output1, output2, label.cuda())
else:
loss = criterion(output1, output2, label)
loss.backward() # backpropagate the loss
optimizer.step() # update the weights
avg_train_loss += loss.item() # add the loss to the average training loss
avg_train_loss /= len(train_dataloader)
correct = 0
# validation
for j, vdata in enumerate(valid_dataloader):
vimg0, vimg1, vlabel = vdata
if torch.cuda.is_available():
voutput1, voutput2 = model(vimg0.cuda(), vimg1.cuda())
else:
voutput1, voutput2 = model(vimg0, vimg1)
cosine_similarity = torch.nn.functional.cosine_similarity(
voutput1, voutput2)
pred_label = cosine_similarity.cpu().detach().numpy()
pred_label[pred_label > threshold] = 1.0 # if cosine similarity is above threshold, images are of same person
pred_label[pred_label <= threshold] = -1.0 # if cosine similarity is below threshold, images are of different people
correct += np.sum(pred_label == vlabel.cpu().detach().numpy()) # add the number of correct predictions
accuracy = correct*100/(8*len(valid_dataloader)) # calculate the accuracy denominator is 8 because batch size is 8
print("Epoch number {} : Training loss {} : Validation Accuracy {}%".format(
epoch, avg_train_loss, accuracy))
curr_epoch += 1
counter.append(curr_epoch)
train_loss_history.append(avg_train_loss)
valid_accuracy_history.append(accuracy)
if (visualize): # visualize the training loss and validation accuracy
plt.plot(counter, train_loss_history)
plt.xlabel("Epochs")
plt.ylabel("Training Loss")
plt.show()
plt.plot(counter, valid_accuracy_history)
plt.xlabel("Epochs")
plt.ylabel("Validation Accuracy")
plt.show()
# %% [markdown]
# ## Without Regularization and Image Augmentation
# %%
train_model(model, 75, visualize=True)
# %% [markdown]
# - We see that the training loss is decreasing and the moving average of our validation accuracy is increasing, thus we can say that our model is learning
# %%
torch.save(model, 'epochs75.pt')
# %%
model = torch.load('epochs75.pt')
# %% [markdown]
# ### Cosine Similarity Visualization
# %%
dataiter = iter(test_dataloader)
for i in range(3):
img0, img1, label = next(dataiter)
concatenated = torch.cat((img0, img1),0)
output1, output2 = model(img0.cuda(), img1.cuda()) # forward pass
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2) # calculate cosine similarity
print(cosine_similarity.cpu().detach().numpy().T) # print cosine similarity
img = torchvision.utils.make_grid(concatenated)
npimg = img.numpy()
# visualize the batch
plt.figure(figsize = (16, 8))
plt.axis("off")
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# %% [markdown]
# As we can see that the cosine similarities of the embeddings of the similar images are close to 1 and the cosine similarities of the embeddings of the dissimilar images further away from 1 closer to 0 and -1
# %% [markdown]
# ### Test Accuracy
# %%
# same code as in training used for validation accuracy, but now used for test accuracy
threshold = 0.8
correct = 0
for i, data in enumerate(test_dataloader):
img0, img1, label = data
if torch.cuda.is_available():
output1, output2 = model(img0.cuda(), img1.cuda())
else:
output1, output2 = model(img0, img1)
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
pred_label = cosine_similarity.cpu().detach().numpy()
pred_label[pred_label > threshold] = 1.0
pred_label[pred_label <= threshold] = -1.0
correct += np.sum(pred_label == label.cpu().detach().numpy())
print("Accuracy:", correct*100/(8*len(test_dataloader)))
# %% [markdown]
# ## 6 (a) With Image Augmentation
#
# - One out of random horizontal flip and random rotation of upto 10 degrees, also random color jitter (the brightness, contrast and saturation changed), gaussian blur, horizontal flip is applied at random with a probability of 0.2
#
# - We keep the same model architecture and hyperparameters as before, also optimiser and loss function are kept the same so that we can compare the results
# %%
augmentation_transform = transforms.Compose([
transforms.Resize((224, 224)), # resize to 224x224
transforms.RandomApply([ # apply random transformations
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(degrees=10), # rotate by 10 degrees
transforms.ColorJitter(brightness=0.05, contrast=0.05, # change brightness, contrast, saturation, hue
saturation=0.05, hue=0.05),
transforms.GaussianBlur(kernel_size=(3, 3), sigma=(0.1, 0.2)), # apply gaussian blur
], p=0.2), transforms.ToTensor()])
# %%
train_dataset = SiameseNetworkDataset(personNames=train_data_names, dataset_size=1000, transform=augmentation_transform)
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=48)
valid_dataset = SiameseNetworkDataset(personNames=validation_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=8)
test_dataset = SiameseNetworkDataset(personNames=test_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
test_dataloader = DataLoader(test_dataset, shuffle=False, batch_size=8)
# %%
if torch.cuda.is_available():
model = SiameseNetwork(resnet50_model).cuda()
else:
model = SiameseNetwork(resnet50_model)
criterion = torch.nn.CosineEmbeddingLoss()
optimizer = optim.Adagrad(model.parameters(), lr=0.01)
# %%
train_model(model, 75, visualize=True)
# %% [markdown]
# - We see that the training loss is decreasing and the moving average of our validation accuracy is increasing, thus we can say that our model is learning
# %%
torch.save(model, 'epochs75_aug.pt')
# %%
model = torch.load('epochs75_aug.pt')
# %% [markdown]
# ### Cosine Similarity Visualization
# %%
dataiter = iter(test_dataloader)
for i in range(3):
img0, img1, label = next(dataiter)
concatenated = torch.cat((img0, img1),0)
output1, output2 = model(img0.cuda(), img1.cuda())
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
print(cosine_similarity.cpu().detach().numpy().T)
img = torchvision.utils.make_grid(concatenated)
npimg = img.numpy()
plt.figure(figsize = (16, 8))
plt.axis("off")
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# %% [markdown]
# As we can see that the cosine similarities of the embeddings of the similar images are close to 1 and the cosine similarities of the embeddings of the dissimilar images further away from 1 closer to 0 and -1
# %% [markdown]
# ### Test Accuracy
# %%
threshold = 0.8
correct = 0
for i, data in enumerate(test_dataloader):
img0, img1, label = data
if torch.cuda.is_available():
output1, output2 = model(img0.cuda(), img1.cuda())
else:
output1, output2 = model(img0, img1)
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
pred_label = cosine_similarity.cpu().detach().numpy()
pred_label[pred_label > threshold] = 1.0
pred_label[pred_label <= threshold] = -1.0
correct += np.sum(pred_label == label.cpu().detach().numpy())
print("Accuracy:", correct*100/(8*len(test_dataloader)))
# %% [markdown]
#
# %% [markdown]
# ## 6 (b) With Regularization
#
# %%
train_dataset = SiameseNetworkDataset(personNames=train_data_names, dataset_size=1000, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=48)
valid_dataset = SiameseNetworkDataset(personNames=validation_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=8)
test_dataset = SiameseNetworkDataset(personNames=test_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
test_dataloader = DataLoader(test_dataset, shuffle=False, batch_size=8)
# %% [markdown]
# ### We use same architecture as before, but we add dropout layers with a probability of 0.15 after each hidden layer and also add L2 regularization with a weight decay of 0.0001
# %%
class SiameseNetwork(nn.Module):
def __init__(self, base_model):
super(SiameseNetwork, self).__init__()
self.base_model = nn.Sequential(*list(base_model.children())[:-1])
for wt in self.base_model.parameters():
wt.requires_grad_(False)
self.fc = nn.Sequential(
nn.Linear(2048, 512),
nn.ReLU(),
nn.Dropout(0.15), # add dropout
nn.Linear(512, 256),
nn.ReLU(),
nn.Dropout(0.15), # add dropout
nn.Linear(256, 128),
)
def forward_one(self, x):
x = self.base_model(x)
x = x.view(x.size()[0], -1)
x = self.fc(x)
return x
def forward(self, input1, input2):
output1 = self.forward_one(input1)
output2 = self.forward_one(input2)
return output1, output2
# %%
if torch.cuda.is_available():
model = SiameseNetwork(resnet50_model).cuda()
else:
model = SiameseNetwork(resnet50_model)
criterion = torch.nn.CosineEmbeddingLoss()
optimizer = optim.Adagrad(model.parameters(), lr=0.01, weight_decay=0.0001) # add weight decay
# %%
train_model(model, 75, visualize=True)
# %% [markdown]
# - We see that the training loss is decreasing and the moving average of our validation accuracy is increasing, thus we can say that our model is learning
# %%
torch.save(model, 'epochs75_reg.pt')
# %%
model = torch.load('epochs75_reg.pt')
# %% [markdown]
# ### Cosine Similarity Visualization
# %%
dataiter = iter(test_dataloader)
for i in range(3):
img0, img1, label = next(dataiter)
concatenated = torch.cat((img0, img1),0)
output1, output2 = model(img0.cuda(), img1.cuda())
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
print(cosine_similarity.cpu().detach().numpy().T)
img = torchvision.utils.make_grid(concatenated)
npimg = img.numpy()
plt.figure(figsize = (16, 8))
plt.axis("off")
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# %% [markdown]
# As we can see that the cosine similarities of the embeddings of the similar images are close to 1 and the cosine similarities of the embeddings of the dissimilar images further away from 1 closer to 0 and -1
# %% [markdown]
# ### Test Accuracy
# %%
threshold = 0.8
correct = 0
for i, data in enumerate(test_dataloader):
img0, img1, label = data
if torch.cuda.is_available():
output1, output2 = model(img0.cuda(), img1.cuda())
else:
output1, output2 = model(img0, img1)
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
pred_label = cosine_similarity.cpu().detach().numpy()
pred_label[pred_label > threshold] = 1.0
pred_label[pred_label <= threshold] = -1.0
correct += np.sum(pred_label == label.cpu().detach().numpy())
print("Accuracy:", correct*100/(8*len(test_dataloader)))
# %% [markdown]
# - Seeing the improvement in the test accuracy we can say that the model is learning better with regularization as well as image augmentation, so for all tasks from now on we will use regularization and image augmentation.
# %% [markdown]
# ## Q7 : Using Learning Rate Schedulers
# %%
augmentation_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.RandomApply([
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(degrees=10),
transforms.ColorJitter(brightness=0.05, contrast=0.05,
saturation=0.05, hue=0.05),
transforms.GaussianBlur(kernel_size=(3, 3), sigma=(0.1, 0.2)),
], p=0.2), transforms.ToTensor()])
# %%
train_dataset = SiameseNetworkDataset(personNames=train_data_names, dataset_size=1000, transform=augmentation_transform)
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=48)
valid_dataset = SiameseNetworkDataset(personNames=validation_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=8)
test_dataset = SiameseNetworkDataset(personNames=test_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
test_dataloader = DataLoader(test_dataset, shuffle=False, batch_size=8)
# %%
class SiameseNetwork(nn.Module):
def __init__(self, base_model):
super(SiameseNetwork, self).__init__()
self.base_model = nn.Sequential(*list(base_model.children())[:-1])
for wt in self.base_model.parameters():
wt.requires_grad_(False)
self.fc = nn.Sequential(
nn.Linear(2048, 512),
nn.ReLU(),
nn.Dropout(0.15),
nn.Linear(512, 256),
nn.ReLU(),
nn.Dropout(0.15),
nn.Linear(256, 128),
)
def forward_one(self, x):
x = self.base_model(x)
x = x.view(x.size()[0], -1)
x = self.fc(x)
return x
def forward(self, input1, input2):
output1 = self.forward_one(input1)
output2 = self.forward_one(input2)
return output1, output2
# %%
if torch.cuda.is_available():
model = SiameseNetwork(resnet50_model).cuda()
else:
model = SiameseNetwork(resnet50_model)
criterion = torch.nn.CosineEmbeddingLoss()
optimizer = optim.Adagrad(model.parameters(), lr=0.01, weight_decay=0.0001)
# %% [markdown]
#
# ## StepLR
# - We use the StepLR scheduler with step size 15 and gamma 0.5, which will half the learning rate every 10 epochs
# %%
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=15, gamma=0.5) # add learning rate scheduler
# %% [markdown]
# ### Modification to training function to include scheduler
# %%
def train_model_with_scheduler(model, number_of_epochs, scheduler, visualize=False):
# modified training function to use scheduler
threshold = 0.8
curr_epoch = 0
counter = []
train_loss_history = []
valid_accuracy_history = []
for epoch in range(number_of_epochs):
avg_train_loss = 0.0
for i, data in enumerate(train_dataloader):
img0, img1, label = data
optimizer.zero_grad()
if torch.cuda.is_available():
output1, output2 = model(img0.cuda(), img1.cuda())
else:
output1, output2 = model(img0, img1)
if torch.cuda.is_available():
loss = criterion(output1, output2, label.cuda())
else:
loss = criterion(output1, output2, label)
loss.backward()
optimizer.step()
avg_train_loss += loss.item()
avg_train_loss /= len(train_dataloader)
correct = 0
for j, vdata in enumerate(valid_dataloader):
vimg0, vimg1, vlabel = vdata
if torch.cuda.is_available():
voutput1, voutput2 = model(vimg0.cuda(), vimg1.cuda())
else:
voutput1, voutput2 = model(vimg0, vimg1)
cosine_similarity = torch.nn.functional.cosine_similarity(
voutput1, voutput2)
pred_label = cosine_similarity.cpu().detach().numpy()
pred_label[pred_label > threshold] = 1.0
pred_label[pred_label <= threshold] = -1.0
correct += np.sum(pred_label == vlabel.cpu().detach().numpy())
accuracy = correct*100/(8*len(valid_dataloader))
print("Epoch number {} : Training loss {} : Validation Accuracy {}% : Current LR {}".format(
epoch, avg_train_loss, accuracy, scheduler.get_last_lr()))
scheduler.step()
curr_epoch += 1
counter.append(curr_epoch)
train_loss_history.append(avg_train_loss)
valid_accuracy_history.append(accuracy)
if (visualize):
plt.plot(counter, train_loss_history)
plt.xlabel("Epochs")
plt.ylabel("Training Loss")
plt.show()
plt.plot(counter, valid_accuracy_history)
plt.xlabel("Epochs")
plt.ylabel("Validation Accuracy")
plt.show()
# %%
train_model_with_scheduler(model, 75, scheduler, visualize=True)
# %%
torch.save(model, 'epochs75_aug_reg_steplr.pt')
# %%
model = torch.load('epochs75_aug_reg_steplr.pt')
# %% [markdown]
# ### Cosine Similarity Visualization
# %%
dataiter = iter(test_dataloader)
for i in range(3):
img0, img1, label = next(dataiter)
concatenated = torch.cat((img0, img1),0)
output1, output2 = model(img0.cuda(), img1.cuda())
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
print(cosine_similarity.cpu().detach().numpy().T)
img = torchvision.utils.make_grid(concatenated)
npimg = img.numpy()
plt.figure(figsize = (16, 8))
plt.axis("off")
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# %% [markdown]
# As we can see that the cosine similarities of the embeddings of the similar images are close to 1 and the cosine similarities of the embeddings of the dissimilar images further away from 1 closer to 0 and -1
# %% [markdown]
# ### Test Accuracy
# %%
threshold = 0.8
correct = 0
for i, data in enumerate(test_dataloader):
img0, img1, label = data
if torch.cuda.is_available():
output1, output2 = model(img0.cuda(), img1.cuda())
else:
output1, output2 = model(img0, img1)
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
pred_label = cosine_similarity.cpu().detach().numpy()
pred_label[pred_label > threshold] = 1.0
pred_label[pred_label <= threshold] = -1.0
correct += np.sum(pred_label == label.cpu().detach().numpy())
print("Accuracy:", correct*100/(8*len(test_dataloader)))
# %% [markdown]
# - This doesn't perform as well as the constant learning rate one, however is able to achieve a test accuracy better as compared to the vanilla siamese network without regularization and image augmentation
# %% [markdown]
#
# ## PolynomialLR
# - We use the Polynomial LR scheduler with total iters 150, power of 1, which will linearly decrease the learning rate from 0.01 to 0.005 over the course of 75 epochs
# %%
if torch.cuda.is_available():
model = SiameseNetwork(resnet50_model).cuda()
else:
model = SiameseNetwork(resnet50_model)
criterion = torch.nn.CosineEmbeddingLoss()
optimizer = optim.Adagrad(model.parameters(), lr=0.01, weight_decay=0.0001)
# %%
scheduler = torch.optim.lr_scheduler.PolynomialLR(optimizer, total_iters=150, power=1) # use polynomial learning rate scheduler
# %%
train_model_with_scheduler(model, 75, scheduler, visualize=True)
# %%
torch.save(model, 'epochs75_aug_reg_polylr.pt')
# %%
model = torch.load('epochs75_aug_reg_polylr.pt')
# %% [markdown]
# ### Cosine Similarity Visualization
# %%
dataiter = iter(test_dataloader)
for i in range(3):
img0, img1, label = next(dataiter)
concatenated = torch.cat((img0, img1),0)
output1, output2 = model(img0.cuda(), img1.cuda())
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
print(cosine_similarity.cpu().detach().numpy().T)
img = torchvision.utils.make_grid(concatenated)
npimg = img.numpy()
plt.figure(figsize = (16, 8))
plt.axis("off")
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# %% [markdown]
# As we can see that the cosine similarities of the embeddings of the similar images are close to 1 and the cosine similarities of the embeddings of the dissimilar images further away from 1 closer to 0 and -1
# %% [markdown]
# ### Test Accuracy
# %%
threshold = 0.8
correct = 0
for i, data in enumerate(test_dataloader):
img0, img1, label = data
if torch.cuda.is_available():
output1, output2 = model(img0.cuda(), img1.cuda())
else:
output1, output2 = model(img0, img1)
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
pred_label = cosine_similarity.cpu().detach().numpy()
pred_label[pred_label > threshold] = 1.0
pred_label[pred_label <= threshold] = -1.0
correct += np.sum(pred_label == label.cpu().detach().numpy())
print("Accuracy:", correct*100/(8*len(test_dataloader)))
# %% [markdown]
# - This doesn't perform as well as constant learning rate with image augmentation and regularization, however is able to achieve a test accuracy better as compared to the vanilla siamese network as well as the stepLR one with regularization and image augmentation
# %% [markdown]
# #### Thus we see that both the learning rate schedulers are able to achieve good test accuracy results as compared to the vanilla siamese network, the polynomial LR scheduler performs better than the stepLR scheduler. However the constant learning rate with image augmentation and regularization performs the best.
#
# #### This may be because the StepLR leads to a sharper drop in learning rate per epoch and thus the model is not able to learn as well as the constant learning rate one, the polynomial LR scheduler is able to achieve better results than the stepLR scheduler because it decreases the learning rate linearly and thus the model is able to learn better.
# %% [markdown]
# ## Q8: Using Different Optimizers
#
# - Since we have already used the Adagrad optimizer, we will now use Adam and compare the results. We will pick the model which has the best test accuracy and use it for the next tasks. So we will compare the results of the constant learning rate with image augmentation and regularization with Adam and Adagrad optimizers.
# %%
augmentation_transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.RandomApply([
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(degrees=10),
transforms.ColorJitter(brightness=0.05, contrast=0.05,
saturation=0.05, hue=0.05),
transforms.GaussianBlur(kernel_size=(3, 3), sigma=(0.1, 0.2)),
], p=0.2), transforms.ToTensor()])
# %%
train_dataset = SiameseNetworkDataset(personNames=train_data_names, dataset_size=1000, transform=augmentation_transform)
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=48)
valid_dataset = SiameseNetworkDataset(personNames=validation_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
valid_dataloader = DataLoader(valid_dataset, shuffle=False, batch_size=8)
test_dataset = SiameseNetworkDataset(personNames=test_data_names, dataset_size=100, transform=transforms.Compose([
transforms.Resize((224, 224)), transforms.ToTensor()]))
test_dataloader = DataLoader(test_dataset, shuffle=False, batch_size=8)
# %%
class SiameseNetwork(nn.Module):
def __init__(self, base_model):
super(SiameseNetwork, self).__init__()
self.base_model = nn.Sequential(*list(base_model.children())[:-1])
for wt in self.base_model.parameters():
wt.requires_grad_(False)
self.fc = nn.Sequential(
nn.Linear(2048, 512),
nn.ReLU(),
nn.Dropout(0.15),
nn.Linear(512, 256),
nn.ReLU(),
nn.Dropout(0.15),
nn.Linear(256, 128),
)
def forward_one(self, x):
x = self.base_model(x)
x = x.view(x.size()[0], -1)
x = self.fc(x)
return x
def forward(self, input1, input2):
output1 = self.forward_one(input1)
output2 = self.forward_one(input2)
return output1, output2
# %%
if torch.cuda.is_available():
model = SiameseNetwork(resnet50_model).cuda()
else:
model = SiameseNetwork(resnet50_model)
criterion = torch.nn.CosineEmbeddingLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001) # use Adam optimizer instead of Adagrad
# %%
train_model(model, 75, visualize=True)
# %% [markdown]
# - We see that the training loss is decreasing and the moving average of our validation accuracy is increasing, thus we can say that our model is learning
# %%
torch.save(model, 'epochs75_aug_reg_adam.pt')
# %%
model = torch.load('epochs75_aug_reg_adam.pt')
# %% [markdown]
# ### Cosine Similarity Visualization
# %%
dataiter = iter(test_dataloader)
for i in range(3):
img0, img1, label = next(dataiter)
concatenated = torch.cat((img0, img1),0)
output1, output2 = model(img0.cuda(), img1.cuda())
cosine_similarity = torch.nn.functional.cosine_similarity(output1, output2)
print(cosine_similarity.cpu().detach().numpy().T)
img = torchvision.utils.make_grid(concatenated)
npimg = img.numpy()
plt.figure(figsize = (16, 8))
plt.axis("off")
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# %% [markdown]
# As we can see that the cosine similarities of the embeddings of the similar images are close to 1 and the cosine similarities of the embeddings of the dissimilar images further away from 1 closer to 0 and -1
# %% [markdown]
# ### Test Accuracy
# %%
threshold = 0.8
correct = 0