Skip to main content

Automatic Grad-CAM heatmap generator for TensorFlow/Keras and PyTorch models

Project description

GradHeatmap GradHeatmap is a Python library designed to simplify the generation of Grad-CAM (Gradient-weighted Class Activation Mapping) heatmaps. It automates the process of backbone detection and layer identification for both TensorFlow/Keras and PyTorch models, removing the need for manual architecture inspection or hardcoded layer names.

Features Framework Agnostic: Unified support for TensorFlow/Keras (.keras, .h5) and PyTorch models.

Automatic Detection: Automatically identifies backbones (ResNet, VGG, MobileNet, EfficientNet, etc.) and the final convolutional layer.

Classification Support: Works with binary (sigmoid/single logit) and multi-class (softmax/multi-logit) outputs.

Smart Preprocessing: Detects internal tf.keras.layers.Rescaling in TensorFlow and provides ImageNet normalization for PyTorch.

Transfer Learning Ready: Seamlessly handles custom CNNs and models built via transfer learning.

Visualization: OpenCV JET heatmap overlay with adjustable alpha blending.

Validation: Built-in safe output validation and fallback normalization.

Installation Install the package directly from GitHub:

pip install git+https://github.com/AhmedAbdAlKareem1/gradheatmap.git

Optional Extras To install dependencies for specific frameworks:

For TensorFlow

pip install "gradheatmap[tf]"

For PyTorch

pip install "gradheatmap[torch]"

#Quick Start (TensorFlow / Keras)

from gradheatmap import HeatMap

model_path = "your_model.keras"   # Supports .keras or .h5
image_path = "your_image.jpg"
class_names = ["class0", "class1"]

heat = HeatMap(
    model=model_path,
    img_path=image_path,
    class_names=class_names
)

overlay = heat.overlay_heatmap(alpha=0.4)
heat.save_heat_img("result.jpg", overlay)

Project Structure Output:

Plaintext heatmap/ └── result.jpg

#Quick Start (PyTorch)

import torch
import torch.nn as nn
from torchvision import models
from gradheatmap import HeatMapPyTorch

Rebuild architecture

def build_resnet50(num_classes=2):
    model = models.resnet50(weights=None)
    model.fc = nn.Linear(model.fc.in_features, num_classes)
    return model

Load checkpoint

ckpt = torch.load("resnet50_catdog_best.pth", map_location="cpu")

model = build_resnet50(num_classes=2)
model.load_state_dict(ckpt["model_state_dict"])
model.eval()

Generate Grad-CAM

heat = HeatMapPyTorch(
    model=model,
    img_path="image.jpg",
    class_names=ckpt.get("class_names", ["Cat", "Dog"]),
    preprocess="resnet50",        # enables ImageNet normalization
    image_size=(224, 224)
)

overlay = heat.overlay_heatmap(alpha=0.4)
heat.save_heat_img("result_torch.jpg", overlay)

#Terminal Output Example When running the generator, the library provides automated feedback on the model architecture:

Plaintext

Detected Model : vgg16
Detected Image Size = (224, 224)
Detected Backbone = vgg16
Last Convo Layer : block5_conv3
Class: 0 class0  Confidence: 100.00%
Successfully saved heatmap to: heatmap/result.jpg

Requirements Python >= 3.8

OpenCV

NumPy

TensorFlow >= 2.x (Optional)

PyTorch >= 1.x (Optional)

License This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gradheatmap-0.2.0.tar.gz (13.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gradheatmap-0.2.0-py3-none-any.whl (13.8 kB view details)

Uploaded Python 3

File details

Details for the file gradheatmap-0.2.0.tar.gz.

File metadata

  • Download URL: gradheatmap-0.2.0.tar.gz
  • Upload date:
  • Size: 13.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for gradheatmap-0.2.0.tar.gz
Algorithm Hash digest
SHA256 33081c31b2bd3483968ca0ed8110f26cc0084691b12eb588fdf76c0ee077a895
MD5 63dee987cf0990d87baf86bd8ffb24d7
BLAKE2b-256 551bf660c50c9f1821a539740fa89f4a6be59f5782cb8bd08030e15e27d1b390

See more details on using hashes here.

File details

Details for the file gradheatmap-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: gradheatmap-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 13.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for gradheatmap-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f8481cf056d2eac4e10d5de196055469c3ac057ad440c17f57dc7acc17b73d1f
MD5 79483fb5cdbe7b5921d90aebc77c4db4
BLAKE2b-256 42a6aeda4312caef1fcfdda10af3382b264097fd3ce0891db02e61b5f99d8216

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page