computes the confusion matrix for intersectionoverunion metrics formula python iou truepositives truepositives falsepositives falsenegatives intersectionoverunion is a common evaluation metric for semantic image segmentation from ious of individual classes the meaniou can be computed as the mean of the individual ious to compute ious the predictions are accumulated in a confusion matrix weighted by sampleweight and the metric is then calculated from it if sampleweight is none weights default to 1 use sampleweight of 0 to mask values args numclasses the possible number of labels the prediction task can have name optional string name of the metric instance dtype optional data type of the metric result ignoreclass optional integer the id of a class to be ignored during metric computation this is useful for example in segmentation problems featuring a void class commonly 1 or 255 in segmentation maps by default ignoreclassnone all classes are considered sparseytrue whether labels are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label sparseypred whether predictions are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label axis optional 1 is the dimension containing the logits defaults to 1 defaulting to float32 to avoid issues with confusion matrix metric should be maximized during optimization accumulates the confusion matrix statistics args ytrue the ground truth values ypred the predicted values sampleweight optional weighting of each example can be a tensor whose rank is either 0 or the same as ytrue and must be broadcastable to ytrue defaults to 1 returns update op flatten the input if its rank 1 computes the intersectionoverunion metric for specific target classes formula python iou truepositives truepositives falsepositives falsenegatives intersectionoverunion is a common evaluation metric for semantic image segmentation to compute ious the predictions are accumulated in a confusion matrix weighted by sampleweight and the metric is then calculated from it if sampleweight is none weights default to 1 use sampleweight of 0 to mask values note this class first computes ious for all individual classes then returns the mean of ious for the classes that are specified by targetclassids if targetclassids has only one id value the iou of that specific class is returned args numclasses the possible number of labels the prediction task can have targetclassids a tuple or list of target class ids for which the metric is returned to compute iou for a specific class a list or tuple of a single id value should be provided name optional string name of the metric instance dtype optional data type of the metric result ignoreclass optional integer the id of a class to be ignored during metric computation this is useful for example in segmentation problems featuring a void class commonly 1 or 255 in segmentation maps by default ignoreclassnone all classes are considered sparseytrue whether labels are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label sparseypred whether predictions are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label axis optional 1 is the dimension containing the logits defaults to 1 examples standalone usage cm 1 1 1 1 sumrow 2 2 sumcol 2 2 truepositives 1 1 iou truepositives sumrow sumcol truepositives iou 0 33 0 33 m keras metrics iounumclasses2 targetclassids0 m updatestate0 0 1 1 0 1 0 1 m result 0 33333334 m resetstate m updatestate0 0 1 1 0 1 0 1 sampleweight0 3 0 3 0 3 0 1 cm 0 3 0 3 0 3 0 1 sumrow 0 6 0 4 sumcol 0 6 0 4 truepositives 0 3 0 1 iou 0 33 0 14 m result 0 33333334 usage with compile api python model compile optimizer sgd loss mse metricskeras metrics iounumclasses2 targetclassids0 compute the intersectionoverunion via the confusion matrix sumoverrow ops cast ops sumself totalcm axis0 dtypeself dtype sumovercol ops cast ops sumself totalcm axis1 dtypeself dtype truepositives ops castops diagself totalcm dtypeself dtype sumoverrow sumovercol 2 truepositives falsepositives falsenegatives denominator sumoverrow sumovercol truepositives targetclassids ops converttotensor self targetclassids dtypeint32 only keep the target classes truepositives ops takealongaxis truepositives targetclassids axis1 denominator ops takealongaxis denominator targetclassids axis1 if the denominator is 0 we need to ignore the class numvalidentries ops sum ops castops greaterdenominator 1e9 dtypeself dtype iou ops dividetruepositives denominator backend epsilon return ops divide ops sumiou axisself axis numvalidentries backend epsilon def getconfigself config numclasses self numclasses targetclassids self targetclassids ignoreclass self ignoreclass sparseytrue self sparseytrue sparseypred self sparseypred axis self axis baseconfig super getconfig return dictlistbaseconfig items listconfig items kerasexportkeras metrics binaryiou class binaryiouiou def init self targetclassids0 1 threshold0 5 namenone dtypenone super init numclasses2 targetclassidstargetclassids namename dtypedtype self threshold threshold def updatestateself ytrue ypred sampleweightnone ytrue ops converttotensorytrue dtypeself dtype ypred ops converttotensorypred dtypeself dtype ypred ops castypred self threshold self dtype return super updatestateytrue ypred sampleweight def getconfigself return targetclassids self targetclassids threshold self threshold name self name dtype self dtype kerasexportkeras metrics meaniou class meaniouiou def init self numclasses namenone dtypenone ignoreclassnone sparseytruetrue sparseypredtrue axis1 targetclassids listrangenumclasses super init namename numclassesnumclasses targetclassidstargetclassids axisaxis dtypedtype ignoreclassignoreclass sparseytruesparseytrue sparseypredsparseypred def getconfigself return numclasses self numclasses name self name dtype self dtype ignoreclass self ignoreclass sparseytrue self sparseytrue sparseypred self sparseypred axis self axis kerasexportkeras metrics onehotiou class onehotiouiou def init self numclasses targetclassids namenone dtypenone ignoreclassnone sparseypredfalse axis1 super init numclassesnumclasses targetclassidstargetclassids namename dtypedtype ignoreclassignoreclass sparseytruefalse sparseypredsparseypred axisaxis def getconfigself return numclasses self numclasses targetclassids self targetclassids name self name dtype self dtype ignoreclass self ignoreclass sparseypred self sparseypred axis self axis kerasexportkeras metrics onehotmeaniou class onehotmeanioumeaniou def init self numclasses namenone dtypenone ignoreclassnone sparseypredfalse axis1 super init numclassesnumclasses axisaxis namename dtypedtype ignoreclassignoreclass sparseytruefalse sparseypredsparseypred def getconfigself return numclasses self numclasses name self name dtype self dtype ignoreclass self ignoreclass sparseypred self sparseypred axis self axis computes the confusion matrix for intersection over union metrics formula python iou true_positives true_positives false_positives false_negatives intersection over union is a common evaluation metric for semantic image segmentation from ious of individual classes the meaniou can be computed as the mean of the individual ious to compute ious the predictions are accumulated in a confusion matrix weighted by sample_weight and the metric is then calculated from it if sample_weight is none weights default to 1 use sample_weight of 0 to mask values args num_classes the possible number of labels the prediction task can have name optional string name of the metric instance dtype optional data type of the metric result ignore_class optional integer the id of a class to be ignored during metric computation this is useful for example in segmentation problems featuring a void class commonly 1 or 255 in segmentation maps by default ignore_class none all classes are considered sparse_y_true whether labels are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label sparse_y_pred whether predictions are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label axis optional 1 is the dimension containing the logits defaults to 1 defaulting to float32 to avoid issues with confusion matrix metric should be maximized during optimization accumulates the confusion matrix statistics args y_true the ground truth values y_pred the predicted values sample_weight optional weighting of each example can be a tensor whose rank is either 0 or the same as y_true and must be broadcastable to y_true defaults to 1 returns update op flatten the input if its rank 1 computes the intersection over union metric for specific target classes formula python iou true_positives true_positives false_positives false_negatives intersection over union is a common evaluation metric for semantic image segmentation to compute ious the predictions are accumulated in a confusion matrix weighted by sample_weight and the metric is then calculated from it if sample_weight is none weights default to 1 use sample_weight of 0 to mask values note this class first computes ious for all individual classes then returns the mean of ious for the classes that are specified by target_class_ids if target_class_ids has only one id value the iou of that specific class is returned args num_classes the possible number of labels the prediction task can have target_class_ids a tuple or list of target class ids for which the metric is returned to compute iou for a specific class a list or tuple of a single id value should be provided name optional string name of the metric instance dtype optional data type of the metric result ignore_class optional integer the id of a class to be ignored during metric computation this is useful for example in segmentation problems featuring a void class commonly 1 or 255 in segmentation maps by default ignore_class none all classes are considered sparse_y_true whether labels are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label sparse_y_pred whether predictions are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label axis optional 1 is the dimension containing the logits defaults to 1 examples standalone usage cm 1 1 1 1 sum_row 2 2 sum_col 2 2 true_positives 1 1 iou true_positives sum_row sum_col true_positives iou 0 33 0 33 m keras metrics iou num_classes 2 target_class_ids 0 m update_state 0 0 1 1 0 1 0 1 m result 0 33333334 m reset_state m update_state 0 0 1 1 0 1 0 1 sample_weight 0 3 0 3 0 3 0 1 cm 0 3 0 3 0 3 0 1 sum_row 0 6 0 4 sum_col 0 6 0 4 true_positives 0 3 0 1 iou 0 33 0 14 m result 0 33333334 usage with compile api python model compile optimizer sgd loss mse metrics keras metrics iou num_classes 2 target_class_ids 0 compute the intersection over union via the confusion matrix sum_over_row sum_over_col 2 true_positives false_positives false_negatives only keep the target classes if the denominator is 0 we need to ignore the class computes the intersection over union metric for class 0 and or 1 formula python iou true_positives true_positives false_positives false_negatives intersection over union is a common evaluation metric for semantic image segmentation to compute ious the predictions are accumulated in a confusion matrix weighted by sample_weight and the metric is then calculated from it if sample_weight is none weights default to 1 use sample_weight of 0 to mask values this class can be used to compute ious for a binary classification task where the predictions are provided as logits first a threshold is applied to the predicted values such that those that are below the threshold are converted to class 0 and those that are above the threshold are converted to class 1 ious for classes 0 and 1 are then computed the mean of ious for the classes that are specified by target_class_ids is returned note with threshold 0 this metric has the same behavior as iou args target_class_ids a tuple or list of target class ids for which the metric is returned options are 0 1 or 0 1 with 0 or 1 the iou metric for class 0 or class 1 respectively is returned with 0 1 the mean of ious for the two classes is returned threshold a threshold that applies to the prediction logits to convert them to either predicted class 0 if the logit is below threshold or predicted class 1 if the logit is above threshold name optional string name of the metric instance dtype optional data type of the metric result examples standalone usage m keras metrics binaryiou target_class_ids 0 1 threshold 0 3 m update_state 0 1 0 1 0 1 0 2 0 4 0 7 m result 0 33333334 m reset_state m update_state 0 1 0 1 0 1 0 2 0 4 0 7 sample_weight 0 2 0 3 0 4 0 1 cm 0 2 0 4 0 3 0 1 sum_row 0 6 0 4 sum_col 0 5 0 5 true_positives 0 2 0 1 iou 0 222 0 125 m result 0 17361112 usage with compile api python model compile optimizer sgd loss mse metrics keras metrics binaryiou target_class_ids 0 threshold 0 5 accumulates the confusion matrix statistics before the confusion matrix is updated the predicted values are thresholded to be 0 for values that are smaller than the threshold 1 for values that are larger or equal to the threshold args y_true the ground truth values y_pred the predicted values sample_weight optional weighting of each example can be a tensor whose rank is either 0 or the same as y_true and must be broadcastable to y_true defaults to 1 returns update op computes the mean intersection over union metric formula python iou true_positives true_positives false_positives false_negatives intersection over union is a common evaluation metric for semantic image segmentation to compute ious the predictions are accumulated in a confusion matrix weighted by sample_weight and the metric is then calculated from it if sample_weight is none weights default to 1 use sample_weight of 0 to mask values note that this class first computes ious for all individual classes then returns the mean of these values args num_classes the possible number of labels the prediction task can have this value must be provided since a confusion matrix of dimension num_classes num_classes will be allocated name optional string name of the metric instance dtype optional data type of the metric result ignore_class optional integer the id of a class to be ignored during metric computation this is useful for example in segmentation problems featuring a void class commonly 1 or 255 in segmentation maps by default ignore_class none all classes are considered sparse_y_true whether labels are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label sparse_y_pred whether predictions are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label axis optional the dimension containing the logits defaults to 1 examples standalone usage cm 1 1 1 1 sum_row 2 2 sum_col 2 2 true_positives 1 1 iou true_positives sum_row sum_col true_positives result 1 2 2 1 1 2 2 1 2 0 33 m keras metrics meaniou num_classes 2 m update_state 0 0 1 1 0 1 0 1 m result 0 33333334 m reset_state m update_state 0 0 1 1 0 1 0 1 sample_weight 0 3 0 3 0 3 0 1 m result numpy 0 23809525 usage with compile api python model compile optimizer sgd loss mse metrics keras metrics meaniou num_classes 2 computes the intersection over union metric for one hot encoded labels formula python iou true_positives true_positives false_positives false_negatives intersection over union is a common evaluation metric for semantic image segmentation to compute ious the predictions are accumulated in a confusion matrix weighted by sample_weight and the metric is then calculated from it if sample_weight is none weights default to 1 use sample_weight of 0 to mask values this class can be used to compute iou for multi class classification tasks where the labels are one hot encoded the last axis should have one dimension per class note that the predictions should also have the same shape to compute the iou first the labels and predictions are converted back into integer format by taking the argmax over the class axis then the same computation steps as for the base iou class apply note if there is only one channel in the labels and predictions this class is the same as class iou in this case use iou instead also make sure that num_classes is equal to the number of classes in the data to avoid a labels out of bound error when the confusion matrix is computed args num_classes the possible number of labels the prediction task can have target_class_ids a tuple or list of target class ids for which the metric is returned to compute iou for a specific class a list or tuple of a single id value should be provided name optional string name of the metric instance dtype optional data type of the metric result ignore_class optional integer the id of a class to be ignored during metric computation this is useful for example in segmentation problems featuring a void class commonly 1 or 255 in segmentation maps by default ignore_class none all classes are considered sparse_y_pred whether predictions are encoded using integers or dense floating point vectors if false the argmax function is used to determine each sample s most likely associated label axis optional the dimension containing the logits defaults to 1 examples standalone usage y_true np array 0 0 1 1 0 0 0 1 0 1 0 0 y_pred np array 0 2 0 3 0 5 0 1 0 2 0 7 0 5 0 3 0 1 0 1 0 4 0 5 sample_weight 0 1 0 2 0 3 0 4 m keras metrics onehotiou num_classes 3 target_class_ids 0 2 m update_state y_true y_true y_pred y_pred sample_weight sample_weight cm 0 0 0 2 0 4 0 3 0 0 0 0 0 1 sum_row 0 3 0 0 7 sum_col 0 6 0 3 0 1 true_positives 0 0 0 1 single_iou true_positives sum_row sum_col true_positives mean_iou 0 0 3 0 6 0 0 1 0 7 0 1 0 1 2 m result 0 071 usage with compile api python model compile optimizer sgd loss mse metrics keras metrics onehotiou num_classes 3 target_class_id 1 computes mean intersection over union metric for one hot encoded labels formula python iou true_positives true_positives false_positives false_negatives intersection over union is a common evaluation metric for semantic image segmentation to compute ious the predictions are accumulated in a confusion matrix weighted by sample_weight and the metric is then calculated from it if sample_weight is none weights default to 1 use sample_weight of 0 to mask values this class can be used to compute the mean iou for multi class classification tasks where the labels are one hot encoded the last axis should have one dimension per class note that the predictions should also have the same shape to compute the mean iou first the labels and predictions are converted back into integer format by taking the argmax over the class axis then the same computation steps as for the base meaniou class apply note if there is only one channel in the labels and predictions this class is the same as class meaniou in this case use meaniou instead also make sure that num_classes is equal to the number of classes in the data to avoid a labels out of bound error when the confusion matrix is computed args num_classes the possible number of labels the prediction task can have name optional string name of the metric instance dtype optional data type of the metric result ignore_class optional integer the id of a class to be ignored during metric computation this is useful for example in segmentation problems featuring a void class commonly 1 or 255 in segmentation maps by default ignore_class none all classes are considered sparse_y_pred whether predictions are encoded using natural numbers or probability distribution vectors if false the argmax function will be used to determine each sample s most likely associated label axis optional the dimension containing the logits defaults to 1 examples standalone usage y_true np array 0 0 1 1 0 0 0 1 0 1 0 0 y_pred np array 0 2 0 3 0 5 0 1 0 2 0 7 0 5 0 3 0 1 0 1 0 4 0 5 sample_weight 0 1 0 2 0 3 0 4 m keras metrics onehotmeaniou num_classes 3 m update_state y_true y_true y_pred y_pred sample_weight sample_weight cm 0 0 0 2 0 4 0 3 0 0 0 0 0 1 sum_row 0 3 0 0 7 sum_col 0 6 0 3 0 1 true_positives 0 0 0 1 single_iou true_positives sum_row sum_col true_positives mean_iou 0 0 0 1 0 7 0 1 0 1 3 m result 0 048 usage with compile api python model compile optimizer sgd loss mse metrics keras metrics onehotmeaniou num_classes 3
from keras import backend
from keras import initializers
from keras import ops
from keras.api_export import keras_export
from keras.metrics.metric import Metric
from keras.metrics.metrics_utils import confusion_matrix


