torch.Tensor.Tensor.kthvalue
Tensor.kthvalue<Dim extends number>(k: number, options: KthvalueOptions & { dim: Dim; keepdim?: false }): {
values: Tensor<DynamicShape, D, Dev>;
indices: Tensor<DynamicShape, 'int32', Dev>;
}Tensor.kthvalue(k: number, dimOrOptions?: number | KthvalueOptions, keepdimOrOptions?: boolean | KthvalueOptions, options?: KthvalueOptions): { values: Tensor<DynamicShape, D, Dev>; indices: Tensor<DynamicShape, 'int32', Dev> }Returns the k-th smallest element along a dimension and its position.
Finds the k-th smallest value (1-indexed: k=1 is minimum, k=size is maximum) and the index of where it occurs. More efficient than full sort when you only need one specific quantile. Returns both values and indices.
Use Cases:
- Finding specific quantiles/percentiles (k=size*0.25 for 25th percentile)
- Trimming outliers (k-th smallest and k-th largest bounds)
- Selecting median value (k=ceil(size/2))
- Finding thresholds in ranking/filtering algorithms
- Percentile-based statistics and quality metrics
- 1-indexed: k=1 is the minimum, k=size is the maximum (unlike 0-indexed arrays)
- Position-aware: Returns both value and its index location
- Dimension-specific: Finds k-th along specified dimension
- Efficient: Faster than full sort when k is small or close to size
- Keepdim support: keepdim=true enables broadcasting
- Bounds checking: k must be between 1 and dimension size
- 1-indexed k: Remember k is 1-indexed, not 0-indexed
- K must be valid: k 1 or k dimension_size throws error
- Equal values: Behavior is deterministic but may return any position for equal values
Parameters
knumber- Position to find (1-indexed: k=1 is minimum, k=size is maximum)
optionsKthvalueOptions & { dim: Dim; keepdim?: false }
Returns
{ values: Tensor<DynamicShape, D, Dev>; indices: Tensor<DynamicShape, 'int32', Dev>; }– Object with: - values: The k-th smallest value(s) - indices: Position(s) where the k-th value occursExamples
// Find minimum (k=1) and maximum (k=n)
const x = torch.tensor([5, 2, 8, 1, 9]);
const { values: min_val, indices: min_idx } = x.kthvalue(1); // 1 at index 3
const { values: max_val, indices: max_idx } = x.kthvalue(5); // 9 at index 4
// Find median (k = ceil(n/2))
const { values: median } = x.kthvalue(3); // 5
// Find quartiles for statistics
const data = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]);
const { values: q1 } = data.kthvalue(2, 1); // 25th percentile
const { values: q3 } = data.kthvalue(4, 1); // 75th percentile
// Trim outliers using k-th values
const dataset = torch.randn(1000, 100);
const { values: min_trim } = dataset.kthvalue(50, 1, true); // 5th percentile
const { values: max_trim } = dataset.kthvalue(950, 1, true); // 95th percentile
const trimmed = dataset.clamp(min_trim, max_trim);
// Keep dimensions for broadcasting
const x = torch.tensor([[1, 2, 3], [4, 5, 6]]);
const { values: v, indices: i } = x.kthvalue(2, 1, true); // [[2], [5]]