Text, RNNs & Embeddings
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Text models need three steps: turn strings into integer token ids, map ids to dense vectors, and process the sequence of vectors. In Keras these are the TextVectorization, Embedding and recurrent (LSTM, GRU) or attention layers. This page builds a text classifier end to end and explains each option. The theory is in Recurrent Networks and Sequences and Embeddings and Representation Learning; the PyTorch counterparts are on Recurrent Layers and RNN tutorial. Input pipelines are on tf.data and loading from disk on Loading Images, Text & Audio from Disk. For transformer encoders see Attention & Transformers, and for pre-trained text models KerasHub.
It targets Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is "upcoming"), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. The complete classifier, whose train_ds and val_ds come from your own data, was run on a small synthetic text dataset.
From text to ids: TextVectorization
keras.layers.TextVectorization standardises, splits and indexes strings. Its main arguments:
| Argument | Meaning |
|---|---|
|
Vocabulary size cap, including the padding and out-of-vocabulary entries. |
|
|
|
|
|
Optional n-gram size or tuple of sizes. |
|
|
|
Pads or truncates |
|
Provide a vocabulary directly instead of calling |
The vocabulary is learned with adapt(dataset) over a dataset of strings. Id 0 is reserved for padding and id 1 for out-of-vocabulary tokens.
import keras
import tensorflow as tf
from keras import layers
train_text = tf.data.Dataset.from_tensor_slices([
"The film was wonderful",
"A dull and boring film",
"Wonderful acting, great story",
]).batch(2)
vectorize = layers.TextVectorization(
max_tokens=10_000,
output_mode="int",
output_sequence_length=16,
)
vectorize.adapt(train_text)
print(vectorize.get_vocabulary()[:6])
# ['', '[UNK]', np.str_('wonderful'), np.str_('film'), np.str_('was'), np.str_('the')]
print(vectorize(tf.constant(["a wonderful film"])))
# tf.Tensor([[12 2 3 0 0 0 0 0 0 0 0 0 0 0 0 0]], shape=(1, 16), dtype=int64)
Where to put the layer:
-
In the
tf.datapipeline withdataset.map(lambda x, y: (vectorize(x), y)). This is the efficient choice because tokenisation runs on the CPU in parallel with training, and it is the safe choice on the JAX and PyTorch backends because string ops are TensorFlow ops. -
Inside the model, so the saved model accepts raw strings. This is convenient for deployment, but on a non-TensorFlow backend the model then depends on TensorFlow for the string layer. See Keras Preprocessing Layers.
Embedding
layers.Embedding(input_dim, output_dim) is a trainable lookup table of shape (input_dim, output_dim) mapping each id to a dense vector. Input (batch, length) becomes (batch, length, output_dim). With mask_zero=True, id 0 is treated as padding and a mask propagates to later layers so recurrent layers skip padded positions and pooling layers ignore them. Because index 0 is then reserved, input_dim must be the vocabulary size (it already counts the padding entry when it comes from TextVectorization).
Embeddings can be initialised from pre-trained vectors (GloVe, word2vec) via embeddings_initializer=keras.initializers.Constant(matrix), then optionally frozen with trainable=False. Today a pre-trained transformer from KerasHub or Hugging Face usually beats this approach for anything beyond small datasets.
Recurrent layers
-
layers.LSTM(units, return_sequences=False, return_state=False, dropout=0.0, recurrent_dropout=0.0, go_backwards=False, unroll=False). -
layers.GRU(...): same interface, fewer gates and parameters, often comparably accurate. -
layers.SimpleRNN(...): rarely competitive because of vanishing gradients. -
layers.Bidirectional(layer, merge_mode="concat"): runs the layer forwards and backwards over the sequence. -
layers.RNN(cell): generic wrapper for custom cells.
return_sequences=True returns the output at every time step, shape (batch, time, units); the default returns only the last output, (batch, units). Stack recurrent layers by setting it to True on every layer except the last. return_state=True additionally returns the final hidden (and, for LSTM, cell) state, used for encoder-decoder models. With a mask from Embedding(mask_zero=True), padded steps are skipped and the last output corresponds to the last real token.
Performance note: on a GPU, the fast fused implementation is used only when the layer keeps the default activations, recurrent_dropout=0, unroll=False and use_bias=True, as documented for the TensorFlow backend; a non-default setting silently falls back to a slower generic path. The fused path needs a GPU; on a CPU these settings only change speed through the generic implementation.
A complete text classifier
import keras
import tensorflow as tf
from keras import layers
VOCAB = 20_000
SEQ_LEN = 200
# train_ds, val_ds: batched tf.data datasets of (string tensor, integer label)
vectorize = layers.TextVectorization(max_tokens=VOCAB, output_mode="int",
output_sequence_length=SEQ_LEN)
vectorize.adapt(train_ds.map(lambda text, label: text)) # fit vocabulary on training data only
def to_ids(text, label):
return vectorize(text), label
train_ids = train_ds.map(to_ids, num_parallel_calls=tf.data.AUTOTUNE).prefetch(tf.data.AUTOTUNE)
val_ids = val_ds.map(to_ids, num_parallel_calls=tf.data.AUTOTUNE).prefetch(tf.data.AUTOTUNE)
inputs = keras.Input(shape=(SEQ_LEN,), dtype="int32")
x = layers.Embedding(VOCAB, 128, mask_zero=True)(inputs)
x = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(x)
x = layers.Bidirectional(layers.GRU(32))(x)
x = layers.Dropout(0.3)(x)
outputs = layers.Dense(1)(x) # one logit
model = keras.Model(inputs, outputs)
model.compile(
optimizer=keras.optimizers.Adam(1e-3),
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy(threshold=0.0)], # threshold 0 on logits
)
model.fit(train_ids, validation_data=val_ids, epochs=5)
Source: https://www.tensorflow.org/text/guide/word_embeddings and https://www.tensorflow.org/tutorials/keras/text_classification
BinaryAccuracy(threshold=0.0) is used because the model outputs logits, not probabilities. To deploy with raw strings, wrap the vectorizer and the model in a new functional model: keras.Model(string_input, model(vectorize(string_input))).
A bag-of-words baseline
A strong baseline needs no recurrence. With output_mode="tf_idf" or "multi_hot" and ngrams=2, feed the sparse-ish vector to Dense layers. Short text classification with a few thousand examples is often solved as well by this baseline as by an LSTM, and it trains in seconds. Compare against it before adding sequence models; see Training Deep Networks for a disciplined workflow.
Padding, batching and variable lengths
-
Pad to a fixed
output_sequence_lengthfor simplicity, choosing a length near the 95th percentile of your texts. -
For long-tailed lengths use
dataset.padded_batchor bucketing intf.datato reduce wasted computation. -
Keep the mask: do not strip padding or remove the
Embeddingmask when using an RNN, otherwise the padding positions influence the result.
Visualising and reusing embeddings
After training, model.layers contains the Embedding layer; layer.get_weights()[0] is the matrix, which can be exported with vectorize.get_vocabulary() as labels into the TensorBoard embedding projector (see TensorBoard).
Pitfalls
-
Fitting the vocabulary (
adapt) on validation or test data leaks information; adapt on training text only. -
Using
input_dimsmaller than the largest id raises an index error on CPU and silently wrong values on some accelerators. -
Using softmax outputs with
from_logits=Truein the loss (or the reverse). -
Forgetting
mask_zero=True, so padding inflates averaged features. -
Recurrent layers on long sequences (hundreds of steps) train slowly and forget early tokens; prefer attention (see Attention & Transformers) or truncation.
-
Old tutorials use
keras.preprocessing.text.Tokenizerandpad_sequences. Keras 3.15 has nokeras.preprocessing.textmodule, soTokenizeris gone;keras.utils.pad_sequencesstill exists. UseTextVectorizationand tf.data instead.