class_docstr: Class for importing MXNet Gluon models.
docstr: Compute per-class derivatives w.r.t. `x`.
  
  :param x: Sample input with shape as expected by the model.
  :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class
                output is computed for all samples. If multiple values as provided, the first dimension should
                match the batch size of `x`, and each value will be used as target for its corresponding sample in
                `x`. If `None`, then gradients for all classes will be computed for each sample.
  :param training_mode: `True` for model set to training mode and `'False` for model set to evaluation mode.
  :return: Array of gradients of input features w.r.t. each class in the form
           `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes
           `(batch_size, 1, input_shape)` when `label` parameter is specified.
docstr_tok: ["Compute","per-class","derivatives","w.r.t",".","`","x","`",".",":","param","x",":","Sample","input","with","shape","as","expected","by","the","model",".",":","param","label",":","Index","of","a","specific","per-class","derivative",".","If","an","integer","is","provided",",","the","gradient","of","that","class","output","is","computed","for","all","samples",".","If","multiple","values","as","provided",",","the","first","dimension","should","match","the","batch","size","of","`","x","`",",","and","each","value","will","be","used","as","target","for","its","corresponding","sample","in","`","x","`",".","If","`","None","`",",","then","gradients","for","all","classes","will","be","computed","for","each","sample",".",":","param","training_mode",":","`","True","`","for","model","set","to","training","mode","and","`","'False","`","for","model","set","to","evaluation","mode",".",":","return",":","Array","of","gradients","of","input","features","w.r.t",".","each","class","in","the","form","`","(","batch_size",",","nb_classes",",","input_shape",")","`","when","computing","for","all","classes",",","otherwise","shape","becomes","`","(","batch_size",",","1",",","input_shape",")","`","when","`","label","`","parameter","is","specified","."]
code: def class_gradient(  # pylint: disable=W0221
      self,
      x: np.ndarray,
      label: Optional[Union[int, List[int], np.ndarray]] = None,
      training_mode: bool = False,
      **kwargs,
  ) -> np.ndarray:
      """
      Compute per-class derivatives w.r.t. `x`.
  
      :param x: Sample input with shape as expected by the model.
      :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class
                    output is computed for all samples. If multiple values as provided, the first dimension should
                    match the batch size of `x`, and each value will be used as target for its corresponding sample in
                    `x`. If `None`, then gradients for all classes will be computed for each sample.
      :param training_mode: `True` for model set to training mode and `'False` for model set to evaluation mode.
      :return: Array of gradients of input features w.r.t. each class in the form
               `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes
               `(batch_size, 1, input_shape)` when `label` parameter is specified.
      """
      import mxnet as mx
  
      # Check value of label for computing gradients
      if not (  # pragma: no cover
          label is None
          or (
              isinstance(label, int) and label in range(self.nb_classes)
          )
          or (
              isinstance(label, np.ndarray)
              and len(label.shape) == 1
              and (label < self.nb_classes).all()
              and label.shape[0] == x.shape[0]
          )
      ):
          raise ValueError(f"Label {label} is out of range.")
  
      # Apply preprocessing
      x_preprocessed, _ = self._apply_preprocessing(
          x, y=None, fit=False
      )
      x_preprocessed = mx.nd.array(
          x_preprocessed.astype(config.ART_NUMPY_DTYPE), ctx=self.ctx
      )
      x_preprocessed.attach_grad()
  
      if label is None:
          with mx.autograd.record(train_mode=False):
              preds = self._model(x_preprocessed)
              class_slices = [
                  preds[:, i] for i in range(self.nb_classes)
              ]
  
          grads_list = []
          for slice_ in class_slices:
              slice_.backward(retain_graph=True)
              grad = x_preprocessed.grad.asnumpy()
              grads_list.append(grad)
          grads = np.swapaxes(np.array(grads_list), 0, 1)
      elif isinstance(label, int):
          with mx.autograd.record(train_mode=training_mode):
              preds = self._model(x_preprocessed)
              class_slice = preds[:, label]
  
          class_slice.backward()
          grads = np.expand_dims(x_preprocessed.grad.asnumpy(), axis=1)
      else:
          unique_labels = list(np.unique(label))
  
          with mx.autograd.record(train_mode=training_mode):
              preds = self._model(x_preprocessed)
              class_slices = [preds[:, i] for i in unique_labels]
  
          grads_list = []
          for slice_ in class_slices:
              slice_.backward(retain_graph=True)
              grad = x_preprocessed.grad.asnumpy()
              grads_list.append(grad)
  
          grads = np.swapaxes(np.array(grads_list), 0, 1)
          lst = [unique_labels.index(i) for i in label]
          grads = grads[np.arange(len(grads)), lst]
          grads = np.expand_dims(grads, axis=1)
  
      grads = self._apply_preprocessing_gradient(x, grads)
  
      return grads
  
imports: from __future__ import absolute_import, division, print_function, unicode_literals
  import logging
  import os
  from typing import List, Optional, Tuple, Union, TYPE_CHECKING
  import numpy
  import six
  from art import config
  from art.estimators.mxnet import MXEstimator
  from art.estimators.classification.classifier import ClassGradientsMixin, ClassifierMixin
  from art.utils import check_and_transform_label_format
label_desc: Use image node_id 9 for calling the MXClassifier obj's underlying member method code with example usage: obj.class_gradient(x, label, training_mode) and returns: grads