docstr: Convert gradient to `np.ndarray`.
  
  Converts gradient tensor to flat `numpy` array. If the gradient is a sparse tensor, it is converted to a dense
  tensor first.
docstr_tok: ["Convert","gradient","to","`","np.ndarray","`",".","Converts","gradient","tensor","to","flat","`","numpy","`","array",".","If","the","gradient","is","a","sparse","tensor",",","it","is","converted","to","a","dense","tensor","first","."]
code: def _grad_to_numpy(
      grad: torch.Tensor, name: Optional[str] = None
  ) -> np.ndarray:
      """Convert gradient to `np.ndarray`.
  
      Converts gradient tensor to flat `numpy` array. If the gradient is a sparse tensor, it is converted to a dense
      tensor first.
      """
      if grad.is_sparse:
          grad = grad.to_dense()
  
      if not hasattr(grad, "numpy"):
          name = f" for the named tensor: {name}" if name else ""
          raise TypeError(
              (
                  f"Could not convert gradient to `numpy` array{name}. To ignore these "
                  "gradients in the similarity computation set ``requires_grad=False`` on the "
                  "corresponding parameter."
              )
          )
      return grad.reshape(-1).cpu().numpy()
  
file_path: alibi/alibi/explainers/similarity/backends/pytorch/base.py
imports: from typing import Any, Callable, List, Optional, Union
  import numpy
  import torch
  import torch.nn
label_desc: Use image node_id 2 for calling the _PytorchBackend obj's underlying member method code with example usage: obj._grad_to_numpy(grad, name) and returns: grad