Created
August 27, 2020 09:46
-
-
Save digital-thinking/4da96060366e714a2f861b79080cebfa to your computer and use it in GitHub Desktop.
Keras Layer to map raw indices to labels and only outputing the top n predictions (tensorflow 2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MappingLayer(tf.keras.layers.Layer): | |
""" | |
Converts probability outputs to TopN predictions applying a label mapping from indices to ids | |
""" | |
def __init__(self, mapping, topN): | |
super(MappingLayer, self).__init__() | |
initializer = tf.lookup.KeyValueTensorInitializer( | |
keys=tf.range(len(mapping)), | |
values=tf.constant(mapping, tf.int32), | |
key_dtype=tf.int32, | |
value_dtype=tf.int32) | |
self.table = tf.lookup.StaticHashTable(initializer, default_value=-1) | |
self.topN = topN | |
def call(self, input, **kwargs): | |
probas, indices = tf.math.top_k( | |
input, k=self.topN, sorted=True, name='mapped_out' | |
) | |
mapped = self.table.lookup(indices) | |
return [probas, mapped] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment