TensorFlow in_top_k 评估输入参数

TensorFlow in_top_k evaluation input argumants

我正在按照 this link 中的教程进行操作,并尝试更改模型的评估方法(在底部)。我想获得前 5 名的评价,我正在尝试使用以下代码:

topFiver=tf.nn.in_top_k(y, y_, 5, name=None)

但是,这会产生以下错误:

File "AlexNet.py", line 111, in <module>
    topFiver = tf.nn.in_top_k(pred, y, 5, name=None)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 346, in in_top_k
    targets=targets, k=k, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 486, in apply_op
    _Attr(op_def, input_arg.type_attr))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 59, in _SatisfiesTypeConstraint
    ", ".join(dtypes.as_dtype(x).name for x in allowed_list)))
TypeError: DataType float32 for attr 'T' not in list of allowed values: int32, int64

据我所知,问题是 tf.nn.in_top_k() 仅适用于 tf.int32tf.int64 数据,但我的数据是 tf.float32 格式。有什么解决方法吗?

tf.nn.in_top_k(predictions, targets, k)targets 参数必须是 class 个 ID 的向量(即 predictions 矩阵中列的索引)。这意味着它仅适用于单class class化问题。

如果您的问题是单一 class 问题,那么我假设您的 y_ 张量是您示例的真实标签的单热编码(例如,因为您也通过像 tf.nn.softmax_cross_entropy_with_logits() 这样的操作。在这种情况下,您有两个选择:

  • 如果标签最初存储为整数标签,则将它们直接传递给 tf.nn.in_top_k(),而不将它们转换为 one-hot。 (另外,考虑使用 tf.nn.sparse_softmax_cross_entropy_with_logits() 作为你的损失函数,因为它可能更有效。)
  • 如果标签最初以单热格式存储,您可以使用 tf.argmax():

    将它们转换为整数
    labels = tf.argmax(y_, 1)
    topFiver = tf.nn.in_top_k(y, labels, 5)