AJain1234 commited on
Commit
ac10abd
·
verified ·
1 Parent(s): 71f4725

Update Experiments/Resnet50_classification.py

Browse files
Files changed (1) hide show
  1. Experiments/Resnet50_classification.py +127 -127
Experiments/Resnet50_classification.py CHANGED
@@ -1,128 +1,128 @@
1
- import torchvision.datasets as datasets
2
- import matplotlib.pyplot as plt
3
- import tensorflow
4
- import numpy as np
5
- import warnings
6
- warnings.filterwarnings("ignore")
7
- import torchvision.models as models
8
- import torch
9
- from tqdm import tqdm
10
- import torch.nn as nn
11
- import torchvision.transforms as v2
12
- from torch.utils.data import DataLoader
13
- import torchvision.datasets as datasets
14
- from sklearn.metrics.pairwise import euclidean_distances
15
- from PIL import Image,ImageFilter
16
- import torchvision.transforms as transforms
17
- import pickle
18
- import os
19
- os.system("gdown --id 1qO2OLR7skDibo1LaMKD3CiOl_jaCTZ0h")
20
-
21
-
22
- IMAGE_SIZE = 224
23
- mean, std = [0.4914, 0.4822, 0.4465], [0.247, 0.243, 0.261]
24
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
25
-
26
-
27
- def unpickle(file):
28
- with open(file, 'rb') as fo:
29
- dict = pickle.load(fo, encoding='bytes')
30
- return dict
31
-
32
- class HiddenLayer(nn.Module):
33
- def __init__(self, pretrained_model):
34
- super().__init__()
35
- self.premodel = pretrained_model
36
- self.new_layer = nn.Sequential(
37
- nn.Linear(1000, 512),
38
- nn.LeakyReLU(),
39
- nn.Linear(512, 512),
40
- nn.LeakyReLU(),
41
- nn.Linear(512, 256),
42
- nn.LeakyReLU(),
43
- nn.Linear(256, 10)
44
- )
45
-
46
- def forward(self, x):
47
- out = self.premodel(x)
48
- out_new_layer = self.new_layer(out)
49
- return out_new_layer
50
-
51
-
52
- def predict(features_path,image):
53
- batch1 = unpickle(r"Model\data\data_batch_1")
54
- batch2 = unpickle(r"Model\data\data_batch_2")
55
- batch3 = unpickle(r"Model\data\data_batch_3")
56
- batch4 = unpickle(r"Model\data\data_batch_4")
57
- batch5 = unpickle(r"Model\data\data_batch_5")
58
- test_batch = unpickle(r"Model\data\test_batch")
59
- train_batch = [batch1,batch2,batch3,batch4,batch5]
60
- train_y = []
61
- train_x = []
62
- for batch in train_batch:
63
- y_data = batch[b'labels']
64
- x_data = batch[b'data']
65
- x_data = x_data.reshape(len(x_data),3,32,32).transpose(0,2,3,1)
66
-
67
- for i in range(len(y_data)):
68
- train_y.append(y_data[i])
69
-
70
- for i in range(len(y_data)):
71
- train_x.append(x_data[i])
72
-
73
- features = torch.load(features_path)
74
-
75
- resnet_train_data = []
76
- for i in range(len(features)):
77
- resnet_train_data.append((features[i],train_y[i]))
78
-
79
- class_images_dict = {}
80
- for batch_idx, (images, labels) in enumerate(resnet_train_data):
81
- if labels not in class_images_dict:
82
- class_images_dict[labels] = []
83
- class_images_dict[labels].append(batch_idx)
84
-
85
- transform = transforms.Compose([
86
- transforms.Resize((224, 224)),
87
- transforms.ToTensor(),
88
- transforms.Normalize(mean, std)
89
- ])
90
- pil_image = Image.fromarray(image)
91
- image_tensor = transform(pil_image).unsqueeze(0)
92
- resnet = models.resnet50(pretrained=True)
93
- model_check = HiddenLayer(resnet)
94
- model_check.load_state_dict(torch.load("CIFAR_end_hll.pt"))
95
- model_check.eval()
96
-
97
- with torch.no_grad():
98
- z = model_check(image_tensor)
99
- _, test_label = torch.max(z, 1)
100
-
101
- return test_label,z,features,class_images_dict,train_x
102
-
103
-
104
-
105
- def retrieve(image,k,feature_path=r"Model\Resnet50_train_features.pt"):
106
- print(image.shape)
107
- test_label,z,features,class_images_dict,train_x = predict(feature_path,image)
108
- class_indices = class_images_dict[test_label.item()]
109
- class_features = [(features[idx], idx) for idx in class_indices]
110
- test_features = z.cpu().detach().numpy()
111
- distances = euclidean_distances(test_features, [f[0].cpu() for f in class_features])
112
- sorted_indices = np.argsort(distances.flatten())[:k]
113
- closest_indices = [class_features[idx][1] for idx in sorted_indices]
114
- retrieved_images = []
115
- for i, idx in enumerate(closest_indices):
116
- closest_image = Image.fromarray(train_x[idx])
117
- sharpened_closest_image = closest_image.filter(ImageFilter.SHARPEN)
118
- retrieved_images.append(sharpened_closest_image)
119
-
120
- return retrieved_images
121
-
122
-
123
-
124
-
125
-
126
-
127
- # test_image = Image.open("/kaggle/input/planes/download.jpeg")
128
  # retrieved_images = retrieve(test_image,3)
 
