分享

tensorflow的top操作

 Harper666 2017-05-26

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

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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(predictions, targets, k, name=None)

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

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

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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]
转载自:http://www.jianshu.com/p/343c2eaacd18

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多