<br />

<button value="stable" default="">See Stable</button> <button value="nightly">See Nightly</button>

<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/keras-team/keras/tree/v3.15.1/keras/src/ops/math.py#L251-L278) |

Finds the top-k values and their indices in a tensor.

```python
tf.keras.ops.top_k(
    x, k, sorted=True
)
```

<br />

<br />

<br />

| ## Args ||
|---|---|
| `x` | Input tensor. |
| `k` | An integer representing the number of top elements to retrieve. |
| `sorted` | A boolean indicating whether to sort the output in descending order. Defaults to `True`. |

<br />

<br />

<br />

<br />

| ## Returns ||
|---|---|
| A tuple containing two tensors. The first tensor contains the top-k values, and the second tensor contains the indices of the top-k values in the input tensor. ||

<br />

#### Example:

```python
x = keras.ops.convert_to_tensor([5, 2, 7, 1, 9, 3])
values, indices = top_k(x, k=3)
print(values)
array([9 7 5], shape=(3,), dtype=int32)
print(indices)
array([4 2 0], shape=(3,), dtype=int32)
```