class _IoUBase(Metric):
    

    def __init__(
        self,
        num_classes,
        name=None,
        dtype=None,
        ignore_class=None,
        sparse_y_true=True,
        sparse_y_pred=True,
        axis=-1,
    ):
        
        super().__init__(name=name, dtype=dtype or "float32")
        
        self._direction = "up"
        self.num_classes = num_classes
        self.ignore_class = ignore_class
        self.sparse_y_true = sparse_y_true
        self.sparse_y_pred = sparse_y_pred
        self.axis = axis

        self.total_cm = self.add_variable(
            name="total_confusion_matrix",
            shape=(num_classes, num_classes),
            initializer=initializers.Zeros(),
        )

    def update_state(self, y_true, y_pred, sample_weight=None):
        

        if not self.sparse_y_true:
            y_true = ops.argmax(y_true, axis=self.axis)
        if not self.sparse_y_pred:
            y_pred = ops.argmax(y_pred, axis=self.axis)

        y_true = ops.convert_to_tensor(y_true, dtype=self.dtype)
        y_pred = ops.convert_to_tensor(y_pred, dtype=self.dtype)

        
        if len(y_pred.shape) > 1:
            y_pred = ops.reshape(y_pred, [-1])

        if len(y_true.shape) > 1:
            y_true = ops.reshape(y_true, [-1])

        if sample_weight is None:
            sample_weight = 1

        sample_weight = ops.convert_to_tensor(sample_weight, dtype=self.dtype)

        if len(sample_weight.shape) > 1:
            sample_weight = ops.reshape(sample_weight, [-1])

        sample_weight = ops.broadcast_to(sample_weight, ops.shape(y_true))

        if self.ignore_class is not None:
            ignore_class = ops.convert_to_tensor(
                self.ignore_class, y_true.dtype
            )
            valid_mask = ops.not_equal(y_true, ignore_class)
            y_true = y_true[valid_mask]
            y_pred = y_pred[valid_mask]
            if sample_weight is not None:
                sample_weight = sample_weight[valid_mask]

        y_pred = ops.cast(y_pred, dtype=self.dtype)
        y_true = ops.cast(y_true, dtype=self.dtype)
        sample_weight = ops.cast(sample_weight, dtype=self.dtype)

        current_cm = confusion_matrix(
            y_true,
            y_pred,
            self.num_classes,
            weights=sample_weight,
            dtype="float32",
        )

        return self.total_cm.assign(self.total_cm + current_cm)

    def reset_state(self):
        self.total_cm.assign(
            ops.zeros(self.total_cm.shape, dtype=self.total_cm.dtype)
        )


