Sub topic 2
From Raw Text to Tokens
This chapter covers the first step of the pipeline: turning a raw string into a list of tokens that later steps can count. It assumes you know basic Python, have used regular expressions at least once, and understand the idea of a training set and a test set. You do not need to know TF-IDF yet. The next chapters build on the token lists produced here.
Why preprocessing matters
A classifier cannot read strings. It reads numbers. Before any weighting or model fitting, each document has to become a sequence of discrete units that can be counted. Those units are called tokens. Most of the time a token is a word, but it can also be a number, a piece of punctuation, or a fragment of a word.
Every choice made at this stage changes the vocabulary, which is the set of distinct tokens the model will know about. A choice that merges "Cat" and "cat" shrinks the vocabulary and pools evidence. A choice that splits "don't" into two pieces changes which words the model sees. These choices are made once and then silently affect everything downstream.
The preprocessing steps
Lowercasing
Lowercasing maps "Space", "SPACE", and "space" to one token. This helps when the training set is small, because each form would otherwise get only a fraction of the evidence. It hurts when case carries meaning. "US" (the country) and "us" (the pronoun) become the same token. "Apple" the company and "apple" the fruit merge too. For topic classification the pooling usually wins. For tasks like detecting shouting or named entities, you may want to keep case.
TfidfVectorizer lowercases by default (lowercase=True).
Tokenization
Tokenization splits a string into tokens. The simplest approach splits on whitespace, but that leaves punctuation stuck to words: "mat." and "mat" would be different tokens.
scikit-learn's default tokenizer uses the regular expression (?u)\b\w\w+\b. It keeps runs of two or more word characters and drops everything else. You can see its effect directly:
import re
text = "Don't panic: the U.S. launched 3 probes, e-mail me at [email protected]!"
default_pattern = re.compile(r"(?u)\b\w\w+\b")
print(default_pattern.findall(text.lower()))The output is:
['don', 'panic', 'the', 'launched', 'probes', 'mail', 'me', 'at', 'nasa', 'example', 'com']Several things happened that you may not expect:
- "Don't" became
don. Thetwas dropped because it is a single character. - "U.S." disappeared entirely, since each letter is alone between punctuation marks.
- The digit
3disappeared because it is one character long. - "e-mail" lost its
efor the same reason. - The email address was split into three tokens.
None of these is a bug. They are consequences of a design that favors simplicity. You should know them so you can decide whether they matter for your data.
Stop word removal
Stop words are very common words such as "the", "and", and "of". They appear in almost every document, so they rarely help tell classes apart. Removing them shrinks the feature matrix.
In scikit-learn you pass stop_words="english". The built-in list has 318 words. Two cautions apply:
- The list was not built for every task. It includes words like "not", "no", and "never", which matter for sentiment. Removing them turns "not good" into "good".
- Stop words are less necessary with TF-IDF than with raw counts. TF-IDF already gives a low weight to words found in nearly every document. Removal is still a cheap way to cut noise and speed up training.
You can also pass your own list of strings, which is safer when you know your domain.
Stemming and lemmatization
Stemming chops word endings with fixed rules so that "launching", "launched", and "launches" share a stem. Lemmatization looks words up in a dictionary and returns the base form, called the lemma, so "better" becomes "good" given the right part of speech.
| Method | How it works | Example output for "studies" | Typical cost |
|---|---|---|---|
| None | Keep the word as is | studies | none |
| Stemming | Strip suffixes by rules | studi | fast |
| Lemmatization | Dictionary lookup, often needs a part of speech tag | study | slower, needs a language resource |
scikit-learn does not stem or lemmatize. You supply a function through the tokenizer or preprocessor argument. A short example with NLTK's Porter stemmer:
import re
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
stemmer = PorterStemmer()
token_pattern = re.compile(r"(?u)\b\w\w+\b")
def stem_tokenizer(text):
return [stemmer.stem(tok) for tok in token_pattern.findall(text)]
vectorizer = TfidfVectorizer(
tokenizer=stem_tokenizer,
token_pattern=None,
stop_words=None,
)
X = vectorizer.fit_transform(["The probes launched", "A probe launches soon"])
print(vectorizer.get_feature_names_out())Setting token_pattern=None tells scikit-learn you are replacing the pattern. Without it, you get a warning that the pattern will be ignored.
Stemming is not always worth it. With a large training set, a linear model can learn that "launch", "launched", and "launches" all point the same way. Stemming mostly helps when data is scarce. It can also hurt by merging unrelated words, such as "university" and "universe" under some stemmers.
Accents and Unicode
The strip_accents argument accepts "ascii" (fast, handles many Latin characters), "unicode" (slower, more thorough), or None (the default, which leaves accents alone). Use it when your data mixes "café" and "cafe". It does not help with scripts that do not separate words by spaces, such as Chinese or Japanese. Those need a language-specific tokenizer.
Where preprocessing lives in scikit-learn
TfidfVectorizer and CountVectorizer split the work into three hooks. Knowing the order tells you which one to override.
preprocessortakes the raw string and returns a string. By default it lowercases and optionally strips accents.tokenizertakes that string and returns a list of tokens. By default it appliestoken_pattern.analyzeris the whole chain, including n-gram building and stop word filtering. You normally leave it as"word".
You can inspect each one without fitting anything:
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(stop_words="english")
preprocess = vectorizer.build_preprocessor()
tokenize = vectorizer.build_tokenizer()
analyze = vectorizer.build_analyzer()
text = "The Probes LAUNCHED to Mars, again and again."
print(preprocess(text))
print(tokenize(preprocess(text)))
print(analyze(text))build_analyzer() returns the exact function the vectorizer applies to each document. When you are unsure why a word is missing from the vocabulary, run your sample text through it. This is the quickest debugging tool in this chapter.
Cleaning that belongs outside the vectorizer
Some cleaning is specific to your data source rather than to language in general. The 20 newsgroups data used in this tutorial is a good example. Each post starts with a header block that names the newsgroup, and many posts end with a signature and quoted replies. A classifier can latch onto those and score well for the wrong reason.
fetch_20newsgroups lets you drop them:
from sklearn.datasets import fetch_20newsgroups
categories = ["sci.space", "rec.autos"]
raw = fetch_20newsgroups(subset="train", categories=categories)
clean = fetch_20newsgroups(
subset="train",
categories=categories,
remove=("headers", "footers", "quotes"),
)
print(len(raw.data[0]), len(clean.data[0]))
print(clean.data[0][:200])Other sources have their own artifacts: HTML tags, URLs, email addresses, boilerplate footers, and timestamps. A few rules of thumb:
- Remove or replace artifacts that identify the source but not the topic. Leaking the label through a header inflates your test score and the model fails on real data.
- Replace rather than delete when the presence of the thing is informative. For example, replacing every URL with the token
urltokenkeeps the fact that a link appeared. - Write these steps as a function of one string, so you can pass it as the
preprocessorand keep it inside the pipeline.
import re
URL = re.compile(r"https?://\S+")
EMAIL = re.compile(r"\S+@\S+")
def clean_text(text):
text = URL.sub(" urltoken ", text)
text = EMAIL.sub(" emailtoken ", text)
return text.lower()You would pass this as TfidfVectorizer(preprocessor=clean_text). When you supply a preprocessor, scikit-learn no longer lowercases for you, which is why the function lowercases itself.
Common errors
- Preprocessing outside the pipeline with statistics from all the data. Pure per-document cleaning, such as lowercasing, is safe to do anywhere. Anything that learns from data, such as building a vocabulary or choosing a frequency cutoff, must be fit on training data only. The vectorizer does this correctly when it sits inside a
Pipeline. - Forgetting that the default drops one-letter tokens. Tokens such as "a", "I", and "C" vanish, and so do single digits. If you classify code or product names, set
token_pattern=r"(?u)\b\w+\b". - Stop word and tokenizer mismatch. See the warning above.
- Over-cleaning. Removing all digits, punctuation, and short words can erase useful signals such as "$", "!!!", and years. Start with the defaults and add steps only when you can show they help on validation data.
- Assuming English. The built-in stop word list, stemmers, and token pattern are tuned for English and similar languages.
Choosing your steps
A practical default for a medium-sized English topic task is lowercasing, the default token pattern, and stop_words="english". Add stemming or custom cleaning only when a validation score or an inspection of the vocabulary tells you to. Because each choice is a hyperparameter of the vectorizer, you can compare variants in the grid search covered later in the tutorial.
Exercise
Using the default token pattern (?u)\b\w\w+\b with lowercasing, what tokens does TfidfVectorizer().build_analyzer() produce for the text "I can't find the C++ docs in 2024!"? Which meaningful pieces are lost, and which single argument change would keep one-letter tokens?
Show answer
The tokens are ['can', 'find', 'the', 'docs', 'in', '2024']. The pattern requires two or more word characters, so "I" is dropped, "can't" becomes "can" because the "t" is a single character, and "C" from "C++" is dropped, as the plus signs are not word characters. The negation in "can't" and the name of the language are both lost. Setting token_pattern=r"(?u)\b\w+\b" keeps one-letter tokens, giving ['i', 'can', 't', 'find', 'the', 'c', 'docs', 'in', '2024']. Note that this still splits "can't" into "can" and "t", so negation handling would need a custom tokenizer.
Exercise
You add a Porter stemming tokenizer and set stop_words="english" in the same TfidfVectorizer. scikit-learn prints a warning. Why, and what are two ways to fix it?
Show answer
The stop word list holds unstemmed words, but the tokenizer outputs stemmed tokens, so some stop words, such as "because" which becomes "becaus", no longer match the list and are not removed. The two fixes are to remove stopwords and filter inside your own tokenizer, or to stem the stop word list with the same stemmer and pass it as a list to stopwords.