class_docstr: This class computes the occlusion sensitivity for a model's prediction of a given image. By occlusion sensitivity,
  we mean how the probability of a given prediction changes as the occluded section of an image changes. This can be
  useful to understand why a network is making certain decisions.
  
  As important parts of the image are occluded, the probability of classifying the image correctly will decrease.
  Hence, more negative values imply the corresponding occluded volume was more important in the decision process.
  
  Two ``torch.Tensor`` will be returned by the ``__call__`` method: an occlusion map and an image of the most probable
  class. Both images will be cropped if a bounding box used, but voxel sizes will always match the input.
  
  The occlusion map shows the inference probabilities when the corresponding part of the image is occluded. Hence,
  more -ve values imply that region was important in the decision process. The map will have shape ``BCHW(D)N``,
  where ``N`` is the number of classes to be inferred by the network. Hence, the occlusion for class ``i`` can
  be seen with ``map[...,i]``.
  
  The most probable class is an image of the probable class when the corresponding part of the image is occluded
  (equivalent to ``occ_map.argmax(dim=-1)``).
  
  See: R. R. Selvaraju et al. Grad-CAM: Visual Explanations from Deep Networks via
  Gradient-based Localization. https://doi.org/10.1109/ICCV.2017.74.
  
  Examples:
  
  .. code-block:: python
  
      # densenet 2d
      from monai.networks.nets import DenseNet121
      from monai.visualize import OcclusionSensitivity
      import torch
  
      model_2d = DenseNet121(spatial_dims=2, in_channels=1, out_channels=3)
      occ_sens = OcclusionSensitivity(nn_module=model_2d)
      occ_map, most_probable_class = occ_sens(x=torch.rand((1, 1, 48, 64)), b_box=[2, 40, 1, 62])
  
      # densenet 3d
      from monai.networks.nets import DenseNet
      from monai.visualize import OcclusionSensitivity
  
      model_3d = DenseNet(spatial_dims=3, in_channels=1, out_channels=3, init_features=2, growth_rate=2, block_config=(6,))
      occ_sens = OcclusionSensitivity(nn_module=model_3d, n_batch=10)
      occ_map, most_probable_class = occ_sens(torch.rand(1, 1, 6, 6, 6), b_box=[1, 3, -1, -1, -1, -1])
  
  See Also:
  
      - :py:class:`monai.visualize.occlusion_sensitivity.OcclusionSensitivity.`
