Sub topic 2
From Raw Text to Tokens
This chapter assumes basic Python, familiarity with training and test sets, and a general understanding of supervised learning. You should also be comfortable reading regular expressions, which are patterns used to find text.
Why tokenization matters
A classifier cannot use a paragraph directly. It needs a numeric representation. Tokenization is the process of splitting text into smaller units called tokens. A token is often a word, but it can also be punctuation, a number, or a multi-word phrase.
For example:
"Fast cars are fun!"might become:
["fast", "cars", "are", "fun"]This conversion looks simple, but the rules affect every later feature. If "Cars" and "cars" become different tokens, the vocabulary becomes larger and each form receives fewer training examples.
Normalization choices
Text normalization changes different spellings or formats into a consistent form. Common choices include:
- Converting text to lowercase.
- Replacing or removing punctuation.
- Handling numbers.
- Expanding contractions, such as changing
"can't"to"can not". - Removing common words called stop words, such as
"the"or"and". - Applying stemming or lemmatization.
Stemming cuts words down using simple rules. For example, "connected" might become "connect". Lemmatization uses vocabulary and grammar to find a word's base form. It may convert "better" to "good". These methods can reduce vocabulary size, but they can also remove useful distinctions.
There is no universally correct preprocessing sequence. For sentiment classification, removing "not" can be harmful because "not good" and "good" have different meanings. For a legal or medical task, punctuation, numbers, and exact word forms may carry important information.
A small tokenizer
A regular expression can define which characters belong to a token. The example below keeps alphabetic words and converts them to lowercase.
import re
def tokenize(text):
"""Return lowercase alphabetic tokens from text."""
return re.findall(r"[a-z]+", text.lower())
documents = [
"Fast cars are fun!",
"Cars are expensive in 2025.",
"I can't drive today.",
]
for document in documents:
print(tokenize(document))The output is:
['fast', 'cars', 'are', 'fun']
['cars', 'are', 'expensive', 'in']
['i', 'can', 't', 'drive', 'today']This tokenizer drops the year and punctuation. It also splits "can't" into "can" and "t", which may not be what you want. A production tokenizer should therefore be tested against examples from the actual data.
Tokenization in scikit-learn
TfidfVectorizer performs tokenization and later feature construction for you. By default, it lowercases text and extracts tokens containing at least two word characters. You can inspect the analyzer before training a model.
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
analyze = vectorizer.build_analyzer()
text = "Fast cars are fun! Cars cost $20,000."
print(analyze(text))The analyzer is useful for checking assumptions. If important items disappear, such as product codes, short words, or symbols, adjust the vectorizer settings or use a custom analyzer.
Common errors
A frequent error is fitting preprocessing separately on each dataset. Vocabulary decisions should come from the training data, not from the test data. A later Pipeline will enforce this boundary.
Another error is deleting information before checking its meaning. Stop-word lists, stemming, and punctuation removal are heuristics, not rules of language. Compare a simple baseline with and without each choice.
Exercise
Why might removing the word "not" reduce the quality of a sentiment classifier?
Show answer
Because "not good" expresses a different sentiment from "good". Removing "not" makes those examples look more alike and discards useful information.