{"id":27847,"library":"grad-cam","title":"Grad-CAM (PyTorch)","description":"Grad-CAM is a PyTorch library for generating Class Activation Maps (CAMs) for image classification, segmentation, object detection, and more. Current version 1.5.5 supports many CAM methods (GradCAM, GradCAM++, HiResCAM, etc.) and runs on Python >=3.8. Releases are periodic, maintained by the author.","status":"active","version":"1.5.5","language":"python","source_language":"en","source_url":"https://github.com/jacobgil/pytorch-grad-cam","tags":["grad-cam","pytorch","explainability","class activation map","computer vision"],"install":[{"cmd":"pip install grad-cam","lang":"bash","label":"Install via PyPI"}],"dependencies":[{"reason":"Core dependency for tensor operations and neural networks.","package":"torch","optional":false},{"reason":"Required for image transforms and pretrained models.","package":"torchvision","optional":false},{"reason":"Used for image processing and visualization.","package":"opencv-python","optional":false},{"reason":"Required for array operations.","package":"numpy","optional":false},{"reason":"Often used for plotting visualizations.","package":"matplotlib","optional":true},{"reason":"Image loading and manipulation.","package":"Pillow","optional":true}],"imports":[{"note":"The package name is 'grad-cam' but the import module is 'pytorch_grad_cam'.","wrong":"from grad_cam import GradCAM","symbol":"GradCAM","correct":"from pytorch_grad_cam import GradCAM"},{"note":"","wrong":null,"symbol":"GradCAMPlusPlus","correct":"from pytorch_grad_cam import GradCAMPlusPlus"},{"note":"","wrong":null,"symbol":"HiResCAM","correct":"from pytorch_grad_cam import HiResCAM"},{"note":"","wrong":null,"symbol":"ScoreCAM","correct":"from pytorch_grad_cam import ScoreCAM"},{"note":"","wrong":null,"symbol":"LayerCAM","correct":"from pytorch_grad_cam import LayerCAM"},{"note":"Utility functions are in 'pytorch_grad_cam.utils.image' submodule.","wrong":"from pytorch_grad_cam import show_cam_on_image","symbol":"utils","correct":"from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image"}],"quickstart":{"code":"import torch\nimport torchvision\nimport cv2\nimport numpy as np\nfrom pytorch_grad_cam import GradCAM\nfrom pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image\n\ndef get_cam(model, image_path, target_layer):\n    # Load and preprocess image\n    image = cv2.imread(image_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image_resized = cv2.resize(image, (224, 224))\n    image_normalized = image_resized.astype(np.float32) / 255.0\n    input_tensor = preprocess_image(image_resized, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n    \n    # Create CAM object\n    cam = GradCAM(model=model, target_layers=[target_layer])\n    \n    # Generate CAM mask\n    grayscale_cam = cam(input_tensor=input_tensor)[0, :]\n    visualization = show_cam_on_image(image_normalized, grayscale_cam, use_rgb=True)\n    return visualization\n\n# Example usage:\nmodel = torchvision.models.resnet50(pretrained=True).eval()\ntarget_layer = model.layer4[-1]\nvis = get_cam(model, 'path/to/image.jpg', target_layer)","lang":"python","description":"Demonstrates loading a pretrained ResNet50, creating a GradCAM object with the final convolutional layer, and generating a CAM visualization on an input image."},"warnings":[{"fix":"Always wrap target layers in a list: e.g., `target_layers=[model.layer4[-1]]`.","message":"In version 1.5.x, the `target_layers` argument must be a list of layer objects, not a single layer. Passing a single layer will raise an error.","severity":"breaking","affected_versions":">=1.5.0"},{"fix":"Use `device='cuda'` instead of `use_cuda=True`.","message":"The `use_cuda` parameter is deprecated in favor of `device` parameter. Using `use_cuda=True` may still work but raises a warning.","severity":"deprecated","affected_versions":">=1.4.0"},{"fix":"Use `from pytorch_grad_cam import ...`.","message":"Import path is `pytorch_grad_cam`, not `grad_cam` or `gradcam`. The PyPI package name is `grad-cam`.","severity":"gotcha","affected_versions":"all"},{"fix":"Ensure input tensor has shape (1, C, H, W). Use `input_tensor.unsqueeze(0)` if needed.","message":"The `input_tensor` parameter expects a tensor with batch dimension. If you pass a single image tensor without batch, you'll get unexpected shape errors.","severity":"gotcha","affected_versions":"all"},{"fix":"Always call `model.eval()` and use `torch.no_grad()` (outside CAM generation).","message":"For classification models, the default `model.eval()` must be called before CAM generation; otherwise batch norm/dropout layers produce wrong gradients.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-05-09T00:00:00.000Z","next_check":"2026-08-07T00:00:00.000Z","problems":[{"fix":"Replace `use_cuda=True` with `device='cuda'`.","cause":"Version 1.5.0 removed the `use_cuda` parameter and replaced it with `device`.","error":"TypeError: GradCAM.__init__() got an unexpected keyword argument 'use_cuda'"},{"fix":"Resize the input image to 224x224 before preprocessing, or adapt the model to the input size.","cause":"Input tensor spatial dimensions don't match the model's expected input size (e.g., ResNet expects 224x224).","error":"RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 224 but got size 224."},{"fix":"Use correct import: `from pytorch_grad_cam import GradCAM`.","cause":"Importing from the wrong module name; the package is installed as `grad-cam` but imports from `pytorch_grad_cam`.","error":"AttributeError: module 'pytorch_grad_cam' has no attribute 'GradCAM'"},{"fix":"Wrap the target layer in a list: `target_layers=[model.layer4[-1]]`.","cause":"Passing a single layer instead of a list in versions >=1.5.0.","error":"ValueError: target_layers must be a list of nn.Module layers."}],"ecosystem":"pypi","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}