tf.keras.layers.experimental.preprocessing.TextVectorization

View source on GitHub

Text vectorization layer.

tf.keras.layers.experimental.preprocessing.TextVectorization(
    max_tokens=None, standardize=LOWER_AND_STRIP_PUNCTUATION,
    split=SPLIT_ON_WHITESPACE, ngrams=None, output_mode=INT,
    output_sequence_length=None, pad_to_max_tokens=True, **kwargs
)

This layer has basic options for managing text in a Keras model. It transforms a batch of strings (one sample = one string) into either a list of token indices (one sample = 1D tensor of integer token indices) or a dense representation (one sample = 1D tensor of float values representing data about the sample's tokens).

The processing of each sample contains the following steps: 1) standardize each sample (usually lowercasing + punctuation stripping) 2) split each sample into substrings (usually words) 3) recombine substrings into tokens (usually ngrams) 4) index tokens (associate a unique int value with each token) 5) transform each sample using this index, either into a vector of ints or a dense float vector.

Some notes on passing Callables to customize splitting and normalization for this layer: 1) Any callable can be passed to this Layer, but if you want to serialize this object you should only pass functions that are registered Keras serializables (see tf.keras.utils.register_keras_serializable for more details). 2) When using a custom callable for standardize, the data recieved by the callable will be exactly as passed to this layer. The callable should return a tensor of the same shape as the input. 3) When using a custom callable for split, the data recieved by the callable will have the 1st dimension squeezed out - instead of [["string to split"], ["another string to split"]], the Callable will see ["string to split", "another string to split"]. The callable should return a Tensor with the first dimension containing the split tokens - in this example, we should see something like [["string", "to", "split], ["another", "string", "to", "split"]]. This makes the callable site natively compatible with tf.strings.split().

Attributes:

Example:

This example instantiates a TextVectorization layer that lowercases text, splits on whitespace, strips punctuation, and outputs integer vocab indices. ``` max_features = 5000 # Maximum vocab size. max_len = 40 # Sequence length to pad the outputs to.

Create the layer.

vectorize_layer = text_vectorization.TextVectorization( max_tokens=max_features, output_mode='int', output_sequence_length=max_len)

Now that the vocab layer has been created, call adapt on the text-only

dataset to create the vocabulary. You don't have to batch, but for large

datasets this means we're not keeping spare copies of the dataset in memory.

vectorize_layer.adapt(text_dataset.batch(64))

Create the model that uses the vectorize text layer

model = tf.keras.models.Sequential()

Start by creating an explicit input layer. It needs to have a shape of (1,)

(because we need to guarantee that there is exactly one string input per

batch), and the dtype needs to be 'string'.

model.add(tf.keras.Input(shape=(1,), dtype=tf.string))

The first layer in our model is the vectorization layer. After this layer,

we have a tensor of shape (batch_size, max_len) containing vocab indices.

model.add(vectorize_layer)

Next, we add a layer to map those vocab indices into a space of

dimensionality 'embedding_dims'. Note that we're using max_features+1 here,

since there's an OOV token that gets added to the vocabulary in

vectorize_layer.

model.add(tf.keras.layers.Embedding(max_features+1, embedding_dims))

At this point, you have embedded float data representing your tokens, and

can add whatever other layers you need to create your model.

## Methods

<h3 id="adapt"><code>adapt</code></h3>

<a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/v2.1.0/tensorflow/python/keras/layers/preprocessing/text_vectorization.py#L364-L402">View source</a>

```python
adapt(
    data, reset_state=True
)

Fits the state of the preprocessing layer to the dataset.

Overrides the default adapt method to apply relevant preprocessing to the inputs before passing to the combiner.

Arguments:

get_vocabulary

View source

get_vocabulary()

set_vocabulary

View source

set_vocabulary(
    vocab, df_data=None, oov_df_value=None, append=False
)

Sets vocabulary (and optionally document frequency) data for this layer.

This method sets the vocabulary and DF data 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 either replace it, if 'append' is set to False, or append to it (if 'append' is set to True).

Arguments:

Raises: