This project shows how to use Grad-CAM (Gradient-weighted Class Activation Mapping) to visualise where a CNN looks when it makes a prediction. The demo trains a small CNN on the TensorFlow Flowers dataset (5 flower classes) and overlays Grad-CAM heatmaps on top of the input images.
Grad-CAM helps explain why the model classified an image the way it did — a key tool in Explainable AI (XAI).
🎓 Originally built for the CS42 Explainable AI unit. Designed to give a hands-on intuition for what convolutional layers actually attend to.
- Loads and preprocesses the TF-Flowers dataset (5 classes: daisy, dandelion, roses, sunflowers, tulips)
- Builds a CNN for image classification
- Computes Grad-CAM heatmaps for any prediction
- Visualises original image + heatmap overlay side-by-side
- Self-contained Jupyter / Colab notebook
| Property | Details |
|---|---|
| Source | tensorflow_datasets → tf_flowers |
| Classes | daisy, dandelion, roses, sunflowers, tulips |
| Samples | ~3,670 |
| Task | Multi-class image classification |
Install the dependencies:
pip install -r requirements.txtPinned versions:
tensorflow>=2.12tensorflow-datasetsnumpymatplotlibscikit-learn
jupyter notebook Gradcam_tf_Flowers.ipynb- Open Colab → File → Upload notebook
- Pick
Gradcam_tf_Flowers.ipynb - Run all cells (GPU recommended: Runtime → Change runtime type → GPU)
Grad-CAM-Visualization-Demo-TF-Flowers-CNN-/
├── Gradcam_tf_Flowers.ipynb # Main notebook (training + Grad-CAM)
├── Output.png # Saved Grad-CAM example
├── Sample images.png # Dataset preview
├── requirements.txt # Python dependencies
├── LICENSE
└── README.md
- Pick a target class (e.g., the predicted class).
- Compute the gradient of the target class score with respect to the activations of the last convolutional layer.
- Average those gradients spatially → these are the importance weights for each feature map.
- Multiply each feature map by its weight, sum them all → you get a 2-D heatmap.
- Upsample the heatmap to the input image size and overlay it.
The brighter the region, the more it influenced the prediction.
- Understand what a CNN's last convolutional layer "looks at"
- Compute gradients with
tf.GradientTape - Implement and apply Grad-CAM end-to-end
- Critically evaluate model decisions (XAI mindset)
- Original Grad-CAM paper — Selvaraju et al., 2016: "Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization"
- Keras Grad-CAM tutorial: https://keras.io/examples/vision/grad_cam/
MIT — Credits to CS42.org.