@keras_export("keras.metrics.IoU")
class IoU(_IoUBase):
    

    def __init__(
        self,
        num_classes,
        target_class_ids,
        name=None,
        dtype=None,
        ignore_class=None,
        sparse_y_true=True,
        sparse_y_pred=True,
        axis=-1,
    ):
        super().__init__(
            name=name,
            num_classes=num_classes,
            ignore_class=ignore_class,
            sparse_y_true=sparse_y_true,
            sparse_y_pred=sparse_y_pred,
            axis=axis,
            dtype=dtype,
        )
        if max(target_class_ids) >= num_classes:
            raise ValueError(
                f"Target class id {max(target_class_ids)} "
                "is out of range, which is "
                f"[{0}, {num_classes})."
            )
        self.target_class_ids = list(target_class_ids)

    def result(self):
        
        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)

        
        
        denominator = sum_over_row + sum_over_col - true_positives

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

        
        true_positives = ops.take_along_axis(
            true_positives, target_class_ids, axis=-1
        )
        denominator = ops.take_along_axis(
            denominator, target_class_ids, axis=-1
        )

        
        num_valid_entries = ops.sum(
            ops.cast(ops.greater(denominator, 1e-9), dtype=self.dtype)
        )

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

        return ops.divide(
            ops.sum(iou, axis=self.axis), num_valid_entries + backend.epsilon()
        )

    def get_config(self):
        config = {
            "num_classes": self.num_classes,
            "target_class_ids": self.target_class_ids,
            "ignore_class": self.ignore_class,
            "sparse_y_true": self.sparse_y_true,
            "sparse_y_pred": self.sparse_y_pred,
            "axis": self.axis,
        }
        base_config = super().get_config()
        return dict(list(base_config.items()) + list(config.items()))


