class_docstr: Provides an interface to perform backpropagation.
  
  This class provids a way to calculate the gradients of a target class
  output w.r.t. an input image, by performing a single backprobagation.
  
  The gradients obtained can be used to visualise an image-specific class
  saliency map, which can gives some intuition on regions within the input
  image that contribute the most (and least) to the corresponding output.
  
  More details on saliency maps: `Deep Inside Convolutional Networks:
  Visualising Image Classification Models and Saliency Maps
  <https://arxiv.org/pdf/1312.6034.pdf>`_.
  
  Args:
      model: A neural network model from `torchvision.models
          <https://pytorch.org/docs/stable/torchvision/models.html>`_.
class_docstr_tok: ["Provides","an","interface","to","perform","backpropagation",".","This","class","provids","a","way","to","calculate","the","gradients","of","a","target","class","output","w.r.t",".","an","input","image",",","by","performing","a","single","backprobagation",".","The","gradients","obtained","can","be","used","to","visualise","an","image-specific","class","saliency","map",",","which","can","gives","some","intuition","on","regions","within","the","input","image","that","contribute","the","most","(","and","least",")","to","the","corresponding","output",".","More","details","on","saliency","maps",":","`","Deep","Inside","Convolutional","Networks",":","Visualising","Image","Classification","Models","and","Saliency","Maps","<","https",":","\/\/arxiv.org\/pdf\/1312.6034.pdf",">","`","_",".","Args",":","model",":","A","neural","network","model","from","`","torchvision.models","<","https",":","\/\/pytorch.org\/docs\/stable\/torchvision\/models.html",">","`","_","."]
docstr: Calculates gradients of the target_class output w.r.t. an input_.
  
  The gradients is calculated for each colour channel. Then, the maximum
  gradients across colour channels is returned.
  
  Args:
      input_ (torch.Tensor): With shape :math:`(N, C, H, W)`.
      target_class (int, optional, default=None)
      take_max (bool, optional, default=False): If True, take the maximum
          gradients across colour channels for each pixel.
      guided (bool, optional, default=Fakse): If True, perform guided
          backpropagation. See `Striving for Simplicity: The All
          Convolutional Net <https://arxiv.org/pdf/1412.6806.pdf>`_.
      use_gpu (bool, optional, default=False): Use GPU if set to True and
          `torch.cuda.is_available()`.
  
  Returns:
      gradients (torch.Tensor): With shape :math:`(C, H, W)`.
docstr_tok: ["Calculates","gradients","of","the","target_class","output","w.r.t",".","an","input_",".","The","gradients","is","calculated","for","each","colour","channel",".","Then",",","the","maximum","gradients","across","colour","channels","is","returned",".","Args",":","input_","(","torch.Tensor",")",":","With","shape",":","math",":","`","(","N",",","C",",","H",",","W",")","`",".","target_class","(","int",",","optional",",","default=None",")","take_max","(","bool",",","optional",",","default=False",")",":","If","True",",","take","the","maximum","gradients","across","colour","channels","for","each","pixel",".","guided","(","bool",",","optional",",","default=Fakse",")",":","If","True",",","perform","guided","backpropagation",".","See","`","Striving","for","Simplicity",":","The","All","Convolutional","Net","<","https",":","\/\/arxiv.org\/pdf\/1412.6806.pdf",">","`","_",".","use_gpu","(","bool",",","optional",",","default=False",")",":","Use","GPU","if","set","to","True","and","`","torch.cuda.is_available","(",")","`",".","Returns",":","gradients","(","torch.Tensor",")",":","With","shape",":","math",":","`","(","C",",","H",",","W",")","`","."]
code: def calculate_gradients(
      self,
      input_,
      target_class=None,
      take_max=False,
      guided=False,
      use_gpu=False,
  ):
      """Calculates gradients of the target_class output w.r.t. an input_.
  
      The gradients is calculated for each colour channel. Then, the maximum
      gradients across colour channels is returned.
  
      Args:
          input_ (torch.Tensor): With shape :math:`(N, C, H, W)`.
          target_class (int, optional, default=None)
          take_max (bool, optional, default=False): If True, take the maximum
              gradients across colour channels for each pixel.
          guided (bool, optional, default=Fakse): If True, perform guided
              backpropagation. See `Striving for Simplicity: The All
              Convolutional Net <https://arxiv.org/pdf/1412.6806.pdf>`_.
          use_gpu (bool, optional, default=False): Use GPU if set to True and
              `torch.cuda.is_available()`.
  
      Returns:
          gradients (torch.Tensor): With shape :math:`(C, H, W)`.
  
      """  # noqa
  
      if "inception" in self.model.__class__.__name__.lower():
          if input_.size()[1:] != (3, 299, 299):
              raise ValueError(
                  "Image must be 299x299 for Inception models."
              )
  
      if guided:
          self.relu_outputs = []
          self._register_relu_hooks()
  
      if torch.cuda.is_available() and use_gpu:
          self.model = self.model.to("cuda")
          input_ = input_.to("cuda")
  
      self.model.zero_grad()
  
      self.gradients = torch.zeros(input_.shape)
  
      # Get a raw prediction value (logit) from the last linear layer
  
      output = self.model(input_)
  
      # Don't set the gradient target if the model is a binary classifier
      # i.e. has one class prediction
  
      if len(output.shape) == 1:
          target = None
      else:
          _, top_class = output.topk(1, dim=1)
  
          # Create a 2D tensor with shape (1, num_classes) and
          # set all element to zero
  
          target = torch.FloatTensor(1, output.shape[-1]).zero_()
  
          if torch.cuda.is_available() and use_gpu:
              target = target.to("cuda")
  
          if (target_class is not None) and (top_class != target_class):
              warnings.warn(
                  UserWarning(
                      f"The predicted class index {top_class.item()} does not"
                      + f"equal the target class index {target_class}. "
                      + "Calculating the gradient w.r.t. the predicted class."
                  )
              )
  
          # Set the element at top class index to be 1
  
          target[0][top_class] = 1
  
      # Calculate gradients of the target class output w.r.t. input_
  
      output.backward(gradient=target)
  
      # Detach the gradients from the graph and move to cpu
  
      gradients = self.gradients.detach().cpu()[0]
  
      if take_max:
          # Take the maximum across colour channels
  
          gradients = gradients.max(dim=0, keepdim=True)[0]
  
      return gradients
  
file_path: flashtorch/flashtorch/saliency/backprop.py
imports: import warnings
  import matplotlib.pyplot
  import torch
  import torch.nn
  from flashtorch.utils import denormalize, format_for_plotting, standardize_and_clip
label_desc: Use image node_id 2 for calling the Backprop obj's underlying member method code with example usage: obj.calculate_gradients(input_, target_class, take_max, guided, use_gpu) and returns: gradients