docstr: `GradientSimilarity` explainer.
  
  The gradient similarity explainer is used to find examples in the training data that the predictor considers
  similar to test instances the user wants to explain. It uses the gradients of the loss between the model output
  and the training data labels. These are compared using the similarity function specified by ``sim_fn``. The
  `GradientSimilarity` explainer can be applied to models trained for both classification and regression tasks.
  
  
  Parameters
  ----------
  predictor
      Model to explain.
  loss_fn
      Loss function used. The gradient of the loss function is used to compute the similarity between the test
      instances and the training set.
  sim_fn
      Similarity function to use. The ``'grad_dot'`` similarity function computes the dot product of the
      gradients, see :py:func:`alibi.explainers.similarity.metrics.dot`. The ``'grad_cos'`` similarity function
      computes the cosine similarity between the gradients, see
      :py:func:`alibi.explainers.similarity.metrics.cos`. The ``'grad_asym_dot'`` similarity function is similar
      to ``'grad_dot'`` but is asymmetric, see :py:func:`alibi.explainers.similarity.metrics.asym_dot`.
  task
      Type of task performed by the model. If the task is ``'classification'``, the target value passed to the
      explain method of the test instance can be specified either directly or left  as ``None``, if left ``None``
      we use the model's maximum prediction. If the task is ``'regression'``, the target value of the test
      instance must be specified directly.
  precompute_grads
      Whether to precompute the gradients. If ``False``, gradients are computed on the fly otherwise we
      precompute them which can be faster when it comes to computing explanations. Note this option may be memory
      intensive if the model is large.
  backend
      Backend to use.
  device
      Device to use. If ``None``, the default device for the backend is used. If using `pytorch` backend see
      `pytorch device docs <https://pytorch.org/docs/stable/tensor_attributes.html#torch-device>`_ for correct
      options. Note that in the `pytorch` backend case this parameter can be a ``torch.device``. If using
      `tensorflow` backend see `tensorflow docs <https://www.tensorflow.org/api_docs/python/tf/device>`_ for
      correct options.
  verbose
      Whether to print the progress of the explainer.
  
  Raises
  ------
  ValueError
      If the ``task`` is not ``'classification'`` or ``'regression'``.
  ValueError
      If the ``sim_fn`` is not ``'grad_dot'``, ``'grad_cos'`` or ``'grad_asym_dot'``.
  ValueError
      If the ``backend`` is not ``'tensorflow'`` or ``'pytorch'``.
  TypeError
      If the device is not an ``int``, ``str``, ``torch.device`` or ``None`` for the torch backend option or if
      the device is not ``str`` or ``None`` for the tensorflow backend option.
