code: def _histogram_to_binary_confusion_matrices(
      thresholds: List[float],
      histogram: calibration_histogram.Histogram,
  ) -> Matrices:
      """Converts histogram to binary confusion matrices."""
      # tp(i) - sum of positive labels >= bucket i
      # fp(i) - sum of negative labels >= bucket i
      # fn(i) - sum of positive labels < bucket i
      # tn(i) - sum of negative labels < bucket i
      n = len(histogram)
      tp = [0.0] * n
      fp = [0.0] * n
      tn = [0.0] * n
      fn = [0.0] * n
      for i in range(n):
          start = i
          end = n - i - 1
          start_pos = histogram[start].weighted_labels
          start_neg = (
              histogram[start].weighted_examples
              - histogram[start].weighted_labels
          )
          end_pos = histogram[end].weighted_labels
          end_neg = (
              histogram[end].weighted_examples
              - histogram[end].weighted_labels
          )
          tp[end] = tp[end + 1] + end_pos if end < n - 1 else end_pos
          fp[end] = fp[end + 1] + end_neg if end < n - 1 else end_neg
          if start + 1 < n:
              tn[start + 1] = tn[start] + start_neg
              fn[start + 1] = fn[start] + start_pos
      # Check if need to remove -epsilon bucket (or reset back to 1 bucket).
      threshold_offset = 0
      if (thresholds[0] >= 0 or len(thresholds) == 1) and len(
          histogram
      ) > 1:
          threshold_offset = 1
      tp = tp[threshold_offset : threshold_offset + len(thresholds)]
      fp = fp[threshold_offset : threshold_offset + len(thresholds)]
      tn = tn[threshold_offset : threshold_offset + len(thresholds)]
      fn = fn[threshold_offset : threshold_offset + len(thresholds)]
      # We sum all values >= bucket i, but TP/FP values greater that 1.0 + EPSILON
      # should be 0.0. The FN/TN above 1.0 + _EPSILON should also be adjusted to
      # match the TP/FP values at the start.
      for i, t in enumerate(thresholds):
          if t >= 1.0 + _EPSILON:
              tp[i] = 0.0
              fp[i] = 0.0
              fn[i] = tp[0]
              tn[i] = fp[0]
      return Matrices(thresholds, tp, tn, fp, fn)
  
imports: from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union
  import apache_beam
  import numpy
  from tensorflow_model_analysis.api import types
  from tensorflow_model_analysis.contrib.aggregates import binary_confusion_matrices
  from tensorflow_model_analysis.metrics import calibration_histogram
  from tensorflow_model_analysis.metrics import metric_types
  from tensorflow_model_analysis.metrics import metric_util
  from tensorflow_model_analysis.proto import config_pb2
  from tensorflow_model_analysis.proto import metrics_for_slice_pb2
label_desc: Use image node_id 3 for calling a global function with example usage: _histogram_to_binary_confusion_matrices(thresholds, histogram) and returns: Matrices