一、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]