@keras_export("keras.metrics.BinaryIoU")
class BinaryIoU(IoU):
    

    def __init__(
        self,
        target_class_ids=(0, 1),
        threshold=0.5,
        name=None,
        dtype=None,
    ):
        super().__init__(
            num_classes=2,
            target_class_ids=target_class_ids,
            name=name,
            dtype=dtype,
        )
        self.threshold = threshold

    def update_state(self, y_true, y_pred, sample_weight=None):
        
        y_true = ops.convert_to_tensor(y_true, dtype=self.dtype)
        y_pred = ops.convert_to_tensor(y_pred, dtype=self.dtype)
        y_pred = ops.cast(y_pred >= self.threshold, self.dtype)
        return super().update_state(y_true, y_pred, sample_weight)

    def get_config(self):
        return {
            "target_class_ids": self.target_class_ids,
            "threshold": self.threshold,
            "name": self.name,
            "dtype": self._dtype,
        }


@keras_export("keras.metrics.MeanIoU")
class MeanIoU(IoU):
    

    def __init__(
        self,
        num_classes,
        name=None,
        dtype=None,
        ignore_class=None,
        sparse_y_true=True,
        sparse_y_pred=True,
        axis=-1,
    ):
        target_class_ids = list(range(num_classes))
        super().__init__(
            name=name,
            num_classes=num_classes,
            target_class_ids=target_class_ids,
            axis=axis,
            dtype=dtype,
            ignore_class=ignore_class,
            sparse_y_true=sparse_y_true,
            sparse_y_pred=sparse_y_pred,
        )

    def get_config(self):
        return {
            "num_classes": self.num_classes,
            "name": self.name,
            "dtype": self._dtype,
            "ignore_class": self.ignore_class,
            "sparse_y_true": self.sparse_y_true,
            "sparse_y_pred": self.sparse_y_pred,
            "axis": self.axis,
        }


