code: def get_confusion_matrix(
      y_pred: torch.Tensor,
      y: torch.Tensor,
      include_background: bool = True,
  ) -> torch.Tensor:
      """
      Compute confusion matrix. A tensor with the shape [BC4] will be returned. Where, the third dimension
      represents the number of true positive, false positive, true negative and false negative values for
      each channel of each sample within the input batch. Where, B equals to the batch size and C equals to
      the number of classes that need to be computed.
  
      Args:
          y_pred: input data to compute. It must be one-hot format and first dim is batch.
              The values should be binarized.
          y: ground truth to compute the metric. It must be one-hot format and first dim is batch.
              The values should be binarized.
          include_background: whether to include metric computation on the first channel of
              the predicted output. Defaults to True.
  
      Raises:
          ValueError: when `y_pred` and `y` have different shapes.
      """
  
      if not include_background:
          y_pred, y = ignore_background(y_pred=y_pred, y=y)
  
      if y.shape != y_pred.shape:
          raise ValueError(
              f"y_pred and y should have same shapes, got {y_pred.shape} and {y.shape}."
          )
  
      # get confusion matrix related metric
      batch_size, n_class = y_pred.shape[:2]
      # convert to [BNS], where S is the number of pixels for one sample.
      # As for classification tasks, S equals to 1.
      y_pred = y_pred.reshape(batch_size, n_class, -1)
      y = y.reshape(batch_size, n_class, -1)
      tp = (y_pred + y) == 2
      tn = (y_pred + y) == 0
  
      tp = tp.sum(dim=[2]).float()
      tn = tn.sum(dim=[2]).float()
      p = y.sum(dim=[2]).float()
      n = y.shape[-1] - p
  
      fn = p - tp
      fp = n - tn
  
      return torch.stack([tp, fp, tn, fn], dim=-1)
  
file_path: MONAI/monai/metrics/confusion_matrix.py
imports: from __future__ import annotations
  import warnings
  from collections.abc import Sequence
  import torch
  from monai.metrics.utils import do_metric_reduction, ignore_background
  from monai.utils import MetricReduction, ensure_tuple
  from .metric import CumulativeIterationMetric
label_desc: Use image node_id 1 for calling a global function with example usage: get_confusion_matrix(y_pred, y, include_background) and returns: torch