View source on GitHub |
A preprocessing layer which maps integer features to contiguous ranges.
Inherits From: PreprocessingLayer
, Layer
, Module
tf.keras.layers.IntegerLookup(
max_tokens=None,
num_oov_indices=1,
mask_token=None,
oov_token=-1,
vocabulary=None,
vocabulary_dtype='int64',
idf_weights=None,
invert=False,
output_mode='int',
sparse=False,
pad_to_max_tokens=False,
**kwargs
)
This layer maps a set of arbitrary integer input tokens into indexed integer
output via a table-based vocabulary lookup. The layer's output indices will
be contiguously arranged up to the maximum vocab size, even if the input
tokens are non-continguous or unbounded. The layer supports multiple options
for encoding the output via output_mode
, and has optional support for
out-of-vocabulary (OOV) tokens and masking.
The vocabulary for the layer must be either supplied on construction or
learned via adapt()
. During adapt()
, the layer will analyze a data set,
determine the frequency of individual integer tokens, and create a
vocabulary from them. If the vocabulary is capped in size, the most frequent
tokens will be used to create the vocabulary and all others will be treated
as OOV.
There are two possible output modes for the layer. When output_mode
is
"int"
, input integers are converted to their index in the vocabulary (an
integer). When output_mode
is "multi_hot"
, "count"
, or "tf_idf"
,
input integers are encoded into an array where each dimension corresponds to
an element in the vocabulary.
The vocabulary can optionally contain a mask token as well as an OOV token
(which can optionally occupy multiple indices in the vocabulary, as set
by num_oov_indices
).
The position of these tokens in the vocabulary is fixed. When output_mode
is "int"
, the vocabulary will begin with the mask token at index 0,
followed by OOV indices, followed by the rest of the vocabulary. When
output_mode
is "multi_hot"
, "count"
, or "tf_idf"
the vocabulary will
begin with OOV indices and instances of the mask token will be dropped.
For an overview and full list of preprocessing layers, see the preprocessing guide.
Examples:
Creating a lookup layer with a known vocabulary
This example creates a lookup layer with a pre-existing vocabulary.
vocab = [12, 36, 1138, 42]
data = tf.constant([[12, 1138, 42], [42, 1000, 36]]) # Note OOV tokens
layer = tf.keras.layers.IntegerLookup(vocabulary=vocab)
layer(data)
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=
array([[1, 3, 4],
[4, 0, 2]])>
Creating a lookup layer with an adapted vocabulary
This example creates a lookup layer and generates the vocabulary by analyzing the dataset.
data = tf.constant([[12, 1138, 42], [42, 1000, 36]])
layer = tf.keras.layers.IntegerLookup()
layer.adapt(data)
layer.get_vocabulary()
[-1, 42, 1138, 1000, 36, 12]
Note that the OOV token -1 have been added to the vocabulary. The remaining tokens are sorted by frequency (42, which has 2 occurrences, is first) then by inverse sort order.
data = tf.constant([[12, 1138, 42], [42, 1000, 36]])
layer = tf.keras.layers.IntegerLookup()
layer.adapt(data)
layer(data)
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=
array([[5, 2, 1],
[1, 3, 4]])>
Lookups with multiple OOV indices
This example demonstrates how to use a lookup layer with multiple OOV indices. When a layer is created with more than one OOV index, any OOV tokens are hashed into the number of OOV buckets, distributing OOV tokens in a deterministic fashion across the set.
vocab = [12, 36, 1138, 42]
data = tf.constant([[12, 1138, 42], [37, 1000, 36]])
layer = tf.keras.layers.IntegerLookup(
vocabulary=vocab, num_oov_indices=2)
layer(data)
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=
array([[2, 4, 5],
[1, 0, 3]])>
Note that the output for OOV token 37 is 1, while the output for OOV token 1000 is 0. The in-vocab terms have their output index increased by 1 from earlier examples (12 maps to 2, etc) in order to make space for the extra OOV token.
One-hot output
Configure the layer with output_mode='one_hot'
. Note that the first
num_oov_indices
dimensions in the ont_hot encoding represent OOV values.
vocab = [12, 36, 1138, 42]
data = tf.constant([12, 36, 1138, 42, 7]) # Note OOV tokens
layer = tf.keras.layers.IntegerLookup(
vocabulary=vocab, output_mode='one_hot')
layer(data)
<tf.Tensor: shape=(5, 5), dtype=float32, numpy=
array([[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.],
[1., 0., 0., 0., 0.]], dtype=float32)>
Multi-hot output
Configure the layer with output_mode='multi_hot'
. Note that the first
num_oov_indices
dimensions in the multi_hot encoding represent OOV tokens
vocab = [12, 36, 1138, 42]
data = tf.constant([[12, 1138, 42, 42],
[42, 7, 36, 7]]) # Note OOV tokens
layer = tf.keras.layers.IntegerLookup(
vocabulary=vocab, output_mode='multi_hot')
layer(data)
<tf.Tensor: shape=(2, 5), dtype=float32, numpy=
array([[0., 1., 0., 1., 1.],
[1., 0., 1., 0., 1.]], dtype=float32)>
Token count output
Configure the layer with output_mode='count'
. As with multi_hot output,
the first num_oov_indices
dimensions in the output represent OOV tokens.
vocab = [12, 36, 1138, 42]
data = tf.constant([[12, 1138, 42, 42],
[42, 7, 36, 7]]) # Note OOV tokens
layer = tf.keras.layers.IntegerLookup(
vocabulary=vocab, output_mode='count')
layer(data)
<tf.Tensor: shape=(2, 5), dtype=float32, numpy=
array([[0., 1., 0., 1., 2.],
[2., 0., 1., 0., 1.]], dtype=float32)>
TF-IDF output
Configure the layer with output_mode='tf_idf'
. As with multi_hot output,
the first num_oov_indices
dimensions in the output represent OOV tokens.
Each token bin will output token_count * idf_weight
, where the idf weights
are the inverse document frequency weights per token. These should be
provided along with the vocabulary. Note that the idf_weight
for OOV
tokens will default to the average of all idf weights passed in.
vocab = [12, 36, 1138, 42]
idf_weights = [0.25, 0.75, 0.6, 0.4]
data = tf.constant([[12, 1138, 42, 42],
[42, 7, 36, 7]]) # Note OOV tokens
layer = tf.keras.layers.IntegerLookup(
output_mode='tf_idf', vocabulary=vocab, idf_weights=idf_weights)
layer(data)
<tf.Tensor: shape=(2, 5), dtype=float32, numpy=
array([[0. , 0.25, 0. , 0.6 , 0.8 ],
[1.0 , 0. , 0.75, 0. , 0.4 ]], dtype=float32)>
To specify the idf weights for oov tokens, you will need to pass the entire vocabularly including the leading oov token.
vocab = [-1, 12, 36, 1138, 42]
idf_weights = [0.9, 0.25, 0.75, 0.6, 0.4]
data = tf.constant([[12, 1138, 42, 42],
[42, 7, 36, 7]]) # Note OOV tokens
layer = tf.keras.layers.IntegerLookup(
output_mode='tf_idf', vocabulary=vocab, idf_weights=idf_weights)
layer(data)
<tf.Tensor: shape=(2, 5), dtype=float32, numpy=
array([[0. , 0.25, 0. , 0.6 , 0.8 ],
[1.8 , 0. , 0.75, 0. , 0.4 ]], dtype=float32)>
When adapting the layer in tf_idf mode, each input sample will be considered
a document, and idf weight per token will be calculated as
log(1 + num_documents / (1 + token_document_count))
.
Inverse lookup
This example demonstrates how to map indices to tokens using this layer.
(You can also use adapt()
with inverse=True
, but for simplicity we'll
pass the vocab in this example.)
vocab = [12, 36, 1138, 42]
data = tf.constant([[1, 3, 4], [4, 0, 2]])
layer = tf.keras.layers.IntegerLookup(vocabulary=vocab, invert=True)
layer(data)
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=
array([[ 12, 1138, 42],
[ 42, -1, 36]])>
Note that the first index correspond to the oov token by default.
Forward and inverse lookup pairs
This example demonstrates how to use the vocabulary of a standard lookup layer to create an inverse lookup layer.
vocab = [12, 36, 1138, 42]
data = tf.constant([[12, 1138, 42], [42, 1000, 36]])
layer = tf.keras.layers.IntegerLookup(vocabulary=vocab)
i_layer = tf.keras.layers.IntegerLookup(
vocabulary=layer.get_vocabulary(), invert=True)
int_data = layer(data)
i_layer(int_data)
<tf.Tensor: shape=(2, 3), dtype=int64, numpy=
array([[ 12, 1138, 42],
[ 42, -1, 36]])>
In this example, the input token 1000 resulted in an output of -1, since
1000 was not in the vocabulary - it got represented as an OOV, and all OOV
tokens are returned as -1 in the inverse layer. Also, note that for the
inverse to work, you must have already set the forward layer vocabulary
either directly or via adapt()
before calling get_vocabulary()
.
Attributes | |
---|---|
is_adapted
|
Whether the layer has been fit to data already. |
Methods
adapt
adapt(
data, batch_size=None, steps=None
)
Computes a vocabulary of interger terms from tokens in a dataset.
Calling adapt()
on an IntegerLookup
layer is an alternative to
passing in a precomputed vocabulary on construction via the
vocabulary
argument. An IntegerLookup
layer should always be either
adapted over a dataset or supplied with a vocabulary.
During adapt()
, the layer will build a vocabulary of all integer
tokens seen in the dataset, sorted by occurrence count, with ties broken
by sort order of the tokens (high to low). At the end of adapt()
, if
max_tokens
is set, the vocabulary wil be truncated to max_tokens
size. For example, adapting a layer with max_tokens=1000
will compute
the 1000 most frequent tokens occurring in the input dataset. If
output_mode='tf-idf'
, adapt()
will also learn the document
frequencies of each token in the input dataset.
In order to make StringLookup
efficient in any distribution context,
the vocabulary is kept static with respect to any compiled tf.Graph
s
that call the layer. As a consequence, if the layer is adapted a second
time, any models using the layer should be re-compiled. For more
information see
tf.keras.layers.experimental.preprocessing.PreprocessingLayer.adapt
.
adapt()
is meant only as a single machine utility to compute layer
state. To analyze a dataset that cannot fit on a single machine, see
Tensorflow Transform for a
multi-machine, map-reduce solution.
Arguments | |
---|---|
data
|
The data to train on. It can be passed either as a
tf.data.Dataset , or as a numpy array.
|
batch_size
|
Integer or None .
Number of samples per state update.
If unspecified, batch_size will default to 32.
Do not specify the batch_size if your data is in the
form of datasets, generators, or keras.utils.Sequence instances
(since they generate batches).
|
steps
|
Integer or None .
Total number of steps (batches of samples)
When training with input tensors such as
TensorFlow data tensors, the default None is equal to
the number of samples in your dataset divided by
the batch size, or 1 if that cannot be determined. If x is a
tf.data dataset, and 'steps' is None, the epoch will run until
the input dataset is exhausted. When passing an infinitely
repeating dataset, you must specify the steps argument. This
argument is not supported with array inputs.
|
compile
compile(
run_eagerly=None, steps_per_execution=None
)
Configures the layer for adapt
.
Arguments | |
---|---|
run_eagerly
|
Bool. Defaults to False . If True , this Model 's
logic will not be wrapped in a tf.function . Recommended to leave
this as None unless your Model cannot be run inside a
tf.function .
|
steps_per_execution
|
Int. Defaults to 1. The number of batches to run
during each tf.function call. Running multiple batches inside a
single tf.function call can greatly improve performance on TPUs or
small models with a large Python overhead.
|
get_vocabulary
get_vocabulary(
include_special_tokens=True
)
Returns the current vocabulary of the layer.
Args | |
---|---|
include_special_tokens
|
If True, the returned vocabulary will include mask and OOV tokens, and a term's index in the vocabulary will equal the term's index when calling the layer. If False, the returned vocabulary will not include any mask or OOV tokens. |
load_assets
load_assets(
dir_path
)
reset_state
reset_state()
Resets the statistics of the preprocessing layer.
save_assets
save_assets(
dir_path
)
set_vocabulary
set_vocabulary(
vocabulary, idf_weights=None
)
Sets vocabulary (and optionally document frequency) for this layer.
This method sets the vocabulary and idf weights for this layer directly,
instead of analyzing a dataset through adapt
. It should be used
whenever the vocab (and optionally document frequency) information is
already known. If vocabulary data is already present in the layer, this
method will replace it.
Args | |
---|---|
vocabulary
|
Either an array or a string path to a text file. If passing an array, can pass a tuple, list, 1D numpy array, or 1D tensor containing the vocbulary terms. If passing a file path, the file should contain one line per term in the vocabulary. |
idf_weights
|
A tuple, list, 1D numpy array, or 1D tensor of inverse
document frequency weights with equal length to vocabulary. Must be
set if output_mode is "tf_idf" . Should not be set otherwise.
|
Raises | |
---|---|
ValueError
|
If there are too many inputs, the inputs do not match, or input data is missing. |
RuntimeError
|
If the vocabulary cannot be set when this function is
called. This happens when "multi_hot" , "count" , and "tf_idf"
modes, if pad_to_max_tokens is False and the layer itself has
already been called.
|
RuntimeError
|
If a tensor vocabulary is passed outside of eager execution. |
update_state
update_state(
data
)
Accumulates statistics for the preprocessing layer.
Arguments | |
---|---|
data
|
A mini-batch of inputs to the layer. |
vocab_size
vocab_size()
vocabulary_size
vocabulary_size()
Gets the current size of the layer's vocabulary.
Returns | |
---|---|
The integer size of the vocabulary, including optional mask and oov indices. |