Tools and Data
Preparing Text
Introduction
A model takes numbers as input, and a message is a string. Preparing text means cleaning the string, splitting it into words, reducing the number of distinct words, and counting them, so that each message becomes a row of numbers. Each step removes information, so each one is a choice about which information the model does not need.
The examples use the SMS Spam Collection, a public dataset of 5,572 text messages labeled ham (legitimate) or spam. 403 rows are exact duplicates. Without them, 5,169 messages remain: 4,516 ham and 653 spam.
Cleaning the Text
Lowercasing
str.lower() turns Free, FREE and free into the same word, so the model sees one feature instead of three. The downside is that the capitals are gone. In this dataset, 70% of spam messages contain a word of three or more capital letters, such as FREE or URGENT, against 6% of ham messages.
df["message"] = df["message"].str.lower()
Removing characters
A regular expression removes every character outside a chosen set:
import re
df["message"] = df["message"].apply(lambda x: re.sub(r"[^a-z\s$!]", "", x))
[^...] matches any character that is not in the brackets, and re.sub replaces each match with an empty string. This pattern keeps the letters a to z, whitespace (\s), $ and !, and deletes everything else:
call 09061701461 to claim £900 prize! don't
call to claim prize! dont
Removing the apostrophe joins don't into dont. New messages go through the same step, so their don't also becomes dont and matches the same column. In this dataset, 128 messages already write dont and 116 write don't, and the step merges both spellings into one feature.
Removing digits deletes phone numbers, short codes and prices. In this dataset, 94% of spam messages contain a digit, against 16% of ham messages, so digits separate the two classes well. Replacing each run of digits with a placeholder word keeps that signal while still merging all the different numbers into one feature:
x = re.sub(r"\d+", " num ", x) # before removing other characters
Finding what to clean
Which characters need handling depends on the dataset. Reading a few rows shows some of them. Counting every character that is not a letter, digit or space over the whole column shows all of them, with how often each one occurs:
import re
from collections import Counter
tags = Counter()
chars = Counter()
for text in df["text"]:
tags.update(re.findall(r"<[^>]{0,20}>", text)) # anything shaped like an HTML tag
chars.update(re.findall(r"[^a-zA-Z0-9\s]", text)) # every character that is not a letter, digit or space
print(tags.most_common(10))
print(chars.most_common(40))
re.findall returns every match in one text, Counter.update adds them to the running totals, and most_common(n) lists the n most frequent with their counts.
On the IMDB movie reviews dataset, 50,000 reviews collected from web pages and labeled positive or negative, the counts show four things the SMS messages do not have:
| Found | Example | Handling |
|---|---|---|
| HTML tags | <br /> about 100,000 times in 25,000 reviews, and a few <i> and <em> | Remove every tag with one pattern |
| Other apostrophe characters | `, ´ and ’ | Convert them to ' before tokenizing, so didn’t is split the same way as didn't |
| Accented letters | é in café and Pokémon | Convert them to the plain letter, so [^a-z] does not split the word in two |
| Characters from an old Windows encoding | \x96 and \x97, which are dashes | Remove them together with the accents |
HTML tags, apostrophes and accents
import unicodedata
def clean(text):
text = text.lower()
text = re.sub(r"<[^>]+>", " ", text) # every HTML tag
text = re.sub(r"[`´’‘]", "'", text) # other apostrophe characters become '
text = unicodedata.normalize("NFKD", text) # é becomes e followed by a separate accent mark
text = text.encode("ascii", "ignore").decode("ascii") # drops the accent marks and every other non-ASCII character
text = re.sub(r"[^a-z\s']", " ", text) # remaining digits and punctuation become spaces
return text
Tags and punctuation are replaced with a space instead of an empty string, so movie.<br />the becomes movie the, and the two words stay separate. The extra spaces do no harm, because the tokenizer ignores whitespace.
unicodedata.normalize("NFKD", ...) splits each accented letter into the plain letter and a separate accent character. Encoding to ASCII with "ignore" drops every character outside ASCII, which removes the accent characters and the \x96 and \x97 dashes. CountVectorizer and TfidfVectorizer can remove accents themselves with strip_accents="unicode".
Tokenization
A token is one unit of text, usually a word or a punctuation mark. Tokenization splits a string into a list of tokens. NLTK (the Natural Language Toolkit) is a Python library for working with human-language text: it provides tokenizers, stop word lists, stemmers and lemmatizers. Their data files are downloaded separately with nltk.download. NLTK’s word_tokenize does more than splitting on spaces. It separates punctuation from words and splits contractions:
from nltk.tokenize import word_tokenize
word_tokenize("go until jurong point, crazy.. don't")
# ['go', 'until', 'jurong', 'point', ',', 'crazy', '..', 'do', "n't"]
word_tokenize uses a pretrained sentence splitter called Punkt. Its data files are downloaded once with nltk.download("punkt") and nltk.download("punkt_tab").
Stop Words
Stop words are very common words such as the, is and in. They appear in almost every message, so whether they appear tells you little about whether a message is spam. NLTK’s English list has 198 of them, downloaded with nltk.download("stopwords"):
from nltk.corpus import stopwords
stop_words = set(stopwords.words("english"))
df["message"] = df["message"].apply(lambda x: [w for w in x if w not in stop_words])
On this dataset, removing them cuts the total number of tokens from 77,697 to 46,920.
The list also contains not and no. After removal, not free and free look the same. For tasks where negation changes the meaning, such as sentiment analysis, these words have to stay. Removing them from the set before filtering keeps them in the text:
negations = {"not", "no", "nor", "never", "n't"}
stop_words = set(stopwords.words("english")) - negations
word_tokenize splits a contraction into two tokens: didn't becomes did and n't, and isn't becomes is and n't. did and is are stop words, so n't is the token that keeps the negation. Replacing it with not after tokenizing makes isn't good and not good the same feature:
tokens = ["not" if t == "n't" else t for t in tokens]
The list contains don't and don, but the regex step runs first and has already turned don't into dont, which is not on the list, so dont stays in every message. A stop word list only works on text in the form the list expects.
Stemming and Lemmatization
Both reduce the different forms of a word to one form, so claim, claimed and claiming count as the same feature. They differ in how they find that form:
- A stemmer cuts the end off each word with fixed rules, such as removing
-ingor turning a final-yinto-i. It has no list of real words. NLTK’sPorterStemmerimplements the Porter algorithm, a set of suffix rules for English published in 1980. - A lemmatizer looks each word up in a dictionary and returns its base form (the lemma), which is always a real word. NLTK’s
WordNetLemmatizeruses the WordNet dictionary, downloaded withnltk.download("wordnet").
Their output on the same words:
| Word | Stem (PorterStemmer) | Lemma (WordNetLemmatizer) |
|---|---|---|
| claimed, claiming | claim | claim |
| studies, studying | studi | study |
| crazy | crazi | crazy |
| university, universe | univers | university, universe |
| went | went | go |
| won | won | win |
| better | better | good |
| mice | mice | mouse |
The stem does not have to be a real word. crazi is fine for a model, which only needs every form of crazy to map to the same feature. The rules make mistakes in both directions, though. university and universe merge although they are unrelated, because they start the same way. Irregular forms such as went, won and mice stay separate from go, win and mouse, because they have no suffix to cut off. The lemmatizer gets all of these right, because the dictionary lists irregular forms.
The lemmatizer needs to know the part of speech (noun, verb, adjective) of each word. Without it, WordNetLemmatizer treats every word as a noun, and claiming and went come back unchanged. The rows above were lemmatized with the right part of speech, such as lemmatize("went", pos="v"). Getting it for every word in a text means running a part-of-speech tagger first, which makes lemmatization slower. The part of speech also separates meanings: meeting as a noun (the meeting) stays meeting, and as a verb (meeting you) becomes meet. The stemmer turns both into meet.
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
df["message"] = df["message"].apply(lambda x: [stemmer.stem(w) for w in x])
Stemming is faster and needs no tagger, and its non-words do not matter when the output only feeds a model and nobody reads it. On this dataset, stemming reduces the number of distinct words from 8,459 to 7,121.
Bag of Words
A bag of words represents each message by how often each word appears in it. Word order is lost, which is where the name comes from. CountVectorizer builds a vocabulary of every word in the training messages, gives each word a column, and turns each message into a row of counts. A list of numbers like this row is called a vector, so a tool that turns text into vectors is called a vectorizer. Like every scikit-learn tool, it works in two steps: fit learns from the training messages, which for CountVectorizer means building the list of words, and transform turns any messages into counts using that list. fit_transform does both on the same data. The table shows the counts for two messages, with ngram_range=(1, 2), which is explained below:
| call | call free | cash | entri | entri win | free | free entri | free now | now | win | win cash | |
|---|---|---|---|---|---|---|---|---|---|---|---|
free entri win cash | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 1 |
call free now | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 0 |
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=1, max_df=0.9, ngram_range=(1, 2))
X = vectorizer.fit_transform(df["message"])
vectorizer.get_feature_names_out() # the vocabulary, one name per column
Here each message in df["message"] is one string, with its tokens joined by spaces. Giving the Tokens to CountVectorizer explains why the token lists are joined, and how to pass them without joining.
N-grams
An n-gram is a sequence of n adjacent tokens. Unigrams are single words and bigrams are pairs. ngram_range=(1, 2) creates a column for every unigram and every bigram. Bigrams keep some of the word order: free entri is a column of its own, separate from free and entri.
Bigrams add many columns. On this dataset, unigrams alone give 7,101 columns, and unigrams plus bigrams give 37,069. More columns take more memory and more training time, and most of the new bigrams appear in only a few messages, so they carry little information about other messages. Sparse matrices handles the memory, and min_df removes the rare columns.
Sparse matrices
A matrix is a grid of numbers in rows and columns, like the bag-of-words table. A matrix where almost every value is 0 is called sparse. Each message uses only a few of the 37,069 columns: of the matrix’s 5,169 × 37,069 cells, 80,181 are non-zero, which is 0.04%. fit_transform therefore returns the matrix in a sparse format from scipy, a Python library for scientific computing. The format stores only the non-zero cells, each with its row and column, and every cell it does not list is 0. A dense array of the same shape, which stores every cell including the zeros, would need about 1.5 GB as 64-bit integers. scikit-learn models accept sparse matrices directly.
min_df and max_df
Both remove columns based on document frequency: the number of messages a term appears in.
| Parameter | Removes terms that appear in | Typical use |
|---|---|---|
min_df=5 | fewer than 5 messages | Drops typos, names and one-off words |
min_df=0.01 | less than 1% of messages | The same, as a fraction |
max_df=0.9 | more than 90% of messages | Drops words common in this dataset, like a stop word list built from the data |
An integer is a number of messages and a float is a fraction. min_df=1 keeps every term. On this dataset, max_df=0.9 removes nothing either: the most common term, call, appears in 9.7% of messages. Raising min_df to 5 reduces the columns from 37,069 to 1,881.
Fitting on training data only
fit reads the training messages and creates one column for each word it finds. After that, the list of columns does not change. A word that was not in the training messages has no column, and transform ignores it, so a word that spammers start using after training has no effect on the prediction. The vectorizer learns from data just as the model does: its list of columns comes from the messages it was fitted on. It is therefore fitted on the training set only, for the same reason as the model, as described in Splitting Without Leakage. Fitted on all messages, it would create columns for words that appear only in the test messages, and the test score would no longer show how the model handles messages it has never seen. The fitted vectorizer is saved with the model, because every new message has to be turned into the same columns before the model can score it.
Giving the Tokens to CountVectorizer
The cleaning steps earlier in this note turn each message into a list of tokens, such as ['free', 'entri', 'win']. CountVectorizer expects each message as one string instead, because it cleans and splits the text itself: it lowercases the string, splits it into tokens and builds n-grams. Given a list, it fails at the first of those steps:
AttributeError: 'list' object has no attribute 'lower'
There are two ways to give it the tokens:
- Join each list back into a string, with spaces between the tokens. The default
CountVectorizeraccepts it, and strings are easy to print and save to a CSV.CountVectorizerthen splits the string again with its own rule, which drops$,!and single letters. - Pass the lists as they are, with
CountVectorizerset up to skip its own lowercasing and splitting. Every token from the cleaning steps is kept, including$and!. New messages then have to be passed as token lists too.
Join the tokens when the default settings are enough. Pass the lists when the cleaning steps kept symbols on purpose, since joining drops them again. The rest of this note uses joined strings, because they are easier to show.
Joining the tokens into a string
Joining each list with spaces turns it back into a string that the default CountVectorizer accepts:
df["message"] = df["message"].apply(lambda x: " ".join(x))
Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...
go jurong point crazi avail bugi n great world la e buffet cine got amor wat
CountVectorizer then splits the string into tokens a second time, with its own rules. Its default token_pattern is (?u)\b\w\w+\b: a token is two or more letters, digits or underscores. It drops $, ! and single letters such as u, n and c, so keeping $ and ! in the regex step has no effect. ! appears in 47% of spam messages and 12% of ham messages, so dropping it removes a feature that separates the two classes. Changing the pattern so that any run of non-space characters is a token keeps them:
CountVectorizer(token_pattern=r"\S+")
Passing the token lists directly
CountVectorizer’s preprocessor and tokenizer parameters accept functions that replace its own lowercasing and splitting. A function that returns its input unchanged makes both steps do nothing, so the lists from NLTK are used as they are:
from sklearn.feature_extraction.text import CountVectorizer
def identity(x):
return x
vectorizer = CountVectorizer(
preprocessor=identity, # no preprocessing of its own
tokenizer=identity, # the input is already a list of tokens
lowercase=False, # already lowercased
token_pattern=None, # not used when tokenizer is set
ngram_range=(1, 2),
)
X = vectorizer.fit_transform(df["message"]) # a column of token lists
N-grams still work: the vocabulary includes bigrams such as win $.
identity is a named function and not a lambda, because a model saved with joblib can store a named function but cannot store a lambda.
TF-IDF
Bag-of-words counts have two problems on longer texts, such as reviews:
- Length: a review of 2,000 words has larger counts than a review of 50 words that says the same thing.
- Common words: words that appear in most documents, such as
moviandfilmin movie reviews, get large counts and carry little information about the label.
TF-IDF (term frequency, inverse document frequency) corrects both. Each value is the term’s count in the document (TF) multiplied by a weight for the term (IDF), which is low for terms that appear in many documents and high for terms that appear in few.
The IDF of a term depends on how many of the training documents contain it. A term in every document gets a weight of 1, so it still counts, and the weight rises as fewer documents contain the term. With 4 documents:
| Term appears in | IDF |
|---|---|
| 4 of 4 documents | 1.00 |
| 2 of 4 documents | 1.51 |
| 1 of 4 documents | 1.92 |
The weight rises slowly. With 1,000 documents, a term that appears in only one of them gets an IDF of 7.2, so the rarest term weighs about 7 times as much as a term in every document, although it is 1,000 times rarer. The formula uses a logarithm, and scikit-learn computes it for you.
After the multiplication, each row is scaled so that its size, measured as its L2 norm, is 1. A 2,000-word review and a 50-word review that use their words in the same proportions end up with the same row. That corrects the length problem.
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=2, max_df=0.9, sublinear_tf=True)
X_train = vectorizer.fit_transform(train_texts)
X_test = vectorizer.transform(test_texts)
TfidfVectorizer takes the same ngram_range, min_df and max_df parameters as CountVectorizer. fit learns the vocabulary and the IDF of every term from the training documents, and transform uses both unchanged on new documents.
sublinear_tf=True replaces each count with a smaller number that grows slowly: a count of 1 stays 1, 10 becomes 3.3, and 100 becomes 5.6. A word used 10 times in one review then counts 3.3 times as much as a word used once, instead of 10 times, so one long review that repeats a word does not dominate that word’s column.
Which one to use depends on the model. Multinomial Naive Bayes is built to model how often each word appears, so it takes the counts from CountVectorizer as they are. Linear models such as logistic regression usually get TF-IDF, which fixes the length and common-word problems before the model sees the data.
Preparing New Messages
A trained model only works on text prepared exactly like its training data. If training stemmed claiming to claim and prediction does not, the new message’s claiming matches no column. Every step, in the same order, has to run again before each prediction:
def preprocess_message(message):
message = message.lower()
message = re.sub(r"[^a-z\s$!]", "", message)
tokens = word_tokenize(message)
tokens = [w for w in tokens if w not in stop_words]
tokens = [stemmer.stem(w) for w in tokens]
return " ".join(tokens)
Keeping a separate copy of the steps for prediction means two copies that have to stay identical. Putting the preparation inside a scikit-learn pipeline keeps one copy, which runs at both training and prediction.
A pipeline that includes a custom function, such as preprocess_message inside a FunctionTransformer, saves only the function’s name, as described in Saving a model. Loading it on another machine fails unless the same function is defined there. When the model will be loaded somewhere else, such as a service that scores submitted models, the vectorizer’s built-in options can do much of the preparation instead: lowercase=True (the default), strip_accents="unicode", stop_words, token_pattern and ngram_range. A pipeline made only of a vectorizer and a model needs nothing but scikit-learn to load.