How to Get the Vocabulary from a Keras Tokenizer
Learn how to read the vocabulary a Keras Tokenizer builds from your text: word_index, index_word, word counts, num_words limits, OOV tokens, TextVectorization and how to verify the result.
After you fit a Keras Tokenizer on your text, the vocabulary is already stored on the tokenizer object. You only need to know which attribute to read and how the tokenizer changed your text along the way. This guide shows where the vocabulary lives, how to turn it into a list or a limited set, and how to check that it still reflects the words that matter in your data.
What the Tokenizer does to your text
The Tokenizer class in tf.keras.preprocessing.text takes raw strings and turns them into tokens, usually words. A token is a unit of text the model treats as one item. When you call fit_on_texts, the tokenizer cleans each string, splits it into words, counts them and assigns each distinct word an integer index. That mapping from word to integer is the vocabulary. Later, texts_to_sequences uses the same mapping to convert new text into lists of integers that a model can consume.
The scope matters. The vocabulary contains only words seen during fit_on_texts, after cleaning. The tokenizer does not keep your original spelling, capitalization or punctuation, so the vocabulary describes a transformed version of your text rather than the text itself.
Step 1: Fit the tokenizer and read word_index
The main vocabulary attribute is word_index, a dictionary that maps each word to its integer index. Indices start at 1 because 0 is reserved for padding. Words are ranked by frequency, so the most common word gets the lowest index.
from tensorflow.keras.preprocessing.text import Tokenizer
texts = ['The cat sat.', 'The dog sat down!']
tokenizer = Tokenizer(oov_token='<OOV>')
tokenizer.fit_on_texts(texts)
vocab = tokenizer.word_index
print(vocab)
Example output, derived from the documented behavior and not from a verified run: {'<OOV>': 1, 'the': 2, 'sat': 3, 'cat': 4, 'dog': 5, 'down': 6}. The out-of-vocabulary token, if you set one, is placed at index 1. 'the' and 'sat' each appear twice, so they come next; the remaining words appear once. Among words with equal counts, the order generally follows first appearance, but treat that as an implementation detail rather than a guarantee.
Step 2: Use the related attributes when you need more than the mapping
| Attribute | What it holds | Typical use |
| word_index | word → integer index | Build an embedding matrix, look up a word's ID |
| index_word | integer index → word | Decode sequences back into words |
| word_counts | word → number of occurrences across all texts | Inspect frequency, find rare words |
| word_docs | word → number of texts containing the word | Document frequency checks |
| document_count | number of texts the tokenizer was fitted on | Sanity check on input size |
To get the vocabulary as an ordered list of words, sort word_index by its values:
vocab_list = [word for word, idx in sorted(tokenizer.word_index.items(), key=lambda item: item[1])]
print(vocab_list)
vocab_size = len(tokenizer.word_index) + 1 # +1 for the reserved padding index 0
print(vocab_size)
The +1 matters when you size an Embedding layer: input_dim must cover every index, including 0.
Step 3: Account for num_words
Setting num_words does not shrink word_index. The dictionary still contains every word seen during fitting. The limit is applied only when converting text, in methods such as texts_to_sequences, which keep words whose index is lower than num_words. If you set an OOV token, words above the limit are replaced by it; otherwise they are dropped. To get the vocabulary the model will actually see, filter it yourself:
tokenizer = Tokenizer(num_words=1000, oov_token='<OOV>')
tokenizer.fit_on_texts(texts)
effective_vocab = {word: idx for word, idx in tokenizer.word_index.items() if idx < tokenizer.num_words}
Step 4: Check how cleaning changed your words
By default the tokenizer lowercases text, replaces a set of punctuation characters with spaces and splits on a single space character. The default filter string is:
'!"#$%&()*+,-./:;<=>?@[\]^_`{|}~\t\n'
Because the apostrophe is not in that set, contractions survive, while hyphens, plus signs and underscores split or disappear. Example input and the tokens you can expect from the default settings (illustrative, not a verified run):
- "Don't" → don't
- "e-mail" → e, mail
- "C++" → c
- "user_id" → user, id
- "Apple" and "apple" → apple (merged into one entry)
If these changes would remove meaningful distinctions, adjust the constructor: pass a shorter filters string to keep characters such as hyphens, set lower=False to preserve case, or use char_level=True if you need characters rather than words.
Watch for invisible and Unicode differences. The tokenizer does not apply Unicode normalization, so "café" written with a single precomposed é (U+00E9) and "café" written as e followed by a combining accent (U+0301) become two separate vocabulary entries. Splitting uses the split character you configure, which is a regular space (U+0020) by default; a non-breaking space (U+00A0) between two words is not treated as a separator, so "New[U+00A0]York" stays a single token. Normalize your text before fitting if these cases appear in your data.
Step 5: Save and reload the vocabulary
To reuse the same vocabulary later, save the whole tokenizer configuration rather than only word_index, so the filters and settings travel with it:
from tensorflow.keras.preprocessing.text import tokenizer_from_json
with open('tokenizer.json', 'w', encoding='utf-8') as f:
f.write(tokenizer.to_json())
with open('tokenizer.json', encoding='utf-8') as f:
restored = tokenizer_from_json(f.read())
assert restored.word_index == tokenizer.word_index
Writing with encoding='utf-8' avoids losing non-ASCII words when the file is saved on systems with a different default encoding.
If you use TextVectorization instead
The legacy Tokenizer is marked as deprecated in recent TensorFlow releases, and newer Keras code typically uses the TextVectorization layer. There, the vocabulary is returned by the get_vocabulary method as a list ordered by index:
import tensorflow as tf
layer = tf.keras.layers.TextVectorization()
layer.adapt(['The cat sat.', 'The dog sat down!'])
print(layer.get_vocabulary())
print(layer.get_vocabulary(include_special_tokens=False))
print(layer.vocabulary_size())
In the full list, position 0 is the empty string used for padding and position 1 is the '[UNK]' token for unknown words; real words follow, ranked by frequency. The order among equally frequent words may differ from the legacy Tokenizer. TextVectorization's default standardization lowercases text and strips punctuation, so run the same cleaning checks described above.
Verify the result
- Print the first entries of the sorted vocabulary and confirm the most frequent words look right.
- Look up a few words you know are important, including ones with hyphens, accents or capital letters, and confirm they appear in the form you expect.
- Check that len(word_index) + 1, or vocabulary_size() for TextVectorization, matches the input_dim of your Embedding layer.
- If you set num_words, confirm that texts_to_sequences on a sample sentence produces only indices below that limit.
- Decode one sequence with index_word to make sure it reads back as the expected words.
Gaps to keep in mind
No version-specific evidence was supplied for this guide. The attribute names and defaults described here reflect the commonly documented tf.keras API, and the example outputs are derived from that behavior rather than from a verified run. Availability and defaults can change between TensorFlow and Keras versions, so confirm them against the documentation for the version you have installed.