Sub topic 4
Building a vocabulary
A vocabulary is the fixed list of terms that become the columns of your feature matrix. This chapter covers how scikit-learn builds that list, how the choices before it change its contents, and what happens to words the list doesn't contain. It assumes you know basic Python and what a tokenizer and lowercasing do, as covered in the previous chapters.
What a vocabulary is
A vocabulary is a mapping from each distinct token to a column index. If the vocabulary has 8 entries, every document becomes a vector of length 8, and position 3 always means the same term. Without that fixed mapping, vectors from different documents could not be compared or stacked into a matrix.
Building one takes four steps:
- Tokenize every training document.
- Normalize the tokens, for example by lowercasing them.
- Collect the distinct tokens.
- Assign each token an integer index.
Inspecting a learned vocabulary
CountVectorizer.fit runs these steps and stores the result in the vocabulary_ attribute. The trailing underscore is scikit-learn's convention for values learned during fit.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
vec.fit(docs)
print(sorted(vec.vocabulary_.items()))
print(vec.get_feature_names_out())
print(len(vec.vocabulary_))The output is:
[('cat', 0), ('chased', 1), ('dog', 2), ('log', 3), ('mat', 4), ('on', 5), ('sat', 6), ('the', 7)]
['cat' 'chased' 'dog' 'log' 'mat' 'on' 'sat' 'the']
8Three points follow from this output:
- The indices are alphabetical. They do not follow the order in which words first appear. This makes the column layout reproducible whatever order the documents arrive in.
vocabulary_maps token to index.get_feature_names_out()gives the reverse view: the array position is the column index, and the value is the token.- The word "the" is in the vocabulary. No stop-word list was set, so even the most common word gets a column.
Choices that shape the vocabulary
Everything that happens before step 3 changes which strings end up as distinct entries. The same corpus can yield very different vocabularies.
Tokenization pattern
By default, CountVectorizer uses the regular expression (?u)\b\w\w+\b. It keeps runs of two or more letters, digits, or underscores. Single-character tokens are silently dropped. You can check this without fitting anything:
from sklearn.feature_extraction.text import CountVectorizer
analyzer = CountVectorizer().build_analyzer()
print(analyzer("I saw a cat, 42 times: e-mail it!"))The output is ['saw', 'cat', '42', 'times', 'mail', 'it']. Here "I", "a", and "e" are lost. The hyphenated "e-mail" is split into "e" and "mail", and only "mail" survives. Punctuation never enters the vocabulary. If single characters matter, as in "C" or "R" in programming-language text, pass your own token_pattern, such as r"(?u)\b\w+\b".
Normalization
Lowercasing is on by default (lowercase=True), so "Cat" and "cat" share one entry. Turning it off roughly doubles the entries for capitalized words, because "The" and "the" then count as different terms. Two other options matter here:
strip_accentsmerges "café" and "cafe".stop_words="english"removes common function words before indexing. This shrinks the vocabulary and reduces noise in some tasks. It also removes words such as "not" that can carry meaning in sentiment tasks.
N-grams and other settings
ngram_range=(1, 2) adds every adjacent word pair as its own entry. A corpus with 10,000 distinct words can easily produce hundreds of thousands of distinct pairs. Later chapters cover n-grams and the pruning options (min_df, max_df, max_features) that keep this growth under control.
| Setting | Effect on the vocabulary |
|---|---|
| `lowercase=False` | Case variants become separate entries |
| `stop_words="english"` | Common words are removed |
| `token_pattern` | Changes what counts as a token, including single characters |
| `ngram_range=(1, 2)` | Adds phrase entries, which can grow the size by a large factor |
| `vocabulary=[...]` | Skips learning and uses your list |
Unseen words at transform time
The vocabulary is frozen after fit. When transform meets a token that was not in the training data, it ignores that token. It does not raise an error and it does not add a column.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer().fit(docs)
new = vec.transform(["the bird sat"])
print(vec.get_feature_names_out())
print(new.toarray())The second line printed is [[0 0 0 0 0 0 1 1]]. Only "sat" (index 6) and "the" (index 7) are counted. "bird" contributes nothing, so a document made only of unseen words becomes an all-zero row. That has two consequences:
- Information is lost silently. A large share of test words missing from the vocabulary is a sign that the training data does not match the data you will see in use.
- Cosine similarity with an all-zero vector is undefined, and scikit-learn returns 0 for it. Do not read that as "dissimilar". It means "no known words".
Supplying a fixed vocabulary
You can skip learning and give the vectorizer the exact list of terms. This is useful when the columns must match an existing feature set, or when you only care about a handful of keywords.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer(vocabulary=["cat", "dog", "bird"])
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.toarray())The output is:
['cat' 'dog' 'bird']
[[1 0 0]
[0 1 0]
[1 1 0]]With a list, the columns follow the order you gave, not alphabetical order. The column for "bird" exists but is all zeros, because no training document contains it. Your terms must match the tokenizer's output. Passing "Cat" with the default lowercasing would produce a column that never fires.
Common mistakes
- Fitting on all the data. Learning the vocabulary from test documents leaks information into your evaluation. Fit on training text only. A later chapter covers this.
- Assuming the vocabulary is complete. It contains only what the tokenizer produced from the training set, not every word of the language.
- Comparing matrices from separate fits. Two vectorizers fitted on different corpora have different column meanings. Column 3 in one is not column 3 in the other. Always reuse the same fitted vectorizer.
- Reading
vocabulary_order as column order. Sort by index or useget_feature_names_out().
Exercise
You fit CountVectorizer() on the three documents above, then call transform(["a dog and a cat"]). Which column indices have a nonzero count, and why are the others zero?
Show answer
The tokenizer drops the single-character token "a". It keeps "dog", "and", and "cat". The word "and" is not in the vocabulary, so it is ignored. "cat" is index 0 and "dog" is index 2, so the row is [1 0 1 0 0 0 0 0]. Every other column is zero because those terms do not appear in the new document.
Exercise
A teammate fits one vectorizer on the training set and another on the test set, then feeds both matrices to a classifier trained on the first. What goes wrong?
Show answer
The two vocabularies differ in size and in the meaning of each column. The matrices may not even have the same number of columns, and where they do, the same index refers to different words. The classifier's learned weights would be applied to the wrong features. The fix is to fit the vectorizer once on the training set and call only transform on the test set.