Install & Compatibility
Where this runs
No compatibility data collected yet for this library.
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
GradCAM
✓ from pytorch_grad_cam import GradCAM
✗ from grad_cam import GradCAM
The package name is 'grad-cam' but the import module is 'pytorch_grad_cam'.
GradCAMPlusPlus
✓ from pytorch_grad_cam import GradCAMPlusPlus
HiResCAM
✓ from pytorch_grad_cam import HiResCAM
ScoreCAM
✓ from pytorch_grad_cam import ScoreCAM
LayerCAM
✓ from pytorch_grad_cam import LayerCAM
utils
✓ from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image
✗ from pytorch_grad_cam import show_cam_on_image
Utility functions are in 'pytorch_grad_cam.utils.image' submodule.
Demonstrates loading a pretrained ResNet50, creating a GradCAM object with the final convolutional layer, and generating a CAM visualization on an input image.
import torch
import torchvision
import cv2
import numpy as np
from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image, preprocess_image
def get_cam(model, image_path, target_layer):
# Load and preprocess image
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_resized = cv2.resize(image, (224, 224))
image_normalized = image_resized.astype(np.float32) / 255.0
input_tensor = preprocess_image(image_resized, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# Create CAM object
cam = GradCAM(model=model, target_layers=[target_layer])
# Generate CAM mask
grayscale_cam = cam(input_tensor=input_tensor)[0, :]
visualization = show_cam_on_image(image_normalized, grayscale_cam, use_rgb=True)
return visualization
# Example usage:
model = torchvision.models.resnet50(pretrained=True).eval()
target_layer = model.layer4[-1]
vis = get_cam(model, 'path/to/image.jpg', target_layer)
Errors
Common errors & fixes
TypeError: GradCAM.__init__() got an unexpected keyword argument 'use_cuda'
Version 1.5.0 removed the `use_cuda` parameter and replaced it with `device`.
fixReplace `use_cuda=True` with `device='cuda'`.
RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 224 but got size 224.
Input tensor spatial dimensions don't match the model's expected input size (e.g., ResNet expects 224x224).
fixResize the input image to 224x224 before preprocessing, or adapt the model to the input size.
AttributeError: module 'pytorch_grad_cam' has no attribute 'GradCAM'
Importing from the wrong module name; the package is installed as `grad-cam` but imports from `pytorch_grad_cam`.
fixUse correct import: `from pytorch_grad_cam import GradCAM`.
ValueError: target_layers must be a list of nn.Module layers.
Passing a single layer instead of a list in versions >=1.5.0.
fixWrap the target layer in a list: `target_layers=[model.layer4[-1]]`.
Upgrade
Version history
1.5.5latest on PyPI · released Apr 7, 2025
Audit
Dependencies
torchrequiredCore dependency for tensor operations and neural networks.
torchvisionrequiredRequired for image transforms and pretrained models.
opencv-pythonrequiredUsed for image processing and visualization.
numpyrequiredRequired for array operations.
matplotliboptionalOften used for plotting visualizations.
PillowoptionalImage loading and manipulation.