Sub topic 1
Tokens, types and vocabulary
Almost every NLP system begins by cutting text into units and counting them. Before you build a tokeniser, you need exact definitions for the things being counted. This chapter defines tokens, types, word forms and vocabulary. It then shows how to measure them and how their counts behave as a corpus grows. Later chapters build tokenisers, normalisers, stemmers and lemmatisers on these definitions.
Prerequisites
This chapter assumes you have:
- Basic Python: strings, lists, dictionaries, functions, and simple regular expressions with the
remodule. - A rough idea of what an NLP task is, such as search, spam filtering or sentiment classification.
- Basic English grammar terms: noun, verb, adjective, plural, tense.
No extra libraries are needed. The code uses only the Python standard library.
Why "word" is not precise enough
In everyday speech, "word" has several meanings. Consider the sentence "The cat saw the dog."
- Someone asked how many words it contains might say 5, counting each occurrence.
- Someone asked how many different words it contains might say 4, because "the" appears twice.
- A linguist might say that "saw" and "see" are the same word, because they are forms of one dictionary entry.
These are three different counts. NLP separates them with distinct terms so that results can be reproduced and compared.
| Term | Meaning | Count for "the cat saw the dog and the dog saw the cat" |
|---|---|---|
| Token | One occurrence of a unit in running text | 11 |
| Type | A distinct token string, counted once | 5 |
| Word form | A specific inflected shape of a word, such as "saw" or "sees" | 5 |
| Lemma | The dictionary headword that groups word forms, such as "see" | 5 here, because every form is already a base form |
A token is an event, a type is a category, and each token is an instance of one type. In this chapter, a type is a distinct string after whatever preprocessing you applied. Change the preprocessing and the number of types changes.
Counting tokens and types
By convention, N is the number of tokens in a corpus and V is the number of types. A corpus is a collection of text used for study or training. The following program uses the simplest tokeniser available: it extracts runs of letters, digits and underscores.
import re
from collections import Counter
text = "the cat saw the dog and the dog saw the cat"
tokens = re.findall(r"\w+", text.lower())
types = Counter(tokens)
print(len(tokens))
print(len(types))
print(types.most_common(2))The output is:
11
5
[('the', 4), ('cat', 2)]len(tokens) is N, the length of the running text. len(types) is V, the number of distinct strings. most_common(2) lists the two most frequent types. "cat", "saw" and "dog" all occur twice, and Counter returns tied items in the order it first saw them, so "cat" comes first.
Two further measures come from these counts:
- The type-token ratio (TTR) is V divided by N. Here it is 5/11, about 0.45. A high ratio means little repetition.
- A hapax legomenon (plural hapax legomena) is a type that occurs exactly once. In the example sentence, "and" is the only one.
hapaxes = [w for w, c in types.items() if c == 1]
ttr = len(types) / len(tokens)
print(hapaxes)
print(round(ttr, 2))This prints ['and'] and 0.45.
Types depend on your preprocessing
The type count is not a fixed property of the text. It changes with every preprocessing decision. Without case folding, "The" and "the" are separate types:
import re
text = "The cat saw the dog."
raw = re.findall(r"\w+", text)
folded = re.findall(r"\w+", text.lower())
print(raw, len(set(raw)))
print(folded, len(set(folded)))The output is:
['The', 'cat', 'saw', 'the', 'dog'] 5
['the', 'cat', 'saw', 'the', 'dog'] 4The token count is 5 in both cases. The type count drops from 5 to 4. The same effect appears with stemming and lemmatisation, which merge types that share a stem or lemma. Always state the preprocessing alongside any vocabulary size you report. A paper that gives "a vocabulary of 50,000 types" without describing its tokeniser has given a number nobody can compare.
Vocabulary: the types a system actually uses
A vocabulary is the fixed set of types a system knows about. It is usually smaller than the set of all types in the training data. Reasons to cut it down:
- Memory and speed. Many models store a vector or a weight per vocabulary entry, so a 2-million-type vocabulary is costly.
- Reliability. A type seen once gives too little evidence to learn from.
- Noise. Typos, rare names and numbers inflate V without helping most tasks.
A common recipe keeps types that occur at least a minimum number of times (or the top K by frequency), and maps everything else to a special unknown symbol, often written <unk>. A token that falls outside the vocabulary is called out-of-vocabulary (OOV).
from collections import Counter
def build_vocab(token_lists, min_count=2):
counts = Counter(tok for toks in token_lists for tok in toks)
kept = sorted(w for w, c in counts.items() if c >= min_count)
vocab = ["<unk>"] + kept
return {w: i for i, w in enumerate(vocab)}
def encode(tokens, vocab):
unk = vocab["<unk>"]
return [vocab.get(t, unk) for t in tokens]
train = [["the", "cat", "sat"], ["the", "dog", "sat"], ["the", "cat", "ran"]]
vocab = build_vocab(train)
print(vocab)
print(encode(["the", "cat", "flew"], vocab))The output is:
{'<unk>': 0, 'cat': 1, 'sat': 2, 'the': 3}
[3, 1, 0]"dog" and "ran" each occur once, so they fall below min_count=2 and are dropped. "flew" never appeared in training. Both cases end up as ID 0. The model cannot tell "flew" from "dog", which is the main cost of a closed vocabulary.
How the counts behave as text grows
Two empirical regularities explain why OOV is a permanent problem.
Zipf's law says a type's frequency is roughly inversely proportional to its rank in the frequency table. The most frequent type is about twice as frequent as the second and three times as frequent as the third. A handful of types, mostly function words like "the" and "of", account for a large share of all tokens. Most types sit in a long tail of rare items, and a large fraction of them are hapax legomena.
Heaps' law describes how V grows with N:
V = K × N^β
K is a constant, often between 30 and 100 for English, and β is usually between 0.4 and 0.6. V keeps growing without ever levelling off, but it grows slower than N. Doubling a corpus does not double its vocabulary, yet new types keep arriving. New names, misspellings, compounds, product codes and inflected forms keep appearing.
The practical consequences follow directly:
- You will meet unseen types at test time, whatever the size of your training data.
- Reporting V from a small sample understates the true vocabulary.
- Comparing TTR across texts of different length is misleading, because TTR falls as N grows. Compare equal-sized samples instead.
Morphologically rich languages make this worse. Finnish, Turkish and Hungarian build long words by adding suffixes, so one lemma can have thousands of surface forms and V grows faster. Later chapters return to this when we look at stemming, lemmatisation and subword units.
Common mistakes
- Calling the token count the vocabulary size. N counts occurrences. V counts distinct strings. A 1-million-token corpus may have only 30,000 types.
- Splitting on spaces and calling the result words.
text.split()leaves punctuation attached, so "cat," and "cat" become different types. The next chapter covers this. - Ignoring preprocessing when comparing numbers. Two vocabularies built with different case handling or tokenisers are not comparable.
- Equating a type with a lemma. "run", "runs", "ran" and "running" are four types and, normally, one lemma. Reducing types to lemmas is the subject of the lemmatisation chapters.
- Using the test set to build the vocabulary. This causes the leakage described in the warning above.
Summary of the working model
- Text is a sequence of N tokens. Each token is an instance of one of V types.
- What counts as a token and a type depends on your tokeniser and normalisation.
- A vocabulary is the subset of types a system keeps, with an unknown symbol for the rest.
- Zipf's law and Heaps' law mean there will always be a long tail of rare types and new types at test time. That is the root of the OOV problem and the motivation for normalisation, stemming, lemmatisation and subword methods.
Exercise
A corpus tokenised with re.findall(r"\w+", text.lower()) contains 2,000 tokens and 400 types. After you remove case folding (so "The" and "the" stay separate), what happens to N and V? Which one can change, and why?
Show answer
N stays 2,000, because the same pattern finds the same runs of characters whatever their case. V can only stay the same or increase, because words that differed only by capitalisation, such as "The" and "the", are now counted as separate types. V stays the same only if no word appears in more than one capitalisation.
Exercise
Using the training data [["a", "b", "a"], ["b", "c", "a"], ["d", "a", "b"]] and min_count=2, which types are in the vocabulary built by build_vocab from this chapter, and what does encode(["c", "a", "z"], vocab) return?
Show answer
The counts are a=4, b=3, c=1, d=1, so only "a" and "b" reach the minimum. The vocabulary is {'<unk>': 0, 'a': 1, 'b': 2}. "c" is below the threshold and "z" was never seen, so both map to 0. The result is [0, 1, 0].
Exercise
You compute TTR for a 500-token news article (0.55) and for a 5-million-token news archive (0.02). A colleague concludes the article uses richer vocabulary. Explain why the comparison is unreliable and how to fix it.
Show answer
TTR falls as N grows, as Heaps' law predicts (V grows more slowly than N), so a very large corpus always has a lower TTR than a short text. The two numbers measure different sample sizes, not richness. To compare fairly, take samples of equal length, such as the first 500 tokens of each, or use a length-robust measure.