def result(self):
        """Compute the intersection-over-union via the confusion matrix."""
        sum_over_row = ops.cast(
            ops.sum(self.total_cm, axis=0), dtype=self.dtype
        )
        sum_over_col = ops.cast(
            ops.sum(self.total_cm, axis=1), dtype=self.dtype
        )
        true_positives = ops.cast(ops.diag(self.total_cm), dtype=self.dtype)

        # sum_over_row + sum_over_col =
        #     2 * true_positives + false_positives + false_negatives.
        denominator = sum_over_row + sum_over_col - true_positives

        target_class_ids = ops.convert_to_tensor(
            self.target_class_ids, dtype="int32"
        )

        # Only keep the target classes
        true_positives = ops.take_along_axis(
            true_positives, target_class_ids, axis=-1
        )
        denominator = ops.take_along_axis(
            denominator, target_class_ids, axis=-1
        )
        denominator = ops.cast(denominator, dtype="float32")

        # If the denominator is 0, we need to ignore the class.
        num_valid_entries = ops.sum(
            ops.cast(ops.greater(denominator, 1e-9), dtype="float32")
        )

        iou = ops.divide(true_positives, denominator + backend.epsilon())

        return ops.divide(
            ops.sum(iou, axis=self.axis), num_valid_entries + backend.epsilon()
        )
Compute the intersection-over-union via the confusion matrix.
keras/src/metrics/iou_metrics.py