Python ``tensorflow.math.top_k()`` 取前 K 大值函数与实例


发布日期 : 2020-05-13 07:56:55 UTC

访问量: 10 次浏览

Python – tensorflow.math.top\_k()

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

top\_k()用于查找最后一个维度的前k个最大条目(对于矩阵来说,沿着每一行)。

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

参数 :

  • input: 它是具有1个或多个维度的输入张量。
  • k(可选): 它是0-D张量,默认值为0。
  • sorted(可选): 如果它被设置为真,返回的元素将被排序。默认为True。
  • name(可选): 它定义了该操作的名称。

返回值:

  • value:沿每个最后维度切片的k个最大元素。
  • indices:输入的最后一个维度内的值的索引。

示例 1:

# 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)

输出:

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)>)

示例 2:

# 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)

输出:

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)>)