Sub topic 2
Splitting Text into Tokens
Assume you know basic Python, NumPy arrays, and the idea of fitting a machine-learning model. This chapter focuses on tokenization, the step that turns text into smaller units before a vocabulary and feature matrix are built.
What tokenization does
Tokenization is the process of splitting text into tokens. A token is a unit that the model can count or represent. Depending on the task, a token can be a word, punctuation mark, character, or part of a word.
For example:
"Models learn from text."A simple word tokenizer might produce:
["Models", "learn", "from", "text"]A tokenizer that keeps punctuation might produce:
["Models", "learn", "from", "text", "."]The choice matters because later steps treat different tokens as different vocabulary entries.
Common tokenization choices
| Strategy | Example tokens for `Cats don't sleep.` | Useful when |
|---|---|---|
| Word tokens | `Cats`, `don't`, `sleep` | General document classification |
| Word plus punctuation | `Cats`, `don't`, `sleep`, `.` | Punctuation carries meaning |
| Character tokens | `C`, `a`, `t`, `s` | Text is noisy or misspelled |
| Subword tokens | `sleep`, `##ing` | Words have useful prefixes or suffixes |
Word tokenization is easy to interpret, but it creates separate tokens for related forms such as connect, connected, and connecting. Character and subword strategies can share information across these forms, but they produce more tokens and larger feature spaces.
A simple tokenizer in Python
This example uses a regular expression. The pattern keeps alphabetic words and apostrophes inside words.
import re
text = "Cats don't sleep. Cats dream!"
tokens = re.findall(r"[A-Za-z]+(?:'[A-Za-z]+)?", text.lower())
print(tokens)The output is:
["cats", "don't", "sleep", "cats", "dream"]Lowercasing makes Cats and cats the same token. That is a normalization choice, not an unavoidable part of tokenization.
Tokenization in scikit-learn
CountVectorizer and TfidfVectorizer tokenize text while learning a vocabulary. With their default settings, they lowercase text and generally select tokens with at least two word characters.
from sklearn.feature_extraction.text import CountVectorizer
docs = ["Cats sleep", "cats dream"]
vectorizer = CountVectorizer()
matrix = vectorizer.fit_transform(docs)
print(vectorizer.get_feature_names_out())
print(matrix.toarray())Both documents use the shared token cats. The resulting matrix can therefore represent that word in the same column.
Common errors include treating punctuation behavior as obvious, forgetting that case changes vocabulary size, and assuming one tokenizer fits every language or domain.
Exercise
Why might lowercasing reduce the number of vocabulary entries?
Show answer
It maps tokens such as Cats and cats to the same normalized token, so they share one vocabulary entry.