Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Python – tensorflow.math.top_k()

  • Last Updated : 16 Jun, 2020

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

top_k()  is used to find top k largest entries for the last dimension(along each row for matrices).

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Syntax:  tensorflow.math.top_k(input, k, sorted, name)



Parameter:

  • input: It’s the input Tensor with 1 or more dimensions.
  • k(optional): It’s is 0-D tensor with default value 0.
  • sorted(optional): If it’s set to true returned elements will be sorted. Default is True.
  • name(optional): It defines the name for the operation.

Returns:

  • values:  k largest elements along each last dimensional slice.
  • indices: indices of values within the last dimension of input.

Example 1:

Python3




# importing the library
import tensorflow as tf
  
# Initializing the input tensor
a = tf.constant([7, 2, 3, 9, 5], dtype = tf.float64)
  
# Printing the input tensor
print('a: ', a)
  
# Calculating result
res = tf.math.top_k(a)
  
# Printing the result
print('Result: ', res)

Output:

a:  tf.Tensor([7. 2. 3. 9. 5.], shape=(5, ), dtype=float64)
Result:  TopKV2(values=<tf.Tensor: shape=(1, ), dtype=float64, numpy=array([9.])>, 
    indices=<tf.Tensor: shape=(1, ), dtype=int32, numpy=array([3], dtype=int32)>)
    
    
    

Example 2:

Python3




# importing the library
import tensorflow as tf
  
# Initializing the input tensor
a = tf.constant([[7, 2, 3], [ 9, 5, 7]], dtype = tf.float64)
  
# Printing the input tensor
print('a: ', a)
  
# Calculating result
res = tf.math.top_k(a, k = 2)
  
# Printing the result
print('Result: ', res)

Output:

a:  tf.Tensor(
[[7. 2. 3.]
 [9. 5. 7.]], shape=(2, 3), dtype=float64)
Result:  TopKV2(values=<tf.Tensor: shape=(2, 2), dtype=float64, numpy=
array([[7., 3.],
       [9., 7.]])>, indices=<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[0, 2],
       [0, 2]], dtype=int32)>)



My Personal Notes arrow_drop_up
Recommended Articles
Page :