Hi Mona,
I think this what you’re looking for:

  
      github.com
  
  
    jacobgil/pytorch-grad-cam/blob/master/grad-cam.py 324
import torch
from torch.autograd import Variable
from torch.autograd import Function
from torchvision import models
from torchvision import utils
import cv2
import sys
import numpy as np
import argparse

class FeatureExtractor():
    """ Class for extracting activations and 
    registering gradients from targetted intermediate layers """
    def __init__(self, model, target_layers):
        self.model = model
        self.target_layers = target_layers
        self.gradients = []

    def save_gradient(self, grad):
    	self.gradients.append(grad)


  This file has been truncated. show original

  
  
    
    
  
  


The code is very clear, so you shouldn’t have troubles to adapt it to your situation. If you do, let me know.
If you’re interested in other visualizations, you should also look at this Github:

  
      
      GitHub
  
  
    

utkuozbulak/pytorch-cnn-visualizations 238

Pytorch implementation of convolutional neural network visualization techniques - utkuozbulak/pytorch-cnn-visualizations