Skip to content

Instantly share code, notes, and snippets.

@digital-thinking
Created August 27, 2020 09:46
Show Gist options
  • Save digital-thinking/4da96060366e714a2f861b79080cebfa to your computer and use it in GitHub Desktop.
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)
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