Tokens and N-grams in Text Processing
Inspecting the tokens and n-grams that are extracted can give powerful insights into the modeling process, and in text processing it is often possible to introspect models meaningfully for both supervised and unsupervised tasks.
The Model Only Sees Numbers
Imagine you are asked to build a filter that flags spam emails, or one that decides whether a movie review is positive or negative. The learning algorithm you plan to use only accepts numbers. It has no direct way to take in a sentence such as 'Great film, I loved the ending.' Something has to turn that sentence into numbers first. That step is called data representation.
The choice of representation sits between the raw text and the model, so it decides what information the model is allowed to see. The course material makes a general point that applies here: as is often the case in machine learning, the representation of the data is key in NLP applications. The same review can be turned into different sets of numbers, and a model that learns from one set may succeed or fail because of the representation rather than the learning algorithm itself.
What do you think happens?
Do the reviews 'not good' and 'good not' produce the same bag-of-words counts?
Reveal answer
Yes, both produce the counts good 1 and not 1.
A bag-of-words representation records which tokens occur and how often, but not the order they appeared in. Reordering the same tokens leaves the counts unchanged, so the two reviews look identical to the model even though 'not good' and 'good not' are not the same way of writing a sentence.
Tracing a Review from Text to Token Counts
A bag-of-words representation starts by splitting text into tokens, which are the units the representation counts. In this article, a token is a lowercase word with punctuation removed. The representation then records each distinct token and how many times it appears. The result is a bag: a collection of words with counts, and nothing that says where each word sat in the sentence.
Follow the steps by hand on one short review: 'Boring plot, boring acting, great ending'. Each step changes the text, and the next step works on the result of the previous one.
Counting the tokens in one review
Build a bag-of-words representation for the review 'Boring plot, boring acting, great ending'.
- 1Lowercase the text
Every letter becomes lowercase, so the review reads: boring plot, boring acting, great ending
- 2Remove punctuation
The comma after plot is removed, leaving: boring plot boring acting great ending
- 3Split on spaces
The text is split into six tokens in this order: boring, plot, boring, acting, great, ending
- 4Count each distinct token
The token boring appears twice. Each of plot, acting, great, and ending appears once.
The bag contains boring 2, plot 1, acting 1, great 1, ending 1. These counts, not the original sentence, are what the model receives.
Notice that the six tokens collapse into five keys. The repeated token boring is stored once with a count of 2. This is what it means for the representation to count distinct tokens: the model learns a fixed table of words and how often each one occurred in the review.
What a Bag Keeps and What It Discards
A bag-of-words representation keeps which tokens occur and how often. It does not keep the order of the tokens. This is the trade-off behind its simplicity. Two texts with the same words in different orders end up with identical counts, so the representation cannot tell them apart.
Whether that loss matters depends on the task. For many classification problems, a strong signal such as repeated words like boring may be enough. This is consistent with the source's description of bag-of-words as a simple and powerful solution for text classification tasks such as spam and fraud detection and sentiment analysis.
Sliding Windows and Recovering Local Order
An n-gram is a run of n consecutive tokens. A window of size n slides across the token sequence one position at a time, and each position produces one n-gram. A bigram, with n equal to 2, keeps a small piece of local order that a single-token count throws away.
Notice what this list reveals. The bigrams 'boring plot' and 'boring acting' record that boring is adjacent to other words, while a single-token bag only knows that boring appeared twice. Inspecting a list like this is a direct way to check that the extracted pieces match your expectations for the text.
| Unit | n | Units produced from six tokens | Example from the review |
|---|---|---|---|
| Unigram | 1 | 6 | boring, plot, boring, acting, great, ending |
| Bigram | 2 | 5 | boring plot, plot boring, boring acting, acting great, great ending |
| Trigram | 3 | 4 | boring plot boring, plot boring acting, boring acting great, acting great ending |
Unit counts for the review 'Boring plot, boring acting, great ending' using the formula N = T - n + 1 with T = 6
As n grows, each unit covers more of the sentence and captures more local order, but the number of distinct units also tends to grow. The representation becomes more specific, which can help when a short phrase carries the signal.
Inspecting Tokens for Task Fit
The course material makes a point that goes beyond choosing a representation: inspecting the tokens and n-grams that are extracted can give powerful insights into the modeling process. Looking at these pieces directly lets you see what the model is actually being given, which is often different from what you assumed when you wrote the preprocessing code.
Consider the review 'Not boring at all'. Lowercasing and removing punctuation gives the tokens not, boring, at, all. A unigram bag records boring once and not once, which looks like a negative cue. The bigram 'not boring' keeps the adjacency that tells the model the negation applies to boring.
Tokenize the review 'Great film, I loved the ending.' by lowercasing it, removing punctuation, and splitting on spaces. Then list its bigrams. Check whether the bigrams contain any sentiment cue that a single-token bag would only show as a standalone word.
Hints
- Remove the comma and the period before splitting on spaces
- Six tokens produce five bigrams when you slide a window of size 2
- Ask whether any bigram joins a sentiment word to a word that could change its meaning
Mistakes When Reading Token Lists
Common mistake Counting the raw sentence instead of the normalized tokens
What it looks likeTreating 'Boring' and 'boring,' as two different tokens
Why it failsWithout lowercasing and punctuation removal, the same word is split across several keys and its count is understated.
Do this insteadLowercase the text and remove punctuation before counting tokens.
Common mistake Assuming a bag-of-words count preserves meaning carried by order
What it looks likeBelieving 'not good' and 'good not' are represented differently
Why it failsA bag keeps counts and discards order, so both sequences produce the same counts.
Do this insteadInspect bigrams when adjacency matters, or accept that the representation cannot separate reorderings.
Common mistake Forgetting that n-gram counts depend on the window size
What it looks likeExpecting six bigrams from a six-token review
Why it failsA window of size 2 over six tokens produces five positions, not six.
Do this insteadUse N = T - n + 1, so the bigram count is 6 - 2 + 1 = 5.
Common mistake Trusting the representation without inspecting the extracted tokens and n-grams
Key Takeaways
- A model can only learn from numbers, so the representation chosen for text decides what information it can use.
- A bag-of-words representation splits text into lowercase tokens with punctuation removed, then records each distinct token and its count.
- A bag keeps which tokens occur and how often, but discards word order, so reorderings such as 'not good' and 'good not' look identical.
- An n-gram is a run of n consecutive tokens; bigrams and trigrams recover some local order, and a sequence of T tokens yields T - n + 1 n-grams of size n.
- Inspecting the extracted tokens and n-grams shows what the model actually receives and whether it contains the cues a task needs.