class_docstr_tok: ["This","class","computes","the","occlusion","sensitivity","for","a","model","'s","prediction","of","a","given","image",".","By","occlusion","sensitivity",",","we","mean","how","the","probability","of","a","given","prediction","changes","as","the","occluded","section","of","an","image","changes",".","This","can","be","useful","to","understand","why","a","network","is","making","certain","decisions",".","As","important","parts","of","the","image","are","occluded",",","the","probability","of","classifying","the","image","correctly","will","decrease",".","Hence",",","more","negative","values","imply","the","corresponding","occluded","volume","was","more","important","in","the","decision","process",".","Two","``","torch.Tensor","``","will","be","returned","by","the","``","__call__","``","method",":","an","occlusion","map","and","an","image","of","the","most","probable","class",".","Both","images","will","be","cropped","if","a","bounding","box","used",",","but","voxel","sizes","will","always","match","the","input",".","The","occlusion","map","shows","the","inference","probabilities","when","the","corresponding","part","of","the","image","is","occluded",".","Hence",",","more","-ve","values","imply","that","region","was","important","in","the","decision","process",".","The","map","will","have","shape","``","BCHW","(","D",")","N","``",",","where","``","N","``","is","the","number","of","classes","to","be","inferred","by","the","network",".","Hence",",","the","occlusion","for","class","``","i","``","can","be","seen","with","``","map","[","...",",","i","]","``",".","The","most","probable","class","is","an","image","of","the","probable","class","when","the","corresponding","part","of","the","image","is","occluded","(","equivalent","to","``","occ_map.argmax","(","dim=-1",")","``",")",".","See",":","R.","R.","Selvaraju","et","al",".","Grad-CAM",":","Visual","Explanations","from","Deep","Networks","via","Gradient-based","Localization",".","https",":","\/\/doi.org\/10.1109\/ICCV.2017.74",".","Examples",":","..","code-block",":",":","python","#","densenet","2d","from","monai.networks.nets","import","DenseNet121","from","monai.visualize","import","OcclusionSensitivity","import","torch","model_2d","=","DenseNet121","(","spatial_dims=2",",","in_channels=1",",","out_channels=3",")","occ_sens","=","OcclusionSensitivity","(","nn_module=model_2d",")","occ_map",",","most_probable_class","=","occ_sens","(","x=torch.rand","(","(","1",",","1",",","48",",","64",")",")",",","b_box=","[","2",",","40",",","1",",","62","]",")","#","densenet","3d","from","monai.networks.nets","import","DenseNet","from","monai.visualize","import","OcclusionSensitivity","model_3d","=","DenseNet","(","spatial_dims=3",",","in_channels=1",",","out_channels=3",",","init_features=2",",","growth_rate=2",",","block_config=","(","6",",",")",")","occ_sens","=","OcclusionSensitivity","(","nn_module=model_3d",",","n_batch=10",")","occ_map",",","most_probable_class","=","occ_sens","(","torch.rand","(","1",",","1",",","6",",","6",",","6",")",",","b_box=","[","1",",","3",",","-1",",","-1",",","-1",",","-1","]",")","See","Also",":","-",":","py",":","class",":","`","monai.visualize.occlusion_sensitivity.OcclusionSensitivity.","`"]
docstr: Predictor function to be passed to the sliding window inferer. Takes a cropped meshgrid,
  referring to the coordinates in the input image. We use the index of the top-left corner
  in combination ``mask_size`` to figure out which region of the image is to be occluded. The
  occlusion is performed on the original image, ``x``, using ``cropped_region * mul + add``. ``mul``
  and ``add`` are sometimes pre-computed (e.g., a constant Gaussian blur), or they are
  sometimes calculated on the fly (e.g., the mean of the occluded patch). For this reason
  ``occ_mode`` is given. Lastly, ``activate`` is used to activate after each call of the model.
  
  Args:
      cropped_grid: subsection of the meshgrid, where each voxel refers to the coordinate of
          the input image. The meshgrid is created by the ``OcclusionSensitivity`` class, and
          the generation of the subset is determined by ``sliding_window_inference``.
      nn_module: module to call on data.
      x: the image that was originally passed into ``OcclusionSensitivity.__call__``.
      mul: occluded region will be multiplied by this. Can be ``torch.Tensor`` or ``float``.
      add: after multiplication, this is added to the occluded region. Can be ``torch.Tensor`` or ``float``.
      mask_size: Size of box to be occluded, centred on the central voxel. Should be
          a sequence, one value for each spatial dimension.
      occ_mode: might be used to calculate ``mul`` and ``add`` on the fly.
      activate: if ``True``, do softmax activation if num_channels > 1 else do ``sigmoid``. If ``False``, don't do any
          activation. If ``callable``, use callable on inferred outputs.
      module_kwargs: kwargs to be passed onto module when inferring
