|
| 1 | +from __future__ import absolute_import, division, print_function |
| 2 | + |
| 3 | +import collections |
| 4 | + |
| 5 | +import tensorflow as tf |
| 6 | +from tensorflow.python.ops import lookup_ops |
| 7 | + |
| 8 | + |
| 9 | +class IndexLookup(tf.keras.layers.Layer): |
| 10 | + """Maps strings to integer indices by looking up a vocabulary. |
| 11 | +
|
| 12 | + This layer transforms categorical inputs to zero-based integer by |
| 13 | + lookuping with a vocabulary list. TensorFlow 2.2 has developed |
| 14 | + `tf.keras.layers.preprocessing.IndexLookup` but not released it yet. |
| 15 | + So the layer is a simple temporary version. The codes in TensorFlow 2.2 is |
| 16 | + `tensorflow.python.keras.layers.preprocessing.index_lookup.IndexLookup`. |
| 17 | +
|
| 18 | + Note that the TensorFlow version with the layer must be greater than 2.0.0. |
| 19 | +
|
| 20 | + Example: |
| 21 | + ```python |
| 22 | + layer = IndexLookup(vocabulary=['A', 'B', 'C']) |
| 23 | + inp = np.array([['A'], ['B'], ['C'], ['D'], ['E']]) |
| 24 | + layer(inputs) |
| 25 | + ``` |
| 26 | + Then output will be `[[0], [1], [2], [3], [3]]` |
| 27 | +
|
| 28 | + Attributes: |
| 29 | + num_oov_tokens: The number of out-of-vocabulary tokens to use; defaults to |
| 30 | + 1. If this value is more than 1, |
| 31 | + `hash(inputs) % num_oov_tokens + len(vocabulary)` converts OOV inputs |
| 32 | + to integer values. |
| 33 | + vocabulary: A list of vocabulary terms, or a path to a text file |
| 34 | + containing a vocabulary to load into this layer. The file should |
| 35 | + contain one token per line. |
| 36 | +
|
| 37 | + Input: A string `tf.Tensor`,`tf.SparseTensor` or |
| 38 | + `tf.RaggedTensor`. |
| 39 | +
|
| 40 | + Output: An int64 tensor with the same type as input. |
| 41 | +
|
| 42 | + """ |
| 43 | + |
| 44 | + def __init__(self, vocabulary=None, num_oov_tokens=1, **kwargs): |
| 45 | + super(IndexLookup, self).__init__() |
| 46 | + self.num_oov_tokens = num_oov_tokens |
| 47 | + |
| 48 | + if vocabulary is not None and isinstance(vocabulary, str): |
| 49 | + vocabulary = self._get_vocabulary_from_file(vocabulary) |
| 50 | + vocabulary_set = set(vocabulary) |
| 51 | + if len(vocabulary) != len(vocabulary_set): |
| 52 | + repeated_items = [ |
| 53 | + item |
| 54 | + for item, count in collections.Counter(vocabulary).items() |
| 55 | + if count > 1 |
| 56 | + ] |
| 57 | + raise ValueError( |
| 58 | + "The passed vocabulary has at least one repeated " |
| 59 | + "term. Please uniquify your dataset before passing " |
| 60 | + "it to IndexLookup(). The repeated terms are %s" |
| 61 | + % repeated_items |
| 62 | + ) |
| 63 | + self.vocabulary = vocabulary |
| 64 | + |
| 65 | + def build(self, input_shape): |
| 66 | + self.table = lookup_ops.index_table_from_tensor( |
| 67 | + vocabulary_list=self.vocabulary, |
| 68 | + num_oov_buckets=self.num_oov_tokens, |
| 69 | + ) |
| 70 | + |
| 71 | + def call(self, inputs): |
| 72 | + if isinstance(inputs, tf.SparseTensor): |
| 73 | + lookup_id = self.table.lookup(inputs.values) |
| 74 | + output = tf.SparseTensor( |
| 75 | + indices=inputs.indices, |
| 76 | + values=lookup_id, |
| 77 | + dense_shape=inputs.dense_shape, |
| 78 | + ) |
| 79 | + elif isinstance(inputs, tf.RaggedTensor): |
| 80 | + return tf.ragged.map_flat_values(self.table.lookup, inputs,) |
| 81 | + else: |
| 82 | + output = self.table.lookup(inputs) |
| 83 | + return tf.cast(output, tf.int64) |
| 84 | + |
| 85 | + def _get_vocabulary_from_file(self, vocabulary_path): |
| 86 | + vocab = [] |
| 87 | + with tf.io.gfile.GFile(vocabulary_path, "r") as reader: |
| 88 | + while True: |
| 89 | + # Get the next line, and break if it is None. |
| 90 | + text = reader.readline() |
| 91 | + if not text: |
| 92 | + break |
| 93 | + |
| 94 | + # Convert the raw text into UTF8 and strip whitespace. |
| 95 | + if isinstance(text, str): |
| 96 | + token = text |
| 97 | + elif isinstance(text, bytes): |
| 98 | + token = text.decode("utf-8", "ignore") |
| 99 | + token = token.strip() |
| 100 | + vocab.append(token) |
| 101 | + return vocab |
| 102 | + |
| 103 | + def vocab_size(self): |
| 104 | + return self._table.size().numpy() |
| 105 | + |
| 106 | + def compute_output_shape(self, input_shape): |
| 107 | + return input_shape |
| 108 | + |
| 109 | + def get_config(self): |
| 110 | + config = { |
| 111 | + "num_oov_tokens": self.num_oov_tokens, |
| 112 | + "vocabulary": None, |
| 113 | + } |
| 114 | + base_config = super(IndexLookup, self).get_config() |
| 115 | + return dict(list(base_config.items()) + list(config.items())) |
0 commit comments