code: def IoU(
      cm: ConfusionMatrix, ignore_index: Optional[int] = None
  ) -> MetricsLambda:
      r"""Calculates Intersection over Union using :class:`~ignite.metrics.confusion_matrix.ConfusionMatrix` metric.
  
      .. math:: \text{J}(A, B) = \frac{ \lvert A \cap B \rvert }{ \lvert A \cup B \rvert }
  
      Args:
          cm: instance of confusion matrix metric
          ignore_index: index to ignore, e.g. background index
  
      Returns:
          MetricsLambda
  
      Examples:
  
          For more information on how metric works with :class:`~ignite.engine.engine.Engine`, visit :ref:`attach-engine`.
  
          .. include:: defaults.rst
              :start-after: :orphan:
  
          .. testcode::
  
              cm = ConfusionMatrix(num_classes=3)
              metric = IoU(cm)
              metric.attach(default_evaluator, 'iou')
              y_true = torch.tensor([0, 1, 0, 1, 2])
              y_pred = torch.tensor([
                  [0.0, 1.0, 0.0],
                  [0.0, 1.0, 0.0],
                  [1.0, 0.0, 0.0],
                  [0.0, 1.0, 0.0],
                  [0.0, 1.0, 0.0],
              ])
              state = default_evaluator.run([[y_pred, y_true]])
              print(state.metrics['iou'])
  
          .. testoutput::
  
              tensor([0.5000, 0.5000, 0.0000], dtype=torch.float64)
      """
      if not isinstance(cm, ConfusionMatrix):
          raise TypeError(
              f"Argument cm should be instance of ConfusionMatrix, but given {type(cm)}"
          )
  
      if not (cm.average in (None, "samples")):
          raise ValueError(
              "ConfusionMatrix should have average attribute either None or 'samples'"
          )
  
      if ignore_index is not None:
          if not (
              isinstance(ignore_index, numbers.Integral)
              and 0 <= ignore_index < cm.num_classes
          ):
              raise ValueError(
                  f"ignore_index should be integer and in the range of [0, {cm.num_classes}), but given {ignore_index}"
              )
  
      # Increase floating point precision and pass to CPU
      cm = cm.to(torch.double)
      iou: MetricsLambda = cm.diag() / (
          cm.sum(dim=1) + cm.sum(dim=0) - cm.diag() + 1e-15
      )
      if ignore_index is not None:
          ignore_idx: int = (
              ignore_index  # used due to typing issues with mympy
          )
  
          def ignore_index_fn(iou_vector: torch.Tensor) -> torch.Tensor:
              if ignore_idx >= len(iou_vector):
                  raise ValueError(
                      f"ignore_index {ignore_idx} is larger than the length of IoU vector {len(iou_vector)}"
                  )
              indices = list(range(len(iou_vector)))
              indices.remove(ignore_idx)
              return iou_vector[indices]
  
          return MetricsLambda(ignore_index_fn, iou)
      else:
          return iou
  
imports: import numbers
  from typing import Callable, Optional, Sequence, Tuple, Union
  import torch
  from ignite.exceptions import NotComputableError
  from ignite.metrics.metric import Metric, reinit__is_reduced, sync_all_reduce
  from ignite.metrics.metrics_lambda import MetricsLambda
label_desc: Use image node_id 1 for calling a global function with example usage: IoU(cm, ignore_index) and returns: MetricsLambda, iou, iou_vector