torch.kthvalue
function kthvalue<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>, k: number, options?: KthvalueOptions): { values: Tensor<S, D, Dev>; indices: Tensor<S, 'int32', Dev> }function kthvalue<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>, k: number, dim: number, keepdim: boolean, options?: KthvalueOptions): { values: Tensor<S, D, Dev>; indices: Tensor<S, 'int32', Dev> }Returns the k-th smallest element (by value) and its index along a dimension.
Finds the element that would be at position k if the tensor were sorted. Efficient single-value selection without computing full sort. Useful for:
- Percentile/quantile computation (IQR, quartiles)
- Median finding (k = n/2 for center element)
- Threshold selection in statistical tests
- Finding specific order statistics
- 1-indexed: k=1 is minimum, k=n is maximum (differs from 0-indexed conventions)
- Efficient: O(n) expected time vs O(n log n) for full sort
- Dimension semantics: -1 is last dimension; Python-style negative indexing
- k bounds: k must satisfy 1 ≤ k ≤ size(input, dim)
- For median: Use k = ceil(n/2) or (n+1)/2 depending on centering preference
- Gradients: Values support gradients; indices are discrete (no gradients)
Parameters
inputTensor<S, D, Dev>- Tensor to find k-th value in
knumber- Position of element to find (1-indexed: 1 = smallest, n = largest)
optionsKthvalueOptionsoptional- K-th value options: -
dim: Dimension to search along (default: -1, last dimension) -keepdim: Keep the reduced dimension with size 1 (default: false)
Returns
{ values: Tensor<S, D, Dev>; indices: Tensor<S, 'int32', Dev> }– Object with two tensors: - values: The k-th smallest value along dimension - indices: Index position where k-th value was foundExamples
// Find median (k-th value with k = ceil(n/2))
const data = torch.tensor([3, 1, 4, 1, 5, 9, 2, 6]);
const { values: median_val, indices: median_idx } = torch.kthvalue(data, 5);
// Sorted: [1, 1, 2, 3, 4, 5, 6, 9]
// 5th element is 4, at original position 2
// Find quartiles
const values = torch.randn(1000);
const q1 = torch.kthvalue(values, 250); // 25th percentile
const q3 = torch.kthvalue(values, 750); // 75th percentile
const iqr = q3.values.sub(q1.values); // Interquartile range
// Batched k-th value (e.g., finding percentiles per sample)
const batch = torch.randn(32, 100); // 32 samples, 100 values each
const medians = torch.kthvalue(batch, 50, { dim: 1 });
// medians.values: [32] - median of each sample
// medians.indices: [32] - position of median in each sample
// Find specific order statistics
const scores = torch.tensor([85.2, 92.1, 78.5, 92.1, 88.3]);
const third_best = torch.kthvalue(scores, 3, { dim: 0 }); // 3rd best score
// values: 85.2, indices: 0
// Robust statistics: use k-th value instead of mean for outlier-resistant average
const noisy_measurements = torch.randn(50); // Some outliers
const robust_middle = torch.kthvalue(noisy_measurements, 25);
// Less affected by extreme values than mean()