【tensorflow】tf.nn.top_k()和tf.nn.in_top_k()——解析

 

一、tf.nn.top_k()使用方法

tf.nn.top_k(input, k, name=None)

解释:这个函数的作用是返回input中每行最大的k个数,并且返回它们所在位置的索引。

代码释义:

import tensorflow as tf
import numpy as np
 
input = tf.constant(np.random.rand(3,4))
k = 2
output = tf.nn.top_k(input, k)
with tf.Session() as sess:
    print(sess.run(input))
    print(sess.run(output))

运行结果:

[[ 0.98925872  0.15743092  0.76471106  0.5949957 ]
 [ 0.95766488  0.67846336  0.21058844  0.2644312 ]
 [ 0.65531991  0.61445187  0.65372938  0.88111084]]
TopKV2(values=array([[ 0.98925872,  0.76471106],
       [ 0.95766488,  0.67846336],
       [ 0.88111084,  0.65531991]]), indices=array([[0, 2],
       [0, 1],
       [3, 0]]))

输入参数:

  • input: 一个张量,数据类型必须是以下之一:float32、float64、int32、int64、uint8、int16、int8。数据维度是 batch_size 乘上 x 个类别。
  • k: 一个整型,必须 >= 1。在每行中,查找最大的 k 个值。
  • name: 为这个操作取个名字

输出参数:

一个元组 Tensor ,数据元素是 (values, indices),具体如下:

  • values: 一个张量,数据类型和 input 相同。数据维度是 batch_size 乘上 k 个最大值。

  • indices: 一个张量,数据类型是 int32 。每个最大值在 input 中的索引位置。

二、tf.nn.in_top_k()使用方法

tf.nn.in_top_k(predictions, targets, k, name=None)

解释:这个函数的作用是返回一个布尔向量,说明目标值是否存在于预测值之中。

输出数据是一个 targets 长度的布尔向量,如果目标值存在于预测值之中,那么 out[i] = true。

注意:targets 是predictions中的索引位,并不是 predictions 中具体的值。

代码:

import tensorflow as tf
import numpy as np
 
input = tf.constant(np.random.rand(3,4), tf.float32)
k = 2   #targets对应的索引是否在最大的前k(2)个数据中
output = tf.nn.in_top_k(input, [3,3,3], k)
with tf.Session() as sess:
    print(sess.run(input))
    print(sess.run(output))
[[ 0.43401602  0.29302254  0.40603295  0.21894781]
 [ 0.77089119  0.95353228  0.04788217  0.37489092]
 [ 0.83710146  0.2505011   0.28791779  0.97788286]]
[False False  True]

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值