| 2771 | |
| 2772 | @keras_export('keras.metrics.sparse_categorical_accuracy') |
| 2773 | def sparse_categorical_accuracy(y_true, y_pred): |
| 2774 | y_pred_rank = ops.convert_to_tensor(y_pred).shape.ndims |
| 2775 | y_true_rank = ops.convert_to_tensor(y_true).shape.ndims |
| 2776 | # If the shape of y_true is (num_samples, 1), squeeze to (num_samples,) |
| 2777 | if (y_true_rank is not None) and (y_pred_rank is not None) and (len( |
| 2778 | K.int_shape(y_true)) == len(K.int_shape(y_pred))): |
| 2779 | y_true = array_ops.squeeze(y_true, [-1]) |
| 2780 | y_pred = math_ops.argmax(y_pred, axis=-1) |
| 2781 | |
| 2782 | # If the predicted output and actual output types don't match, force cast them |
| 2783 | # to match. |
| 2784 | if K.dtype(y_pred) != K.dtype(y_true): |
| 2785 | y_pred = math_ops.cast(y_pred, K.dtype(y_true)) |
| 2786 | |
| 2787 | return math_ops.cast(math_ops.equal(y_true, y_pred), K.floatx()) |
| 2788 | |
| 2789 | |
| 2790 | @keras_export('keras.metrics.top_k_categorical_accuracy') |