Thursday, October 23, 2025
HomeLanguagesJavascriptTensorflow.js tf.topk() Function

Tensorflow.js tf.topk() Function

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.

The tf.topk() function along with the last dimension is also used in finding the values and indices of the k largest entries.

Syntax:

tf.topk (x, k?, sorted?)

Parameters:

  • x: 1-D or higher tf.Tensor with last dimension being at least k.
  • k: It is the number of elements to look for.
  • sorted: It is the boolean value. If it is true, then the resulting k elements will be sorted by the values in descending order.

Return Value: {values: tf.Tensor, indices: tf.Tensor}. It returns an object with two tensors containing the values and indices.

Example 1:

Javascript




const tf = require("@tensorflow/tfjs")
  
// Creating a 2d tensor
const a = tf.tensor2d([[1, 20, 3], [4, 3, 1], [8, 9, 10]]);
const {values, indices} = tf.topk(a);
  
// Printing the values and indices
values.print();
indices.print();


Output:

Tensor
    [[20],
     [4 ],
     [10]]
Tensor
    [[1],
     [0],
     [2]]

Example 2: In this example, we will provide the argument k, to get the largest k entries.

Javascript




const tf = require("@tensorflow/tfjs")
  
// Creating a 2d tensor
const a = tf.tensor2d([[1, 20, 3], [4, 3, 1], [8, 9, 10]]);
const {values, indices} = tf.topk(a, 3);
  
// Printing the values and indices
values.print();
indices.print();


Output:

As we have passed k = 3, we get 3 largest values in our result.

Tensor
    [[20, 3, 1],
     [4 , 3, 1],
     [10, 9, 8]]
Tensor
    [[1, 2, 0],
     [0, 1, 2],
     [2, 1, 0]]

Reference: https://js.tensorflow.org/api/latest/#topk

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS