jacobgil / pytorch-grad-cam

Advanced AI Explainability for computer vision. Support for CNNs, Vision Transformers, Classification, Object detection, Segmentation, Image similarity and more.
https://jacobgil.github.io/pytorch-gradcam-book
MIT License
10.39k stars 1.55k forks source link

no attribute 'activations_and_grads' #375

Closed RMobina closed 1 year ago

RMobina commented 1 year ago

I want to use pretrained ResNet and simply apply grad-cam.But get the following error.

`model1 = resnet50(pretrained=True)

torch.save(model1, 'ResNet.h5')

model1 = torch.load('ResNet.h5')

target_layers = model1.layer4[-1]

img_path = "./eagle.jpg" test_image = Image.open(img_path).convert('RGB') imgplot = plt.imshow(test_image) plt.show()

toTensor = transforms.Compose([ transforms.Resize((100,100)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) input_tensor = toTensor(test_image)

test_image = np.array(test_image) test_image = cv2.resize(test_image,(100,100)) test_image = test_image.astype('float32') test_image /= 255.0

imgplot = plt.imshow(test_image) plt.show()

cam = GradCAM(model=model1, target_layers=target_layers, use_cuda=True) grayscale_cam = cam(input_tensor=input_tensor.unsqueeze(0), targets=None) grayscale_cam = grayscale_cam[0, :] visualization = show_cam_on_image(test_image, grayscale_cam) imgplot = plt.imshow(visualization) plt.show()`

:219: RuntimeWarning: scipy._lib.messagestream.MessageStream size changed, may indicate binary incompatibility. Expected 56 from C header, got 64 from PyObject Traceback (most recent call last): File "/home/ECAPA-TDNN/visualization.py", line 51, in cam = GradCAM(model=model1, target_layers=target_layers, use_cuda=True) File "/home/Voice/venv/lib/python3.8/site-packages/pytorch_grad_cam/grad_cam.py", line 8, in init super( File "/home/Voice/venv/lib/python3.8/site-packages/pytorch_grad_cam/base_cam.py", line 27, in init self.activations_and_grads = ActivationsAndGradients( File "/home/Voice-Privacy-Challenge-2022/venv/lib/python3.8/site-packages/pytorch_grad_cam/activations_and_gradients.py", line 11, in init for target_layer in target_layers: TypeError: 'Bottleneck' object is not iterable Exception ignored in: <function BaseCAM.del at 0x7fa2c2d704c0> Traceback (most recent call last): File "/home/Voice-Privacy-Challenge-2022/venv/lib/python3.8/site-packages/pytorch_grad_cam/base_cam.py", line 192, in del self.activations_and_grads.release() AttributeError: 'GradCAM' object has no attribute 'activations_and_grads'

RMobina commented 1 year ago

it fixed by using target_layers = [model1.layer4[-1]] insead of target_layers = model1.layer4[-1]

jacobgil commented 1 year ago

Yes, exactly. The target_layers expects a list. Will probably make it return an exception in the newest version.