<!--
{
  "availability" : [
    "iOS: 18.0.0 -",
    "iPadOS: 18.0.0 -",
    "macCatalyst: 18.0.0 -",
    "macOS: 15.0.0 -",
    "tvOS: 18.0.0 -",
    "visionOS: 2.0.0 -",
    "watchOS: 11.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "CoreML",
  "identifier" : "/documentation/CoreML/MLTensor/topK(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Core ML",
      "CoreML"
    ],
    "preciseIdentifier" : "s:6CoreML8MLTensorV4topKyAC6values_AC7indicestSiF"
  },
  "title" : "topK(_:)"
}
-->

# topK(_:)

Returns the *k* largest values along the last axis of the tensor.

```
func topK(_ k: Int) -> (values: MLTensor, indices: MLTensor)
```

## Parameters

`k`

The number of largest values to return.

## Return Value

A tuple of (values, indices) with values containing the top k values along the last axis and indices, a `Int32` tensor,
containing the indices to the corresponding values.

## Discussion> Note: The tensor must have at least k elements along its last axis and order returned by largest values which are
> equal is not deterministic.

For example:

```swift
let x = MLTensor(shape: [1, 5], scalars: [1.0, 2.0, 3.0, 4.0, 5.0])
let (values, indices) = x.topK(3)
// values = [[5.0, 4.0, 3.0]]
// indices = [[4, 3, 2]]
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)