# tf.nn.in_top_k()-解析，以及不适用范围

1.in_top_k(predictions, targets, k, name=None)

Args:

predictions: 一种tf.float的张量。一个batch_size的x类张量预测值，one-hot编码,size为[batch_size,label类别数]

targets: 一个张量。必须是下列类型之一:int32, int64。size只有一维，也就意味着不能是one-hot编码的。理由举例就知道了

k：每个样本的预测结果的前k个最大的数里面是否包含targets预测中的标签，一般都是取1，即取预测最大概率的索引与标签对比。

name : 操作的名称(可选)。

import tensorflow as tf

logits = tf.Variable(tf.random_normal([10,5],mean=0.0,stddev=1.0,dtype=tf.float32))
labels = tf.constant([0,2,0,1,0,0,4,0,3,0])
top_1_op = tf.nn.in_top_k(logits,labels,1)
top_2_op = tf.nn.in_top_k(logits,labels,2)

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(logits.eval())
print(labels.eval())
print(top_1_op.eval())
print(top_2_op.eval())

import tensorflow as tf

logits = tf.Variable(tf.random_normal([10,5],mean=0.0,stddev=1.0,dtype=tf.float32))
labels = tf.constant([0,2,0,1,0,0,4,0,3,0])
n_classes = 5
labels = tf.one_hot(labels, depth=n_classes)
print(labels)
top_1_op = tf.nn.in_top_k(logits,labels,1)
top_2_op = tf.nn.in_top_k(logits,labels,2)

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(logits.eval())
print(labels.eval())
print(top_1_op.eval())
print(top_2_op.eval())

Tensor("one_hot:0", shape=(10, 5), dtype=float32)

TypeError: Value passed to parameter 'targets' has DataType float32 not in list of allowed values: int32, int64