code: def multilabel_confusion_matrix(
      y_true,
      y_pred,
      *,
      sample_weight=None,
      labels=None,
      samplewise=False,
      session=None,
      run_kwargs=None,
  ):
      """
      Compute a confusion matrix for each class or sample.
  
      Compute class-wise (default) or sample-wise (samplewise=True) multilabel
      confusion matrix to evaluate the accuracy of a classification, and output
      confusion matrices for each class or sample.
  
      In multilabel confusion matrix :math:`MCM`, the count of true negatives
      is :math:`MCM_{:,0,0}`, false negatives is :math:`MCM_{:,1,0}`,
      true positives is :math:`MCM_{:,1,1}` and false positives is
      :math:`MCM_{:,0,1}`.
  
      Multiclass data will be treated as if binarized under a one-vs-rest
      transformation. Returned confusion matrices will be in the order of
      sorted unique labels in the union of (y_true, y_pred).
  
      Read more in the :ref:`User Guide <multilabel_confusion_matrix>`.
  
      Parameters
      ----------
      y_true : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \
              (n_samples,)
          Ground truth (correct) target values.
  
      y_pred : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \
              (n_samples,)
          Estimated targets as returned by a classifier.
  
      sample_weight : array-like of shape (n_samples,), default=None
          Sample weights.
  
      labels : array-like of shape (n_classes,), default=None
          A list of classes or column indices to select some (or to force
          inclusion of classes absent from the data).
  
      samplewise : bool, default=False
          In the multilabel case, this calculates a confusion matrix per sample.
  
      Returns
      -------
      multi_confusion : ndarray of shape (n_outputs, 2, 2)
          A 2x2 confusion matrix corresponding to each output in the input.
          When calculating class-wise multi_confusion (default), then
          n_outputs = n_labels; when calculating sample-wise multi_confusion
          (samplewise=True), n_outputs = n_samples. If ``labels`` is defined,
          the results will be returned in the order specified in ``labels``,
          otherwise the results will be returned in sorted order by default.
  
      See Also
      --------
      confusion_matrix : Compute confusion matrix to evaluate the accuracy of a
          classifier.
  
      Notes
      -----
      The `multilabel_confusion_matrix` calculates class-wise or sample-wise
      multilabel confusion matrices, and in multiclass tasks, labels are
      binarized under a one-vs-rest way; while
      :func:`~sklearn.metrics.confusion_matrix` calculates one confusion matrix
      for confusion between every two classes.
  
      Examples
      --------
      Multiclass case:
  
      >>> import mars.tensor as mt
      >>> from mars.learn.metrics import multilabel_confusion_matrix
      >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
      >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
      >>> multilabel_confusion_matrix(y_true, y_pred,
      ...                             labels=["ant", "bird", "cat"])
      array([[[3, 1],
              [0, 2]],
      <BLANKLINE>
             [[5, 0],
              [1, 0]],
      <BLANKLINE>
             [[2, 1],
              [1, 2]]])
  
      Multilabel-indicator case not implemented yet.
      """
      exec_kw = dict(session=session, **(run_kwargs or dict()))
  
      y_type, y_true, y_pred = _check_targets(y_true, y_pred)
      execute(y_type, y_true, y_pred, **exec_kw)
      y_type = y_type.fetch()
  
      if sample_weight is not None:
          sample_weight = column_or_1d(sample_weight)
      check_consistent_length(y_true, y_pred, sample_weight, **exec_kw)
  
      if y_type not in ("binary", "multiclass", "multilabel-indicator"):
          raise ValueError("%s is not supported" % y_type)
  
      present_labels = unique_labels(y_true, y_pred)
      if labels is None:
          labels = present_labels
          n_labels = None
      else:
          labels = mt.tensor(labels)
          n_labels = labels.shape[0]
          # todo simplify this when mt.setdiff1d is implemented.
          labels = labels.rechunk(((np.nan,),)).map_chunk(
              lambda l, pl: np.hstack(
                  [l, np.setdiff1d(pl, l, assume_unique=True)]
              ),
              args=(present_labels,),
              dtype=labels.dtype,
              shape=(np.nan,),
          )
  
      if y_true.ndim == 1:
          if samplewise:
              raise ValueError(
                  "Samplewise metrics are not available outside of "
                  "multilabel classification."
              )
  
          le = LabelEncoder()
          le.fit(labels, execute=False)
          y_true = le.transform(y_true, execute=False)
          y_pred = le.transform(y_pred, execute=False)
          sorted_labels = le.classes_
  
          # labels are now from 0 to len(labels) - 1 -> use bincount
          tp = y_true == y_pred
          tp_bins = y_true[tp]
          execute(labels, y_true, y_pred, tp_bins, **exec_kw)
          if sample_weight is not None:
              tp_bins_weights = mt.asarray(sample_weight)[tp]
          else:
              tp_bins_weights = None
  
          if tp_bins.shape[0]:
              tp_sum = mt.bincount(
                  tp_bins,
                  weights=tp_bins_weights,
                  minlength=labels.shape[0],
              )
          else:
              # Pathological case
              true_sum = pred_sum = tp_sum = mt.zeros(labels.shape[0])
          if y_pred.shape[0]:
              pred_sum = mt.bincount(
                  y_pred,
                  weights=sample_weight,
                  minlength=labels.shape[0],
              )
          if y_true.shape[0]:
              true_sum = mt.bincount(
                  y_true,
                  weights=sample_weight,
                  minlength=labels.shape[0],
              )
  
          # Retain only selected labels
          indices = mt.searchsorted(sorted_labels, labels[:n_labels])
          tp_sum = tp_sum[indices]
          true_sum = true_sum[indices]
          pred_sum = pred_sum[indices]
  
      else:
          sum_axis = 1 if samplewise else 0
  
          def _check_labels(labels, present_labels):
              # All labels are index integers for multilabel.
              # Select labels:
              if not np.array_equal(labels, present_labels):
                  if np.max(labels) > np.max(present_labels):
                      raise ValueError(
                          "All labels must be in [0, n labels) for "
                          "multilabel targets. "
                          "Got %d > %d"
                          % (np.max(labels), np.max(present_labels))
                      )
                  if np.min(labels) < 0:
                      raise ValueError(
                          "All labels must be in [0, n labels) for "
                          "multilabel targets. "
                          "Got %d < 0" % np.min(labels)
                      )
              return labels
  
          labels = labels.map_chunk(
              _check_labels,
              args=(present_labels,),
              dtype=labels.dtype,
              shape=labels.shape,
          )
  
          if n_labels is not None:
              y_true = y_true[:, labels[:n_labels]]
              y_pred = y_pred[:, labels[:n_labels]]
  
          # calculate weighted counts
          true_and_pred = mt.multiply(y_true, y_pred)
          tp_sum = count_nonzero(
              true_and_pred, axis=sum_axis, sample_weight=sample_weight
          )
          pred_sum = count_nonzero(
              y_pred, axis=sum_axis, sample_weight=sample_weight
          )
          true_sum = count_nonzero(
              y_true, axis=sum_axis, sample_weight=sample_weight
          )
  
      fp = pred_sum - tp_sum
      fn = true_sum - tp_sum
      tp = tp_sum
  
      # we need to obtain correct shape of y_true for further computation
      executables = (fp, fn, tp, y_true)
      execute(*executables, **exec_kw)
  
      if sample_weight is not None and samplewise:
          sample_weight = mt.asarray(sample_weight)
          tp = mt.asarray(tp)
          fp = mt.asarray(fp)
          fn = mt.asarray(fn)
          tn = sample_weight * y_true.shape[1] - tp - fp - fn
      elif sample_weight is not None:
          tn = sum(sample_weight) - tp - fp - fn
      elif samplewise:
          tn = y_true.shape[1] - tp - fp - fn
      else:
          tn = y_true.shape[0] - tp - fp - fn
  
      ret = mt.array([tn, fp, fn, tp]).T.reshape(-1, 2, 2)
      return ret.execute(**exec_kw)
  
imports: import warnings
  import numpy
  from sklearn.exceptions import UndefinedMetricWarning
  from ...None import execute, fetch
  from ...None import opcodes
  from ...None import tensor
  from ...core import ENTITY_TYPE, recursive_tile
  from ...core.context import get_context
  from ...serialization.serializables import AnyField, BoolField, KeyField
  from ...tensor.core import TensorOrder
  from ..operands import LearnOperand, LearnOperandMixin, OutputType
  from ..preprocessing import LabelBinarizer, LabelEncoder
  from ..utils import check_array, check_consistent_length, column_or_1d
  from ..utils.multiclass import unique_labels
  from ..utils.sparsefuncs import count_nonzero
  from ._check_targets import _check_targets
label_desc: Use image node_id 4 for calling a global function with example usage: multilabel_confusion_matrix(y_true, y_pred) and returns: ret, labels