docstr_tok: ["`","GradientSimilarity","`","explainer",".","The","gradient","similarity","explainer","is","used","to","find","examples","in","the","training","data","that","the","predictor","considers","similar","to","test","instances","the","user","wants","to","explain",".","It","uses","the","gradients","of","the","loss","between","the","model","output","and","the","training","data","labels",".","These","are","compared","using","the","similarity","function","specified","by","``","sim_fn","``",".","The","`","GradientSimilarity","`","explainer","can","be","applied","to","models","trained","for","both","classification","and","regression","tasks",".","Parameters","--","--","--","--","--","predictor","Model","to","explain",".","loss_fn","Loss","function","used",".","The","gradient","of","the","loss","function","is","used","to","compute","the","similarity","between","the","test","instances","and","the","training","set",".","sim_fn","Similarity","function","to","use",".","The","``","'grad_dot","'","``","similarity","function","computes","the","dot","product","of","the","gradients",",","see",":","py",":","func",":","`","alibi.explainers.similarity.metrics.dot","`",".","The","``","'grad_cos","'","``","similarity","function","computes","the","cosine","similarity","between","the","gradients",",","see",":","py",":","func",":","`","alibi.explainers.similarity.metrics.cos","`",".","The","``","'grad_asym_dot","'","``","similarity","function","is","similar","to","``","'grad_dot","'","``","but","is","asymmetric",",","see",":","py",":","func",":","`","alibi.explainers.similarity.metrics.asym_dot","`",".","task","Type","of","task","performed","by","the","model",".","If","the","task","is","``","'classification","'","``",",","the","target","value","passed","to","the","explain","method","of","the","test","instance","can","be","specified","either","directly","or","left","as","``","None","``",",","if","left","``","None","``","we","use","the","model","'s","maximum","prediction",".","If","the","task","is","``","'regression","'","``",",","the","target","value","of","the","test","instance","must","be","specified","directly",".","precompute_grads","Whether","to","precompute","the","gradients",".","If","``","False","``",",","gradients","are","computed","on","the","fly","otherwise","we","precompute","them","which","can","be","faster","when","it","comes","to","computing","explanations",".","Note","this","option","may","be","memory","intensive","if","the","model","is","large",".","backend","Backend","to","use",".","device","Device","to","use",".","If","``","None","``",",","the","default","device","for","the","backend","is","used",".","If","using","`","pytorch","`","backend","see","`","pytorch","device","docs","<","https",":","\/\/pytorch.org\/docs\/stable\/tensor_attributes.html","#","torch-device",">","`","_","for","correct","options",".","Note","that","in","the","`","pytorch","`","backend","case","this","parameter","can","be","a","``","torch.device","``",".","If","using","`","tensorflow","`","backend","see","`","tensorflow","docs","<","https",":","\/\/www.tensorflow.org\/api_docs\/python\/tf\/device",">","`","_","for","correct","options",".","verbose","Whether","to","print","the","progress","of","the","explainer",".","Raises","--","--","--","ValueError","If","the","``","task","``","is","not","``","'classification","'","``","or","``","'regression","'","``",".","ValueError","If","the","``","sim_fn","``","is","not","``","'grad_dot","'","``",",","``","'grad_cos","'","``","or","``","'grad_asym_dot","'","``",".","ValueError","If","the","``","backend","``","is","not","``","'tensorflow","'","``","or","``","'pytorch","'","``",".","TypeError","If","the","device","is","not","an","``","int","``",",","``","str","``",",","``","torch.device","``","or","``","None","``","for","the","torch","backend","option","or","if","the","device","is","not","``","str","``","or","``","None","``","for","the","tensorflow","backend","option","."]
code: def __init__(
      self,
      predictor: "Union[tensorflow.keras.Model, torch.nn.Module]",
      loss_fn: """Union[Callable[[tensorflow.Tensor, tensorflow.Tensor], tensorflow.Tensor],
                                     Callable[[torch.Tensor, torch.Tensor], torch.Tensor]]""",
      sim_fn: Literal[
          "grad_dot", "grad_cos", "grad_asym_dot"
      ] = "grad_dot",
      task: Literal["classification", "regression"] = "classification",
      precompute_grads: bool = False,
      backend: Literal["tensorflow", "pytorch"] = "tensorflow",
      device: "Union[int, str, torch.device, None]" = None,
      verbose: bool = False,
  ):
      """`GradientSimilarity` explainer.
  
      The gradient similarity explainer is used to find examples in the training data that the predictor considers
      similar to test instances the user wants to explain. It uses the gradients of the loss between the model output
      and the training data labels. These are compared using the similarity function specified by ``sim_fn``. The
      `GradientSimilarity` explainer can be applied to models trained for both classification and regression tasks.
  
  
      Parameters
      ----------
      predictor
          Model to explain.
      loss_fn
          Loss function used. The gradient of the loss function is used to compute the similarity between the test
          instances and the training set.
      sim_fn
          Similarity function to use. The ``'grad_dot'`` similarity function computes the dot product of the
          gradients, see :py:func:`alibi.explainers.similarity.metrics.dot`. The ``'grad_cos'`` similarity function
          computes the cosine similarity between the gradients, see
          :py:func:`alibi.explainers.similarity.metrics.cos`. The ``'grad_asym_dot'`` similarity function is similar
          to ``'grad_dot'`` but is asymmetric, see :py:func:`alibi.explainers.similarity.metrics.asym_dot`.
      task
          Type of task performed by the model. If the task is ``'classification'``, the target value passed to the
          explain method of the test instance can be specified either directly or left  as ``None``, if left ``None``
          we use the model's maximum prediction. If the task is ``'regression'``, the target value of the test
          instance must be specified directly.
      precompute_grads
          Whether to precompute the gradients. If ``False``, gradients are computed on the fly otherwise we
          precompute them which can be faster when it comes to computing explanations. Note this option may be memory
          intensive if the model is large.
      backend
          Backend to use.
      device
          Device to use. If ``None``, the default device for the backend is used. If using `pytorch` backend see
          `pytorch device docs <https://pytorch.org/docs/stable/tensor_attributes.html#torch-device>`_ for correct
          options. Note that in the `pytorch` backend case this parameter can be a ``torch.device``. If using
          `tensorflow` backend see `tensorflow docs <https://www.tensorflow.org/api_docs/python/tf/device>`_ for
          correct options.
      verbose
          Whether to print the progress of the explainer.
  
      Raises
      ------
      ValueError
          If the ``task`` is not ``'classification'`` or ``'regression'``.
      ValueError
          If the ``sim_fn`` is not ``'grad_dot'``, ``'grad_cos'`` or ``'grad_asym_dot'``.
      ValueError
          If the ``backend`` is not ``'tensorflow'`` or ``'pytorch'``.
      TypeError
          If the device is not an ``int``, ``str``, ``torch.device`` or ``None`` for the torch backend option or if
          the device is not ``str`` or ``None`` for the tensorflow backend option.
      """
      # TODO: add link to docs page for GradientSimilarity explainer in the docstring once written
  
      sim_fn_opts: Dict[str, Callable] = {
          "grad_dot": dot,
          "grad_cos": cos,
          "grad_asym_dot": asym_dot,
      }
  
      if sim_fn not in sim_fn_opts.keys():
          raise ValueError(
              f"""Unknown method {sim_fn}. Consider using: '{"' | '".join(sim_fn_opts.keys())}'."""
          )
  
      resolved_sim_fn = sim_fn_opts[sim_fn]
  
      if task not in Task.__members__.values():
          raise ValueError(
              f"Unknown task {task}. Consider using: {_get_options_string(Task)}."
          )
  
      self.task = task
  
      if backend not in Framework.__members__.values():
          raise ValueError(
              f"Unknown backend {backend}. Consider using: {_get_options_string(Framework)}."
          )
  
      super().__init__(
          predictor,
          loss_fn,
          resolved_sim_fn,
          precompute_grads,
          Framework(backend),
          device=device,
          meta=copy.deepcopy(DEFAULT_META_SIM),
          verbose=verbose,
      )
  
      self.meta["params"].update(
          sim_fn_name=sim_fn,
          store_grads=precompute_grads,
          backend_name=backend,
          task_name=task,
      )
  
      num_non_trainable = self.backend._count_non_trainable(
          self.predictor
      )
      if num_non_trainable:
          warning_msg = (
              f"Found {num_non_trainable} non-trainable parameters in the model. These parameters "
              "don't have gradients and will not be included in the computation of gradient similarity."
              " This might be because your model has layers that track statistics using non-trainable "
              "parameters such as batch normalization layers. In this case, you don't need to worry. "
              "Otherwise it's because you have set some parameters to be non-trainable and alibi is "
              "letting you know."
          )
          warnings.warn(warning_msg)
  
imports: import copy
  import warnings
  from enum import Enum
  from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
  import numpy
  from alibi.api.defaults import DEFAULT_DATA_SIM, DEFAULT_META_SIM
  from alibi.api.interfaces import Explainer, Explanation
  from alibi.explainers.similarity.base import BaseSimilarityExplainer
  from alibi.explainers.similarity.metrics import asym_dot, cos, dot
  from alibi.utils import _get_options_string
  from alibi.utils.frameworks import Framework
  from typing_extensions import Literal
label_desc: Use image node_id 1 to create a new GradientSimilarity object from inherited base classes: BaseSimilarityExplainer with example: obj = GradientSimilarity(predictor, loss_fn, sim_fn, task, precompute_grads, backend, device, verbose)