Mojo commited on
Commit
923fe1a
·
1 Parent(s): 9efd6ad

Added new files

Browse files
Files changed (1) hide show
  1. utilities/visualise.py +1 -335
utilities/visualise.py CHANGED
@@ -1,6 +1,5 @@
1
  import matplotlib.pyplot as plt
2
  from torchvision import transforms
3
- import torch
4
 
5
 
6
  def plot_class_label_counts(data_loader, classes):
@@ -76,337 +75,4 @@ def plot_incorrect_preds(incorrect, classes, num_imgs):
76
  )
77
  plt.xticks([])
78
  plt.yticks([])
79
- plt.tight_layout()
80
-
81
-
82
- def display_cifar_data_samples(data_set, number_of_samples: int, classes: list):
83
- """
84
- Function to display samples for data_set
85
- :param data_set: Train or Test data_set transformed to Tensor
86
- :param number_of_samples: Number of samples to be displayed
87
- :param classes: Name of classes to be displayed
88
- """
89
- # Get batch from the data_set
90
- batch_data = []
91
- batch_label = []
92
- for count, item in enumerate(data_set):
93
- if not count <= number_of_samples:
94
- break
95
- batch_data.append(item[0])
96
- batch_label.append(item[1])
97
- batch_data = torch.stack(batch_data, dim=0).numpy()
98
-
99
- # Plot the samples from the batch
100
- fig = plt.figure()
101
- x_count = 5
102
- y_count = 1 if number_of_samples <= 5 else math.floor(number_of_samples / x_count)
103
-
104
- for i in range(number_of_samples):
105
- plt.subplot(y_count, x_count, i + 1)
106
- plt.tight_layout()
107
- plt.imshow(np.transpose(batch_data[i].squeeze(), (1, 2, 0)))
108
- plt.title(classes[batch_label[i]])
109
- plt.xticks([])
110
- plt.yticks([])
111
-
112
-
113
- # ---------------------------- MISCLASSIFIED DATA ----------------------------
114
- def display_cifar_misclassified_data(data: list,
115
- classes: list[str],
116
- inv_normalize: transforms.Normalize,
117
- number_of_samples: int = 10):
118
- """
119
- Function to plot images with labels
120
- :param data: List[Tuple(image, label)]
121
- :param classes: Name of classes in the dataset
122
- :param inv_normalize: Mean and Standard deviation values of the dataset
123
- :param number_of_samples: Number of images to print
124
- """
125
- fig = plt.figure(figsize=(10, 10))
126
-
127
- x_count = 5
128
- y_count = 1 if number_of_samples <= 5 else math.floor(number_of_samples / x_count)
129
-
130
- for i in range(number_of_samples):
131
- plt.subplot(y_count, x_count, i + 1)
132
- img = data[i][0].squeeze().to('cpu')
133
- img = inv_normalize(img)
134
- plt.imshow(np.transpose(img, (1, 2, 0)))
135
- plt.title(r"Correct: " + classes[data[i][1].item()] + '\n' + 'Output: ' + classes[data[i][2].item()])
136
- plt.xticks([])
137
- plt.yticks([])
138
-
139
-
140
- def display_mnist_misclassified_data(data: list,
141
- number_of_samples: int = 10):
142
- """
143
- Function to plot images with labels
144
- :param data: List[Tuple(image, label)]
145
- :param number_of_samples: Number of images to print
146
- """
147
- fig = plt.figure(figsize=(8, 5))
148
-
149
- x_count = 5
150
- y_count = 1 if number_of_samples <= 5 else math.floor(number_of_samples / x_count)
151
-
152
- for i in range(number_of_samples):
153
- plt.subplot(y_count, x_count, i + 1)
154
- img = data[i][0].squeeze(0).to('cpu')
155
- plt.imshow(np.transpose(img, (1, 2, 0)), cmap='gray')
156
- plt.title(r"Correct: " + str(data[i][1].item()) + '\n' + 'Output: ' + str(data[i][2].item()))
157
- plt.xticks([])
158
- plt.yticks([])
159
-
160
-
161
- # ---------------------------- AUGMENTATION SAMPLES ----------------------------
162
- def visualize_cifar_augmentation(data_set, data_transforms):
163
- """
164
- Function to visualize the augmented data
165
- :param data_set: Dataset without transformations
166
- :param data_transforms: Dictionary of transforms
167
- """
168
- sample, label = data_set[6]
169
- total_augmentations = len(data_transforms)
170
-
171
- fig = plt.figure(figsize=(10, 5))
172
- for count, (key, trans) in enumerate(data_transforms.items()):
173
- if count == total_augmentations - 1:
174
- break
175
- plt.subplot(math.ceil(total_augmentations / 5), 5, count + 1)
176
- augmented = trans(image=sample)['image']
177
- plt.imshow(augmented)
178
- plt.title(key)
179
- plt.xticks([])
180
- plt.yticks([])
181
-
182
-
183
- def visualize_mnist_augmentation(data_set, data_transforms):
184
- """
185
- Function to visualize the augmented data
186
- :param data_set: Dataset to visualize the augmentations
187
- :param data_transforms: Dictionary of transforms
188
- """
189
- sample, label = data_set[6]
190
- total_augmentations = len(data_transforms)
191
-
192
- fig = plt.figure(figsize=(10, 5))
193
- for count, (key, trans) in enumerate(data_transforms.items()):
194
- if count == total_augmentations - 1:
195
- break
196
- plt.subplot(math.ceil(total_augmentations / 5), 5, count + 1)
197
- img = trans(sample).to('cpu')
198
- plt.imshow(np.transpose(img, (1, 2, 0)), cmap='gray')
199
- plt.title(key)
200
- plt.xticks([])
201
- plt.yticks([])
202
-
203
-
204
- # ---------------------------- LOSS AND ACCURACIES ----------------------------
205
- def display_loss_and_accuracies(train_losses: list,
206
- train_acc: list,
207
- test_losses: list,
208
- test_acc: list,
209
- plot_size: tuple = (10, 10)):
210
- """
211
- Function to display training and test information(losses and accuracies)
212
- :param train_losses: List containing training loss of each epoch
213
- :param train_acc: List containing training accuracy of each epoch
214
- :param test_losses: List containing test loss of each epoch
215
- :param test_acc: List containing test accuracy of each epoch
216
- :param plot_size: Size of the plot
217
- """
218
- # Create a plot of 2x2 of size
219
- fig, axs = plt.subplots(2, 2, figsize=plot_size)
220
-
221
- # Plot the training loss and accuracy for each epoch
222
- axs[0, 0].plot(train_losses)
223
- axs[0, 0].set_title("Training Loss")
224
- axs[1, 0].plot(train_acc)
225
- axs[1, 0].set_title("Training Accuracy")
226
-
227
- # Plot the test loss and accuracy for each epoch
228
- axs[0, 1].plot(test_losses)
229
- axs[0, 1].set_title("Test Loss")
230
- axs[1, 1].plot(test_acc)
231
- axs[1, 1].set_title("Test Accuracy")
232
-
233
-
234
- # ---------------------------- Feature Maps and Kernels ----------------------------
235
-
236
- @dataclass
237
- class ConvLayerInfo:
238
- """
239
- Data Class to store Conv layer's information
240
- """
241
- layer_number: int
242
- weights: torch.nn.parameter.Parameter
243
- layer_info: torch.nn.modules.conv.Conv2d
244
-
245
-
246
- class FeatureMapVisualizer:
247
- """
248
- Class to visualize Feature Map of the Layers
249
- """
250
-
251
- def __init__(self, model):
252
- """
253
- Contructor
254
- :param model: Model Architecture
255
- """
256
- self.conv_layers = []
257
- self.outputs = []
258
- self.layerwise_kernels = None
259
-
260
- # Disect the model
261
- counter = 0
262
- model_children = model.children()
263
- for children in model_children:
264
- if type(children) == nn.Sequential:
265
- for child in children:
266
- if type(child) == nn.Conv2d:
267
- counter += 1
268
- self.conv_layers.append(ConvLayerInfo(layer_number=counter,
269
- weights=child.weight,
270
- layer_info=child)
271
- )
272
-
273
- def get_model_weights(self):
274
- """
275
- Method to get the model weights
276
- """
277
- model_weights = [layer.weights for layer in self.conv_layers]
278
- return model_weights
279
-
280
- def get_conv_layers(self):
281
- """
282
- Get the convolution layers
283
- """
284
- conv_layers = [layer.layer_info for layer in self.conv_layers]
285
- return conv_layers
286
-
287
- def get_total_conv_layers(self) -> int:
288
- """
289
- Get total number of convolution layers
290
- """
291
- out = self.get_conv_layers()
292
- return len(out)
293
-
294
- def feature_maps_of_all_kernels(self, image: torch.Tensor) -> dict:
295
- """
296
- Get feature maps from all the kernels of all the layers
297
- :param image: Image to be passed to the network
298
- """
299
- image = image.unsqueeze(0)
300
- image = image.to('cpu')
301
-
302
- outputs = {}
303
-
304
- layers = self.get_conv_layers()
305
- for index, layer in enumerate(layers):
306
- image = layer(image)
307
- outputs[str(layer)] = image
308
- self.outputs = outputs
309
- return outputs
310
-
311
- def visualize_feature_map_of_kernel(self, image: torch.Tensor, kernel_number: int) -> None:
312
- """
313
- Function to visualize feature map of kernel number from each layer
314
- :param image: Image passed to the network
315
- :param kernel_number: Number of kernel in each layer (Should be less than or equal to the minimum number of kernel in the network)
316
- """
317
- # List to store processed feature maps
318
- processed = []
319
-
320
- # Get feature maps from all kernels of all the conv layers
321
- outputs = self.feature_maps_of_all_kernels(image)
322
-
323
- # Extract the n_th kernel's output from each layer and convert it to grayscale
324
- for feature_map in outputs.values():
325
- try:
326
- feature_map = feature_map[0][kernel_number]
327
- except IndexError:
328
- print("Filter number should be less than the minimum number of channels in a network")
329
- break
330
- finally:
331
- gray_scale = feature_map / feature_map.shape[0]
332
- processed.append(gray_scale.data.numpy())
333
-
334
- # Plot the Feature maps with layer and kernel number
335
- x_range = len(outputs) // 5 + 4
336
- fig = plt.figure(figsize=(10, 10))
337
- for i in range(len(processed)):
338
- a = fig.add_subplot(x_range, 5, i + 1)
339
- imgplot = plt.imshow(processed[i])
340
- a.axis("off")
341
- title = f"{list(outputs.keys())[i].split('(')[0]}_l{i + 1}_k{kernel_number}"
342
- a.set_title(title, fontsize=10)
343
-
344
- def get_max_kernel_number(self):
345
- """
346
- Function to get maximum number of kernels in the network (for a layer)
347
- """
348
- layers = self.get_conv_layers()
349
- channels = [layer.out_channels for layer in layers]
350
- self.layerwise_kernels = channels
351
- return max(channels)
352
-
353
- def visualize_kernels_from_layer(self, layer_number: int):
354
- """
355
- Visualize Kernels from a layer
356
- :param layer_number: Number of layer from which kernels are to be visualized
357
- """
358
- # Get the kernels number for each layer
359
- self.get_max_kernel_number()
360
-
361
- # Zero Indexing
362
- layer_number = layer_number - 1
363
- _kernels = self.layerwise_kernels[layer_number]
364
-
365
- grid = math.ceil(math.sqrt(_kernels))
366
-
367
- plt.figure(figsize=(5, 4))
368
- model_weights = self.get_model_weights()
369
- _layer_weights = model_weights[layer_number].cpu()
370
- for i, filter in enumerate(_layer_weights):
371
- plt.subplot(grid, grid, i + 1)
372
- plt.imshow(filter[0, :, :].detach(), cmap='gray')
373
- plt.axis('off')
374
- plt.show()
375
-
376
-
377
- # ---------------------------- Confusion Matrix ----------------------------
378
- def visualize_confusion_matrix(classes: list[str], device: str, model: 'DL Model',
379
- test_loader: torch.utils.data.DataLoader):
380
- """
381
- Function to generate and visualize confusion matrix
382
- :param classes: List of class names
383
- :param device: cuda/cpu
384
- :param model: Model Architecture
385
- :param test_loader: DataLoader for test set
386
- """
387
- nb_classes = len(classes)
388
- device = 'cuda'
389
- cm = torch.zeros(nb_classes, nb_classes)
390
-
391
- model.eval()
392
- with torch.no_grad():
393
- for inputs, labels in test_loader:
394
- inputs = inputs.to(device)
395
- labels = labels.to(device)
396
- model = model.to(device)
397
-
398
- preds = model(inputs)
399
- preds = preds.argmax(dim=1)
400
-
401
- for t, p in zip(labels.view(-1), preds.view(-1)):
402
- cm[t, p] = cm[t, p] + 1
403
-
404
- # Build confusion matrix
405
- labels = labels.to('cpu')
406
- preds = preds.to('cpu')
407
- cf_matrix = confusion_matrix(labels, preds)
408
- df_cm = pd.DataFrame(cf_matrix / np.sum(cf_matrix, axis=1)[:, None],
409
- index=[i for i in classes],
410
- columns=[i for i in classes])
411
- plt.figure(figsize=(12, 7))
412
- sn.heatmap(df_cm, annot=True)
 
1
  import matplotlib.pyplot as plt
2
  from torchvision import transforms
 
3
 
4
 
5
  def plot_class_label_counts(data_loader, classes):
 
75
  )
76
  plt.xticks([])
77
  plt.yticks([])
78
+ plt.tight_layout()