I've created a little PyTorch script to display the activation maps of a specific, or all the CNN's layers. Since I'm learning PyTorch, I thought it would be interesting to do this little project to get used to handling torch objects and tensors.
To get a local copy up and running, follow these simple example steps.
- Python ⩾ 3.8
sudo apt install python3 python3-pip
- Clone the repo
git clone https://github.com/Clement-W/Activation-Maps-Visualiser-PT.git cd Activation-Maps-Visualiser-PT/
- Create and activate a virtual environment
pip3 install virtualenv --upgrade virtualenv venv source venv/bin/activate
- Install the requirements
pip3 install -r requirements.txt
There is two main ways to use this python script :
- Call the function show_activation_maps(model, layer_name, image). This function shows the activation maps for a specific layer in the model.
- Call the function save_all_activation_maps(model, image,path_to_directory). This function saves the activation maps of every layers of the model in the specified directory.
Check the next section to see an example.
Import modules :
from torchvision import models, transforms, datasets
import torch
from PIL import Image
from ActivationMapsExtractor import save_all_activation_maps, show_activation_maps
Set torch device :
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
Load pretrained RestNet-18 model from PyTorch :
model = models.resnet18(pretrained=True)
Load an image to feed the ResNet-18 model :
image = Image.open("imageNet/sample.JPEG")
transform = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor()])
image = transform(image).to(device)
If you want to see the activation maps of a specific layer by it's name for that input image :
show_activation_maps(model,"conv1",image)
If you want to save the activation maps of every layers for that input image :
save_all_activation_maps(model, image,"./ResNet-activation-maps")
I'm still learning PyTorch, so feel free to use Issues or PR to report errors and/or propose additions or corrections to my code. Any contributions you make are greatly appreciated.
Distributed under the MIT License. See LICENSE
for more information.
- Add a Jupyter notebook demo