tensorflow的top操作

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

解釋:這個(gè)函數(shù)的作用是返回 input 中每行最大的 k 個(gè)數(shù),并且返回它們所在位置的索引。

#!/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]]))

輸入?yún)?shù):

  • input: 一個(gè)張量,數(shù)據(jù)類型必須是以下之一:float32、float64、int32、int64、uint8、int16、int8。數(shù)據(jù)維度是 batch_size 乘上 x 個(gè)類別。
  • k: 一個(gè)整型,必須 >= 1。在每行中,查找最大的 k 個(gè)值。
  • name: 為這個(gè)操作取個(gè)名字。

輸出參數(shù):

一個(gè)元組 Tensor ,數(shù)據(jù)元素是 (values, indices),具體如下:

  • values: 一個(gè)張量,數(shù)據(jù)類型和 input 相同。數(shù)據(jù)維度是 batch_size 乘上 k 個(gè)最大值。

  • indices: 一個(gè)張量,數(shù)據(jù)類型是 int32 。每個(gè)最大值在 input 中的索引位置。

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

解釋:這個(gè)函數(shù)的作用是返回一個(gè)布爾向量,說明目標(biāo)值是否存在于預(yù)測值之中。

輸出數(shù)據(jù)是一個(gè) targets 長度的布爾向量,如果目標(biāo)值存在于預(yù)測值之中,那么 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對(duì)應(yīng)的索引是否在最大的前k(2)個(gè)數(shù)據(jù)中
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]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容