docstr_tok: ["Predictor","function","to","be","passed","to","the","sliding","window","inferer",".","Takes","a","cropped","meshgrid",",","referring","to","the","coordinates","in","the","input","image",".","We","use","the","index","of","the","top-left","corner","in","combination","``","mask_size","``","to","figure","out","which","region","of","the","image","is","to","be","occluded",".","The","occlusion","is","performed","on","the","original","image",",","``","x","``",",","using","``","cropped_region","*","mul","+","add","``",".","``","mul","``","and","``","add","``","are","sometimes","pre-computed","(","e.g.",",","a","constant","Gaussian","blur",")",",","or","they","are","sometimes","calculated","on","the","fly","(","e.g.",",","the","mean","of","the","occluded","patch",")",".","For","this","reason","``","occ_mode","``","is","given",".","Lastly",",","``","activate","``","is","used","to","activate","after","each","call","of","the","model",".","Args",":","cropped_grid",":","subsection","of","the","meshgrid",",","where","each","voxel","refers","to","the","coordinate","of","the","input","image",".","The","meshgrid","is","created","by","the","``","OcclusionSensitivity","``","class",",","and","the","generation","of","the","subset","is","determined","by","``","sliding_window_inference","``",".","nn_module",":","module","to","call","on","data",".","x",":","the","image","that","was","originally","passed","into","``","OcclusionSensitivity.__call__","``",".","mul",":","occluded","region","will","be","multiplied","by","this",".","Can","be","``","torch.Tensor","``","or","``","float","``",".","add",":","after","multiplication",",","this","is","added","to","the","occluded","region",".","Can","be","``","torch.Tensor","``","or","``","float","``",".","mask_size",":","Size","of","box","to","be","occluded",",","centred","on","the","central","voxel",".","Should","be","a","sequence",",","one","value","for","each","spatial","dimension",".","occ_mode",":","might","be","used","to","calculate","``","mul","``","and","``","add","``","on","the","fly",".","activate",":","if","``","True","``",",","do","softmax","activation","if","num_channels",">","1","else","do","``","sigmoid","``",".","If","``","False","``",",","do","n't","do","any","activation",".","If","``","callable","``",",","use","callable","on","inferred","outputs",".","module_kwargs",":","kwargs","to","be","passed","onto","module","when","inferring"]
code: def predictor(
      cropped_grid: torch.Tensor,
      nn_module: nn.Module,
      x: torch.Tensor,
      mul: torch.Tensor | float,
      add: torch.Tensor | float,
      mask_size: Sequence,
      occ_mode: str,
      activate: bool | Callable,
      module_kwargs: Mapping[str, Any],
  ) -> torch.Tensor:
      """
      Predictor function to be passed to the sliding window inferer. Takes a cropped meshgrid,
      referring to the coordinates in the input image. We use the index of the top-left corner
      in combination ``mask_size`` to figure out which region of the image is to be occluded. The
      occlusion is performed on the original image, ``x``, using ``cropped_region * mul + add``. ``mul``
      and ``add`` are sometimes pre-computed (e.g., a constant Gaussian blur), or they are
      sometimes calculated on the fly (e.g., the mean of the occluded patch). For this reason
      ``occ_mode`` is given. Lastly, ``activate`` is used to activate after each call of the model.
  
      Args:
          cropped_grid: subsection of the meshgrid, where each voxel refers to the coordinate of
              the input image. The meshgrid is created by the ``OcclusionSensitivity`` class, and
              the generation of the subset is determined by ``sliding_window_inference``.
          nn_module: module to call on data.
          x: the image that was originally passed into ``OcclusionSensitivity.__call__``.
          mul: occluded region will be multiplied by this. Can be ``torch.Tensor`` or ``float``.
          add: after multiplication, this is added to the occluded region. Can be ``torch.Tensor`` or ``float``.
          mask_size: Size of box to be occluded, centred on the central voxel. Should be
              a sequence, one value for each spatial dimension.
          occ_mode: might be used to calculate ``mul`` and ``add`` on the fly.
          activate: if ``True``, do softmax activation if num_channels > 1 else do ``sigmoid``. If ``False``, don't do any
              activation. If ``callable``, use callable on inferred outputs.
          module_kwargs: kwargs to be passed onto module when inferring
      """
      n_batch = cropped_grid.shape[0]
      sd = cropped_grid.ndim - 2
      # start with copies of x to infer
      im = torch.repeat_interleave(x, n_batch, 0)
      # get coordinates of top left corner of occluded region (possible because we use meshgrid)
      corner_coord_slices = [slice(None)] * 2 + [slice(1)] * sd
      top_corners = cropped_grid[corner_coord_slices]
  
      # replace occluded regions
      for b, t in enumerate(top_corners):
          # starting from corner, get the slices to extract the occluded region from the image
          slices = [slice(b, b + 1), slice(None)] + [
              slice(int(j), int(j) + m) for j, m in zip(t, mask_size)
          ]
          to_occlude = im[slices]
          if occ_mode == "mean_patch":
              add, mul = OcclusionSensitivity.constant_occlusion(
                  x, to_occlude.mean().item(), mask_size
              )
  
          if callable(occ_mode):
              to_occlude = occ_mode(x, to_occlude)
          else:
              to_occlude = to_occlude * mul + add
          if add is None or mul is None:
              raise RuntimeError(
                  "Shouldn't be here, something's gone wrong..."
              )
          im[slices] = to_occlude
      # infer
      out: torch.Tensor = nn_module(im, **module_kwargs)
  
      # if activation is callable, call it
      if callable(activate):
          out = activate(out)
      # else if True (should be boolean), sigmoid if n_chan == 1 else softmax
      elif activate:
          out = out.sigmoid() if x.shape[1] == 1 else out.softmax(1)
  
      # the output will have shape [B,C] where C is number of channels output by model (inference classes)
      # we need to return it to sliding window inference with shape [B,C,H,W,[D]], so add dims and repeat values
      for m in mask_size:
          out = torch.repeat_interleave(out.unsqueeze(-1), m, dim=-1)
  
      return out
  
file_path: MONAI/monai/visualize/occlusion_sensitivity.py
imports: from __future__ import annotations
  from collections.abc import Callable, Mapping, Sequence
  from typing import Any
  import numpy
  import torch
  import torch.nn
  from monai.data.meta_tensor import MetaTensor
  from monai.networks.utils import eval_mode
  from monai.transforms import Compose, GaussianSmooth, Lambda, ScaleIntensity, SpatialCrop
  from monai.utils import ensure_tuple_rep
label_desc: Use image node_id 4 for calling the OcclusionSensitivity obj's underlying member method code with example usage: obj.predictor(cropped_grid, nn_module, x, mul, add, mask_size, occ_mode, activate, module_kwargs) and returns: out