code: def compute_iou(
      y_pred: torch.Tensor,
      y: torch.Tensor,
      include_background: bool = True,
      ignore_empty: bool = True,
  ) -> torch.Tensor:
      """Computes Intersection over Union (IoU) score metric from a batch of predictions.
  
      Args:
          y_pred: input data to compute, typical segmentation model output.
              It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values
              should be binarized.
          y: ground truth to compute mean IoU metric. It must be one-hot format and first dim is batch.
              The values should be binarized.
          include_background: whether to include IoU computation on the first channel of
              the predicted output. Defaults to True.
          ignore_empty: whether to ignore empty ground truth cases during calculation.
              If `True`, NaN value will be set for empty ground truth cases.
              If `False`, 1 will be set if the predictions of empty ground truth cases are also empty.
  
      Returns:
          IoU scores per batch and per class, (shape [batch_size, num_classes]).
  
      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}."
          )
  
      # reducing only spatial dimensions (not batch nor channels)
      n_len = len(y_pred.shape)
      reduce_axis = list(range(2, n_len))
      intersection = torch.sum(y * y_pred, dim=reduce_axis)
  
      y_o = torch.sum(y, reduce_axis)
      y_pred_o = torch.sum(y_pred, dim=reduce_axis)
      union = y_o + y_pred_o - intersection
  
      if ignore_empty:
          return torch.where(
              y_o > 0,
              (intersection) / union,
              torch.tensor(float("nan"), device=y_o.device),
          )
      return torch.where(
          union > 0,
          (intersection) / union,
          torch.tensor(1.0, device=y_o.device),
      )
  
file_path: MONAI/monai/metrics/meaniou.py
imports: from __future__ import annotations
  import torch
  from monai.metrics.utils import do_metric_reduction, ignore_background
  from monai.utils import MetricReduction
  from .metric import CumulativeIterationMetric
label_desc: Use image node_id 1 for calling a global function with example usage: compute_iou(y_pred, y, include_background, ignore_empty) and returns: torch, torch