使用tf.nn.sigmoid()后如何得到多标签输出

How to get multi-label output after using tf.nn.sigmoid()

用途:

我想在tensorflow-serving中预测时直接获取label name,我的问题是如何将pred = tf.nn.sigmoid(last_layer_output)转为真实的label name?

问题描述:

我知道如何处理 multi-类 问题:

CLASSES = tf.constant(['a', 'b', 'c', 'd', 'e'])

pred = tf.nn.softmax(last_layer_output)

# pred pretty similar to:
pred = [[0, 1, 0, 0, 0],
        [0, 0, 0, 1, 0],
        [0, 0, 0, 0, 1]]

classes_value = tf.argmax(pred, 1)
classes_name = tf.gather(CLASSES, classes_value)
# classes_name: [b'b' b'd' b'e']
# batch_size = 3

所以classes_name是我想要的,我可以在tensorflow-serving中使用它设计签名,当我预测时,我可以获得最终标签。

但是在多标签问题中如何做到这一点?

例如

CLASSES = tf.constant(['a', 'b', 'c', 'd', 'e'])

pred = tf.nn.sigmoid(last_layer_output)
pred = tf.round(pred)

# pred pretty similar to:
pred = [[0, 1, 1, 0, 1],     # 'b','c','e'
        [1, 0, 0, 1, 0],     # 'a','d'
        [1, 1, 1, 0, 1]]     # 'a','b','c','e'

如何将 pred 转移到标签名称?我不能在 sees.run() 之后或使用其他 api 像 numpy 那样做,因为这是针对 tensorflow-serving 的,我想我需要使用 tf 方法来做。

如有任何建议,我们将不胜感激!

您应该首先定义许多 classes 的给定概率,您想要 classes return。例如,如果此 class 的概率高于 0.5.

然后你可以在适当的条件下使用 tf.where 来获取索引,然后使用相同的 tf.gather 来获取 classes.

像这样:

indicies = tf.where(tf.greater(pred, 0.5))
classes = tf.gather(CLASSES, indicies[:, 1])

然后您需要使用 indicies[:, 0] 重新组织它,告诉您 class 来自哪个示例。

此外,您必须了解答案的正确形式是 SparseTensor,服务等不太支持它。因此您可能需要 return 两个张量 [strings 和 indicators which strings are for which example] 并在您的客户端处理。