@keras_export("keras.metrics.OneHotIoU")
class OneHotIoU(IoU):
    

    def __init__(
        self,
        num_classes,
        target_class_ids,
        name=None,
        dtype=None,
        ignore_class=None,
        sparse_y_pred=False,
        axis=-1,
    ):
        super().__init__(
            num_classes=num_classes,
            target_class_ids=target_class_ids,
            name=name,
            dtype=dtype,
            ignore_class=ignore_class,
            sparse_y_true=False,
            sparse_y_pred=sparse_y_pred,
            axis=axis,
        )

    def get_config(self):
        return {
            "num_classes": self.num_classes,
            "target_class_ids": self.target_class_ids,
            "name": self.name,
            "dtype": self._dtype,
            "ignore_class": self.ignore_class,
            "sparse_y_pred": self.sparse_y_pred,
            "axis": self.axis,
        }


@keras_export("keras.metrics.OneHotMeanIoU")
class OneHotMeanIoU(MeanIoU):
    

    def __init__(
        self,
        num_classes,
        name=None,
        dtype=None,
        ignore_class=None,
        sparse_y_pred=False,
        axis=-1,
    ):
        super().__init__(
            num_classes=num_classes,
            axis=axis,
            name=name,
            dtype=dtype,
            ignore_class=ignore_class,
            sparse_y_true=False,
            sparse_y_pred=sparse_y_pred,
        )

    def get_config(self):
        return {
            "num_classes": self.num_classes,
            "name": self.name,
            "dtype": self._dtype,
            "ignore_class": self.ignore_class,
            "sparse_y_pred": self.sparse_y_pred,
            "axis": self.axis,
        }