tensorflow的top操作

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]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容