-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathgrad_cam.py
32 lines (26 loc) · 913 Bytes
/
grad_cam.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
import numpy as np
from pytorch_grad_cam.base_cam import BaseCAM
class GradCAM(BaseCAM):
def __init__(self, model, target_layers,
reshape_transform=None):
super(
GradCAM,
self).__init__(
model,
target_layers,
reshape_transform)
def get_cam_weights(self,
input_tensor,
target_layer,
target_category,
activations,
grads):
# 2D image
if len(grads.shape) == 4:
return np.mean(grads, axis=(2, 3))
# 3D image
elif len(grads.shape) == 5:
return np.mean(grads, axis=(2, 3, 4))
else:
raise ValueError("Invalid grads shape."
"Shape of grads should be 4 (2D image) or 5 (3D image).")