-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcam_analysis_timm.py
More file actions
496 lines (385 loc) · 20 KB
/
cam_analysis_timm.py
File metadata and controls
496 lines (385 loc) · 20 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
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
import pdb
import torch
import numpy as np
import os
import torch.nn.functional as F
import matplotlib.pyplot as plt
from Utils.LitModel import LitModel
from Datasets.SSDataModule import SSAudioDataModule
from Demo_Parameters import Parameters
# Create a mock args class to simulate argparse
class MockArgs:
def __init__(self):
self.save_results = True
self.folder = 'Saved_Models/'
self.model = 'convnextv2_tiny.fcmae'
self.histogram = False
self.data_selection = 0
self.numBins = 16
self.feature_extraction = False
self.use_pretrained = True
self.train_batch_size = 64
self.val_batch_size = 128
self.test_batch_size = 128
self.num_epochs = 1
self.resize_size = 256
self.lr = 5e-5
self.use_cuda = True
self.audio_feature = 'STFT'
self.optimizer = 'Adam'
self.patience = 1
self.sample_rate = 32000
# Instantiate mock args and load parameters
args = MockArgs()
Params = Parameters(args)
# Set up constants from Params dictionary
s_rate = Params['sample_rate']
Dataset_n = Params['Dataset']
model_name = Params['Model_name']
num_classes = Params['num_classes'][Dataset_n]
batch_size = Params['batch_size']['train']
data_dir = Params["data_dir"]
new_dir = Params["new_dir"]
# Set up CUDA if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Set PyTorch precision
torch.set_float32_matmul_precision('medium')
data_dir = './Datasets/DeepShip'
batch_size = 32
sample_rate = 32000
data_module = SSAudioDataModule(new_dir, batch_size=batch_size, sample_rate=Params['sample_rate'])
data_module.prepare_data()
split_indices_path = 'split_indices.txt' # Path to split indices file
# Create a mapping of classes to indices
class_to_idx = {
'Cargo': 0,
'Passengership': 1,
'Tanker': 2,
'Tug': 3,
}
# Define the run number and model checkpoint path
run_number = 0 # Change this as needed to select Run_0, Run_1, or Run_2
model_folder = f'PANN_Weights/convnextv2_tiny.fcmae_b64_32000/Run_{run_number}/convnextv2_tiny.fcmae/version_0/checkpoints/'
# Automatically find the checkpoint file in the directory
checkpoint_files = [f for f in os.listdir(model_folder) if f.endswith('.ckpt')]
best_model_path = os.path.join(model_folder, checkpoint_files[0]) # Use the first found checkpoint
# Load the best model from checkpoint
best_model = LitModel.load_from_checkpoint(
checkpoint_path=best_model_path,
Params=Params,
model_name=model_name,
num_classes=num_classes,
Dataset=Dataset_n,
pretrained_loaded=True,
run_number=run_number
)
# Move the model to the appropriate device (GPU or CPU)
best_model.to(device)
# Create a test dataloader
test_loader = data_module.test_dataloader()
# Print model structure for reference
print("Model Architecture:\n", best_model)
# Evaluate test accuracy
best_model.eval() # Set the model to evaluation mode
print('\n')
# Select one correctly classified sample per class for CAM analysis
correct_samples_per_class = {}
# Add a flag to ensure we only print once
printed_once = False
for batch in test_loader:
inputs, labels = batch
inputs, labels = inputs.to(device), labels.to(device)
# Forward pass through the model
outputs = best_model(inputs)
# Print shapes for debugging only once
if not printed_once:
print("First element of outputs:", outputs[0].shape)
print("Second element of outputs (logits):", outputs[1].shape)
printed_once = True
# Extract logits and compute predictions
logits = outputs[1]
_, preds = torch.max(logits, dim=1)
# Check for correctly classified samples within valid index range
for i in range(len(labels)):
if preds[i] == labels[i]:
class_name = list(class_to_idx.keys())[list(class_to_idx.values()).index(labels[i].item())]
if class_name not in correct_samples_per_class:
correct_samples_per_class[class_name] = (inputs[i], labels[i])
# Stop once we have one sample per class
if len(correct_samples_per_class) == len(class_to_idx):
break
# Break outer loop if we have all classes covered
if len(correct_samples_per_class) == len(class_to_idx):
break
### CAM ###
# from contextlib import contextmanager
# @contextmanager
# def register_hooks(layer, forward_hook, backward_hook):
# forward_handle = layer.register_forward_hook(forward_hook)
# backward_handle = layer.register_full_backward_hook(backward_hook)
# try:
# yield
# finally:
# forward_handle.remove()
# backward_handle.remove()
# def generate_gradcam(model, input_tensor, target_class, last_conv_layer):
# gradients = []
# activations = []
# def backward_hook(module, grad_input, grad_output):
# gradients.append(grad_output[0])
# def forward_hook(module, input, output):
# activations.append(output)
# with register_hooks(last_conv_layer, forward_hook, backward_hook):
# # Forward pass
# model.eval()
# logits = model(input_tensor)[1] # Get logits from fully connected layer
# # Backward pass for target class
# model.zero_grad()
# target_score = logits[0][target_class]
# target_score.backward()
# # Get gradients and activations
# gradients = gradients[0]
# activations = activations[0]
# # Compute weights using GAP
# weights = torch.mean(gradients, dim=(2, 3))
# # Compute Grad-CAM
# cam = torch.zeros(activations.shape[2:], device=input_tensor.device)
# for i in range(weights.shape[1]):
# cam += weights[0, i] * activations[0, i]
# cam = F.relu(cam) # Apply ReLU
# # cam -= cam.min()
# # if cam.max() > 0:
# # cam /= cam.max()
# cam = (cam - cam.min()) / (cam.max() + 1e-8)
# return cam.cpu().detach().numpy()
# # Dictionaries to store correctly and misclassified samples per class
# correct_samples_per_class = {class_name: [] for class_name in class_to_idx.keys()}
# misclassified_samples_per_class = {class_name: [] for class_name in class_to_idx.keys()}
# # Populate dictionaries with correctly and misclassified samples
# for batch in test_loader:
# inputs, labels = batch
# inputs, labels = inputs.to(device), labels.to(device)
# # Pass raw waveform directly to the model
# outputs = best_model(inputs) # The model handles spectrogram/log-mel extraction internally
# _, preds = torch.max(outputs[1], dim=1) # Get predictions
# for i in range(len(labels)):
# true_class_name = list(class_to_idx.keys())[list(class_to_idx.values()).index(labels[i].item())]
# if preds[i] == labels[i]: # Correctly classified
# correct_samples_per_class[true_class_name].append((inputs[i], labels[i]))
# else: # Misclassified
# predicted_class_name = list(class_to_idx.keys())[list(class_to_idx.values()).index(preds[i].item())]
# misclassified_samples_per_class[true_class_name].append((inputs[i], labels[i], predicted_class_name))
# # Adjust last convolutional layer for ConvNeXt-based model
# last_conv_layer = best_model.model_ft.backbone.stages[-1].blocks[-1].conv_dw # Last depthwise conv layer
# # Function to process Grad-CAM for a set of samples (correct or misclassified)
# def process_gradcam(samples_dict, description, save_single_example=True):
# for class_name, samples in samples_dict.items():
# print(f"Processing Grad-CAM for {len(samples)} {description} samples in class: {class_name}")
# aggregated_cam = None
# single_example_saved = False # Track if a single example has been saved
# for idx, sample_data in enumerate(samples):
# sample_input = sample_data[0].unsqueeze(0).to(device) # Add batch dimension
# target_class = sample_data[1].item() # Get target class index
# # Pass raw waveform directly to the model (no external spectrogram extraction)
# outputs = best_model(sample_input) # The model handles spectrogram/log-mel extraction internally
# # Generate Grad-CAM heatmap using the last convolutional layer
# cam = generate_gradcam(best_model, sample_input, target_class, last_conv_layer)
# # Resize CAM to match input dimensions (e.g., spectrogram size)
# cam_resized = F.interpolate(torch.tensor(cam).unsqueeze(0).unsqueeze(0), size=(501, 64), mode='bilinear', align_corners=False)
# cam_resized_np = cam_resized.squeeze().numpy()
# # Normalize the individual CAM before aggregation
# cam_resized_np = (cam_resized_np - cam_resized_np.min()) / (cam_resized_np.max() + 1e-8)
# # Aggregate CAMs (e.g., sum or average)
# if aggregated_cam is None:
# aggregated_cam = cam_resized_np
# else:
# aggregated_cam += cam_resized_np
# # Save a single example if requested and not already saved
# if save_single_example and not single_example_saved:
# with torch.no_grad():
# spectrogram_output = best_model.mel_extractor.spectrogram_extractor(sample_input)
# logmel_output = best_model.mel_extractor.logmel_extractor(spectrogram_output)
# logmel_output_np = logmel_output.squeeze(0).squeeze(0).cpu().numpy() # Convert log-mel spectrogram to NumPy array
# plt.figure(figsize=(15, 5))
# # Subplot 1: Original Log-Mel Spectrogram
# plt.subplot(1, 2, 1)
# plt.title(f"Log-Mel Spectrogram ({class_name}, Single Example)")
# plt.imshow(logmel_output_np, aspect='auto', origin='lower', cmap='viridis')
# plt.colorbar()
# # Subplot 2: Grad-CAM Heatmap Overlayed on Spectrogram
# plt.subplot(1, 2, 2)
# plt.title(f"Grad-CAM Heatmap ({class_name}, Single Example)")
# plt.imshow(logmel_output_np, aspect='auto', origin='lower', cmap='viridis') # Background spectrogram
# plt.imshow(cam_resized_np, aspect='auto', origin='lower', cmap='jet', alpha=0.5) # Overlay CAM with transparency
# plt.colorbar()
# output_path = f"cam/figures_timm/gradcam_{class_name}_{description}_single.png"
# plt.savefig(output_path, dpi=300)
# plt.close()
# single_example_saved = True # Mark that the single example has been saved
# if len(samples) > 0:
# aggregated_cam /= len(samples)
# aggregated_cam = (aggregated_cam - aggregated_cam.min()) / (aggregated_cam.max() + 1e-8)
# # Save aggregated CAM visualization
# plt.figure(figsize=(8, 6))
# plt.title(f"Aggregated Grad-CAM Heatmap ({class_name}, {description})")
# plt.imshow(aggregated_cam, aspect='auto', origin='lower', cmap='jet', alpha=0.5, vmin=0, vmax=1)
# plt.colorbar()
# plt.tight_layout()
# plt.savefig(f"cam/figures_timm/gradcam_{class_name}_{description}_aggregated.png", dpi=300)
# plt.close()
# # Process Grad-CAM for correctly classified samples
# process_gradcam(correct_samples_per_class, "correctly classified")
# # Process Grad-CAM for misclassified samples
# process_gradcam(misclassified_samples_per_class, "misclassified")
### CAM ###
import torch
import os
from contextlib import contextmanager
@contextmanager
def register_hooks(layer, forward_hook, backward_hook):
forward_handle = layer.register_forward_hook(forward_hook)
backward_handle = layer.register_full_backward_hook(backward_hook)
try:
yield
finally:
forward_handle.remove()
backward_handle.remove()
def generate_gradcam(model, input_tensor, target_class, last_conv_layer):
gradients = []
activations = []
def backward_hook(module, grad_input, grad_output):
gradients.append(grad_output[0])
def forward_hook(module, input, output):
activations.append(output)
with register_hooks(last_conv_layer, forward_hook, backward_hook):
# Forward pass
model.eval()
logits = model(input_tensor)[1] # Get logits from fully connected layer
# Backward pass for target class
model.zero_grad()
target_score = logits[0][target_class]
target_score.backward()
# Get gradients and activations
gradients = gradients[0]
activations = activations[0]
# Compute weights using Global Average Pooling (GAP)
weights = torch.mean(gradients, dim=(2, 3))
# Compute Grad-CAM
cam = torch.zeros(activations.shape[2:], device=input_tensor.device)
for i in range(weights.shape[1]):
cam += weights[0, i] * activations[0, i]
cam = F.relu(cam) # Apply ReLU
cam = (cam - cam.min()) / (cam.max() + 1e-8) # Normalize
return cam.cpu().detach().numpy()
# Dictionaries to store correctly and misclassified samples per class
correct_samples_per_class = {class_name: [] for class_name in class_to_idx.keys()}
misclassified_samples_per_class = {class_name: [] for class_name in class_to_idx.keys()}
# Populate dictionaries with correctly and misclassified samples
for batch in test_loader:
inputs, labels = batch
inputs, labels = inputs.to(device), labels.to(device)
# Pass raw waveform directly to the model
outputs = best_model(inputs) # The model handles spectrogram/log-mel extraction internally
_, preds = torch.max(outputs[1], dim=1) # Get predictions
for i in range(len(labels)):
true_class_name = list(class_to_idx.keys())[list(class_to_idx.values()).index(labels[i].item())]
if preds[i] == labels[i]: # Correctly classified
correct_samples_per_class[true_class_name].append((inputs[i], labels[i]))
else: # Misclassified
predicted_class_name = list(class_to_idx.keys())[list(class_to_idx.values()).index(preds[i].item())]
misclassified_samples_per_class[true_class_name].append((inputs[i], labels[i], predicted_class_name))
# Adjust last convolutional layer for ConvNeXt-based model
last_conv_layer = best_model.model_ft.backbone.stages[-1].blocks[-1].conv_dw # Last depthwise conv layer
# Save directory
save_directory = "cam/figures_timm"
os.makedirs(save_directory, exist_ok=True)
# Function to process Grad-CAM for a set of samples (correct or misclassified)
def process_gradcam(samples_dict, description, save_single_example=True):
for class_name, samples in samples_dict.items():
print(f"Processing Grad-CAM for {len(samples)} {description} samples in class: {class_name}")
aggregated_cam = None
single_example_saved = False # Track if a single example has been saved
for idx, sample_data in enumerate(samples):
sample_input = sample_data[0].unsqueeze(0).to(device) # Add batch dimension
target_class = sample_data[1].item() # Get target class index
# Pass raw waveform directly to the model (no external spectrogram extraction)
outputs = best_model(sample_input) # The model handles spectrogram/log-mel extraction internally
# Generate Grad-CAM heatmap using the last convolutional layer
cam = generate_gradcam(best_model, sample_input, target_class, last_conv_layer)
# Resize CAM to match input dimensions (e.g., spectrogram size)
cam_resized = F.interpolate(torch.tensor(cam).unsqueeze(0).unsqueeze(0), size=(501, 64), mode='bilinear', align_corners=False)
cam_resized_np = cam_resized.squeeze().numpy()
# Normalize the individual CAM before aggregation
cam_resized_np = (cam_resized_np - cam_resized_np.min()) / (cam_resized_np.max() + 1e-8)
# Aggregate CAMs (e.g., sum)
if aggregated_cam is None:
aggregated_cam = cam_resized_np
else:
aggregated_cam += cam_resized_np
# Save a single example if requested and not already saved
if save_single_example and not single_example_saved:
with torch.no_grad():
# Assuming the model has a method to extract log-mel spectrogram
spectrogram_output = best_model.mel_extractor.spectrogram_extractor(sample_input)
logmel_output = best_model.mel_extractor.logmel_extractor(spectrogram_output)
logmel_output_np = logmel_output.squeeze(0).squeeze(0).cpu().numpy() # Convert to NumPy array
plt.figure(figsize=(15, 15))
# Subplot 1: Original Log-Mel Spectrogram
plt.subplot(1, 2, 1)
plt.imshow(logmel_output_np, aspect='auto', origin='lower', cmap='viridis')
plt.title(f"Log-Mel Spectrogram ({class_name}, Single Example)", fontsize=16)
plt.xlabel('Time (s)', fontsize=14)
plt.ylabel('Frequency (Hz)', fontsize=14)
# Subplot 2: Grad-CAM Heatmap Overlayed on Spectrogram
plt.subplot(1, 2, 2)
plt.imshow(logmel_output_np, aspect='auto', origin='lower', cmap='viridis') # Background spectrogram
plt.imshow(cam_resized_np, aspect='auto', origin='lower', cmap='jet', alpha=0.5) # Overlay CAM with transparency
plt.title(f"Grad-CAM Heatmap ({class_name}, Single Example)")
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')
# Save the single example figure with annotations
output_path_single = os.path.join(save_directory, f"gradcam_{class_name}_{description}_single.png")
plt.tight_layout()
plt.savefig(output_path_single, dpi=300, bbox_inches='tight', pad_inches=0)
plt.close()
single_example_saved = True # Mark that the single example has been saved
if len(samples) > 0:
aggregated_cam /= len(samples)
aggregated_cam = (aggregated_cam - aggregated_cam.min()) / (aggregated_cam.max() + 1e-8)
# Save aggregated CAM with labels, titles, and colorbars
plt.figure(figsize=(8, 6)) # Adjust as needed
plt.title(f"Aggregated Grad-CAM Heatmap ({class_name}, {description})")
plt.imshow(aggregated_cam, aspect='auto', origin='lower', cmap='jet', alpha=0.5, vmin=0, vmax=1)
plt.colorbar()
plt.tight_layout()
output_path_aggregated = os.path.join(save_directory, f"gradcam_{class_name}_{description}_aggregated.png")
plt.savefig(output_path_aggregated, dpi=300)
plt.close()
# Save aggregated CAM without labels, titles, axes, or colorbars
plt.figure(figsize=(3, 6), dpi=600) # Longer on y-axis, high resolution
plt.imshow(aggregated_cam, aspect='auto', origin='lower', cmap='jet', alpha=0.5, vmin=0, vmax=1)
plt.axis('off') # Remove axes
plt.tight_layout(pad=0)
output_path_aggregated_no_labels = os.path.join(save_directory, f"gradcam_{class_name}_{description}_aggregated_no_labels.png")
plt.savefig(output_path_aggregated_no_labels, dpi=600, bbox_inches='tight', pad_inches=0)
plt.close()
# Function to save a single colorbar
def save_colorbar(save_path, cmap_name='jet', orientation='vertical'):
fig, ax = plt.subplots(figsize=(1, 6)) # Adjust width and height as needed
norm = plt.Normalize(vmin=0, vmax=1)
cmap = plt.get_cmap(cmap_name)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
# Create colorbar without any labels or ticks
cbar = plt.colorbar(sm, cax=ax, orientation=orientation, ticks=[])
cbar.outline.set_visible(False) # Remove the outline
ax.axis('off') # Remove axis
plt.tight_layout()
plt.savefig(save_path, dpi=300, transparent=True, bbox_inches='tight', pad_inches=0)
plt.close()
# Example usage: Process Grad-CAM for correctly classified and misclassified samples
process_gradcam(correct_samples_per_class, "correctly classified")
process_gradcam(misclassified_samples_per_class, "misclassified")
# Save the colorbar once after processing all classes
colorbar_path = os.path.join(save_directory, "colorbar.png")
save_colorbar(colorbar_path)