如何检查一个张量的 argmax 是否等于另一个具有多个相等最大值的张量的任何 argmax?

How to check if the argmax of a tensor is equal to any argmax of another tensor which has several equal max?

所以通常在单标签分类中,我们使用如下

correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(self.label, 1))

但是我正在处理多标签分类,所以我想知道如何在标签向量中有多个标签的情况下进行分类。所以我到目前为止所拥有的是下面

 a = tf.constant([0.2, 0.4, 0.3, 0.1])
 b = tf.constant([0,1.0,1,0])
 empty_tensor = tf.zeros([0])
 for index in range(b.get_shape()[0]):
     empty_tensor = tf.cond(tf.equal(b[index],tf.constant(1, dtype = 
     tf.float32)), lambda:  tf.concat([empty_tensor,tf.constant([index], 
     dtype = tf.float32)], axis = 0), lambda: empty_tensor)

 temp, _ = tf.setdiff1d([tf.argmax(a)], tf.cast(empty_tensor, dtype= tf.int64))
 output, _ = tf.setdiff1d([tf.argmax(a)], tf.cast(temp, dtype = tf.int64))

所以这给了我 max(preds) 发生的索引以及 self.label 中有 1 的位置。在上面的示例中,它给出了 [1],如果 argmax 不匹配,那么我得到 [].

我遇到的问题是我不知道如何从那里开始,因为我想要类似下面的东西

correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(self.label, 1))
self.accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))

这对于单标签分类来说很简单。

非常感谢

我不认为你可以用 softmax 实现这个,所以我假设你正在使用 sigmoids 作为你的 preds。如果您使用的是 sigmoid,您的输出将分别(独立地)在 0 和 1 之间。您可以为每个定义一个阈值,也许是 0.5,然后将您的 sigmoid preds 转换为 label 编码( 0 和 1)通过 preds > 0.5.

如果预测为 [0 1] 且标签为 [1 1],您要将其报告为完全错误还是部分错误?我将假设前者。在这种情况下,您将删除 tf.argmax 调用,而是检查 predslabel 是否完全相同的向量,看起来像 tf.reduce_all(tf.equal(preds, label), axis=0)。对于后者,代码看起来像 tf.reduce_sum(tf.equal(preds, label), axis=0).