1
+ import torchvision.datasets as datasets
2
+ import matplotlib.pyplot as plt
3
+ import tensorflow
4
+ import numpy as np
5
+ import warnings
6
+ warnings.filterwarnings("ignore")
7
+ import torchvision.models as models
8
+ import torch
9
+ from tqdm import tqdm
10
+ import torch.nn as nn
11
+ import torchvision.transforms as v2
12
+ from torch.utils.data import DataLoader
13
+ import torchvision.datasets as datasets
14
+ from sklearn.metrics.pairwise import euclidean_distances
15
+ from PIL import Image,ImageFilter
16
+ import torchvision.transforms as transforms
17
+ import pickle
18
+ import os
19
+ os.system("gdown --id 1qO2OLR7skDibo1LaMKD3CiOl_jaCTZ0h")
20
+
21
+
22
+ IMAGE_SIZE = 224
23
+ mean, std = [0.4914, 0.4822, 0.4465], [0.247, 0.243, 0.261]
24
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
25
+
26
+
27
+ def unpickle(file):
28
+ with open(file, 'rb') as fo:
29
+ dict = pickle.load(fo, encoding='bytes')
30
+ return dict
31
+
32
+ class HiddenLayer(nn.Module):
33
+ def __init__(self, pretrained_model):
34
+ super().__init__()
35
+ self.premodel = pretrained_model
36
+ self.new_layer = nn.Sequential(
37
+ nn.Linear(1000, 512),
38
+ nn.LeakyReLU(),
39
+ nn.Linear(512, 512),
40
+ nn.LeakyReLU(),
41
+ nn.Linear(512, 256),
42
+ nn.LeakyReLU(),
43
+ nn.Linear(256, 10)
44
+ )
45
+
46
+ def forward(self, x):
47
+ out = self.premodel(x)
48
+ out_new_layer = self.new_layer(out)
49
+ return out_new_layer
50
+
51
+
52
+ def predict(features_path,image):
53
+ batch1 = unpickle(r"Model/data/data_batch_1")
54
+ batch2 = unpickle(r"Model\data\data_batch_2")
55
+ batch3 = unpickle(r"Model\data\data_batch_3")
56
+ batch4 = unpickle(r"Model\data\data_batch_4")
57
+ batch5 = unpickle(r"Model\data\data_batch_5")
58
+ test_batch = unpickle(r"Model\data\test_batch")
59
+ train_batch = [batch1,batch2,batch3,batch4,batch5]
60
+ train_y = []
61
+ train_x = []
62
+ for batch in train_batch:
63
+ y_data = batch[b'labels']
64
+ x_data = batch[b'data']
65
+ x_data = x_data.reshape(len(x_data),3,32,32).transpose(0,2,3,1)
66
+
67
+ for i in range(len(y_data)):
68
+ train_y.append(y_data[i])
69
+
70
+ for i in range(len(y_data)):
71
+ train_x.append(x_data[i])
72
+
73
+ features = torch.load(features_path)
74
+
75
+ resnet_train_data = []
76
+ for i in range(len(features)):
77
+ resnet_train_data.append((features[i],train_y[i]))
78
+
79
+ class_images_dict = {}
80
+ for batch_idx, (images, labels) in enumerate(resnet_train_data):
81
+ if labels not in class_images_dict:
82
+ class_images_dict[labels] = []
83
+ class_images_dict[labels].append(batch_idx)
84
+
85
+ transform = transforms.Compose([
86
+ transforms.Resize((224, 224)),
87
+ transforms.ToTensor(),
88
+ transforms.Normalize(mean, std)
89
+ ])
90
+ pil_image = Image.fromarray(image)
91
+ image_tensor = transform(pil_image).unsqueeze(0)
92
+ resnet = models.resnet50(pretrained=True)
93
+ model_check = HiddenLayer(resnet)
94
+ model_check.load_state_dict(torch.load("CIFAR_end_hll.pt"))
95
+ model_check.eval()
96
+
97
+ with torch.no_grad():
98
+ z = model_check(image_tensor)
99
+ _, test_label = torch.max(z, 1)
100
+
101
+ return test_label,z,features,class_images_dict,train_x
102
+
103
+
104
+
105
+ def retrieve(image,k,feature_path=r"Model\Resnet50_train_features.pt"):
106
+ print(image.shape)
107
+ test_label,z,features,class_images_dict,train_x = predict(feature_path,image)
108
+ class_indices = class_images_dict[test_label.item()]
109
+ class_features = [(features[idx], idx) for idx in class_indices]
110
+ test_features = z.cpu().detach().numpy()
111
+ distances = euclidean_distances(test_features, [f[0].cpu() for f in class_features])
112
+ sorted_indices = np.argsort(distances.flatten())[:k]
113
+ closest_indices = [class_features[idx][1] for idx in sorted_indices]
114
+ retrieved_images = []
115
+ for i, idx in enumerate(closest_indices):
116
+ closest_image = Image.fromarray(train_x[idx])
117
+ sharpened_closest_image = closest_image.filter(ImageFilter.SHARPEN)
118
+ retrieved_images.append(sharpened_closest_image)
119
+
120
+ return retrieved_images
121
+
122
+
123
+
124
+
125
+
126
+
127
+ # test_image = Image.open("/kaggle/input/planes/download.jpeg")
128
  # retrieved_images = retrieve(test_image,3)