Tokenization in Text Processing
Bag-of-Words processing runs three stages in order: tokenization, vocabulary building, and encoding.
Try it: Text Vectorization: Tokens to Vectors
The text-to-tensor pipeline: standardize, split into tokens, build a frequency-ranked vocabulary with padding and [UNK], map tokens to integer ids, pad or truncate, then one-hot or multi-hot encode and look the ids up in an embedding table.
How it works
- Standardize: lowercase and delete punctuation.
- Split on whitespace into tokens.
- Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
- Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
- Encode: one-hot rows per position or one multi-hot row per text; embed: id k selects row k of the embedding table.
Default run (18 steps): Raw text (59 characters): "The movie was great. The plot was great, the acting wasn't!". A model cannot read strings, so it is turned into numbers step by step. … Embedding lookup: id k selects row k of a fixed 8 x 3 table, giving a (8, 3) dense matrix instead of (8, 8) sparse one-hots. Row 0 (padding) is looked up too; a trained Embedding layer would learn these rows.
Simplified: Bounded ASCII text (up to 200 characters, 40 tokens), whitespace splitting only, and a small FIXED embedding table (a real Embedding layer learns its rows). The multi-hot vector keeps the padding slot (always 0) so its positions line up with the ids.
Loading the simulation…
Why Text Must Become Numbers
Machine learning models work with numbers, but much of the data we care about is text: emails, product reviews, news articles. A model cannot read a sentence the way a person does, so the text has to be converted into a numeric form first.
Bag-of-Words processing is a method for converting a collection of text documents into numeric form. It does this in a fixed sequence of steps, and the output of the whole sequence is a numeric vector for every document. In this article you will follow a document from the moment it enters the process until it leaves as a list of numbers, and you will see exactly which information is kept and which is thrown away along the way.
What do you think happens?
Do the documents 'the dog sat down' and 'down sat dog the' produce the same count vector?
Reveal answer
Yes, the vectors are identical
Bag-of-Words keeps only how often each vocabulary word appears in a document. Both sentences contain the same four words, each once, so their count vectors match even though the word order is reversed. Losing word order is an intended property of the representation, and it is also its main limitation.
The Three Stages in Order
Bag-of-Words processing has three stages, and each one depends on the output of the stage before it. The first stage is tokenization, which breaks each document into individual words. The second stage is vocabulary building, which looks across all of the documents and gathers every distinct word into one shared, numbered list. The third stage is encoding, which uses that shared list to count how often each vocabulary word appears in each document. The final output is one vector of counts per document.
The order matters. Vocabulary building cannot start until tokenization has produced token lists for every document, and encoding cannot count anything until the shared vocabulary exists. Each stage consumes exactly what the previous stage produced.
Stage One: Tokenization
Tokenization splits each document into tokens, usually by splitting on whitespace and punctuation. A token is the unit that the rest of the process works with. Tokenization is the first step in Bag-of-Words processing, and everything that follows works with these tokens rather than with the original sentence.
Tokenizing 'the cat sat'
Split the document 'the cat sat' into tokens.
- 1Identify the separators
The document contains spaces between its words, so whitespace is the separator that divides it.
- 2Split on the spaces
Splitting on the spaces produces three pieces: the, cat, and sat.
- 3Keep the tokens
Each piece is now one token. The document is no longer a single string with an order to it.
Three tokens: the, cat, and sat
Notice what the tokens are no longer doing. After this stage, the document is a collection of words rather than a sequence, which is the reason the method is called a bag of words. A bag holds its items without any arrangement, and that is exactly the state the document is in once tokenized.
Stage Two: Building the Shared Vocabulary
Vocabulary building takes the token lists from every document and collects every distinct word into one numbered list. This single list is shared by all of the documents. Each distinct word gets exactly one entry, no matter how many documents contain it.
Building a Vocabulary from Two Documents
Build the shared vocabulary for the documents 'the cat sat' and 'the dog sat down'.
- 1Tokenize the first document
'the cat sat' yields the, cat, and sat.
- 2Tokenize the second document
'the dog sat down' yields the, dog, sat, and down.
- 3Merge the token lists
The word the appears in both documents, but it occupies a single slot in the vocabulary rather than two.
- 4Sort alphabetically
Sorting the distinct words gives a fixed order that every document will share.
Vocabulary: cat, dog, down, sat, the (five unique words, so every vector will have five features)
The sorted list gives each vocabulary word a fixed position. Position 0 is cat, position 1 is dog, position 2 is down, position 3 is sat, and position 4 is the. Those positions are what the next stage will use to lay out the counts.
Stage Three: Encoding Count Vectors
Encoding counts how often each vocabulary word appears in a document. The result is one count vector per document, with one feature for each unique word in the shared vocabulary. To encode a document, walk through the vocabulary in its fixed order and write down how many times each word occurs in that document. A word that does not appear gets a count of zero.
Encoding Both Documents
Produce the count vector for 'the cat sat' and for 'the dog sat down' using the vocabulary cat, dog, down, sat, the.
- 1Read the vocabulary order
The five features are cat, dog, down, sat, and the, in that order.
- 2Count the first document
'the cat sat' contains cat once, dog zero times, down zero times, sat once, and the once.
- 3Count the second document
'the dog sat down' contains cat zero times, dog once, down once, sat once, and the once.
- 4Write each vector in feature order
Each document's counts are written in the same five-position order, so the positions line up feature-by-feature.
'the cat sat' gives [1, 0, 0, 1, 1]; 'the dog sat down' gives [0, 1, 1, 1, 1]
Why Every Vector Lines Up
Each position in a document's vector is a feature, and each feature corresponds to one unique word from the whole dataset. The feature for a given word therefore means the same thing in every document. The first feature always refers to the same vocabulary word, and so does the last. This shared meaning is what lets a model compare documents, because every document is measured on the same set of word features.
This is also why the vocabulary must be built once, from all of the documents, rather than separately for each one. A document's vector has length equal to the number of unique words in the whole dataset, not the number of unique words in that document alone. In the two-document example, both vectors have five features, even though 'the cat sat' contains only three distinct words.
Where Word Order Goes
Look again at the second document. Its word order, dog then sat then down, is gone from the vector. The vector only records that dog, sat, and down each appear once. This is the intended behavior of the representation, and it is also its main limit: two sentences that differ only in word order produce identical vectors.
In the comparison, 'cat sat' and 'sat cat' both produce the vector with cat at 1 and sat at 1, so the two are indistinguishable to the model. The document 'cat cat sat' differs because the count for cat changes to 2, so its vector is different. Word order is discarded, but word counts are kept.
Common Mistakes Behind Wrong Vectors
Common mistake Building a separate vocabulary for each document
What it looks likeGiving 'the cat sat' a vocabulary of cat, sat, the and 'the dog sat down' a vocabulary of dog, down, sat, the.
Why it failsEach document then has its own feature list, so position 0 means a different word in each document and the vectors cannot be compared feature-by-feature.
Do this insteadBuild one vocabulary from all documents and use it to encode every document.
Common mistake Skipping or inconsistent tokenization of punctuation
What it looks likeLeaving 'sat.' as a single token in one document while tokenizing 'sat' plainly in another.
Why it failsTokenization is meant to split on whitespace and punctuation, so 'sat.' and 'sat' become two different vocabulary entries for the same word, and the counts are split between them.
Do this insteadApply the same splitting rules to every document so the same word always produces the same token.
Common mistake Treating different casing as different words
What it looks likeCounting 'The' and 'the' as two separate vocabulary words.
Why it failsIf the two spellings are not treated as the same token, the vocabulary gains an extra feature and the count for the word is divided between two positions.
Do this insteadDecide on one casing convention before building the vocabulary and apply it to all documents.
Common mistake Expecting word order to be preserved
What it looks likeAssuming 'dog sat down' and 'down sat dog' give different vectors because the sentences look different.
Why it failsAfter tokenization the document is a bag of words, so the order is not part of the vector at all.
Do this insteadTreat the vector as a record of word counts only, and do not rely on it to represent sequence.
Common mistake Using a vector length that does not match the vocabulary
What it looks likeWriting a four-number vector for 'the dog sat down' when the vocabulary has five words.
Why it failsEach vector needs one feature per unique word in the whole dataset, so a shorter vector drops words and a longer one invents features.
Do this insteadCheck that every vector has exactly as many entries as the vocabulary has words.
Tracing a New Document Set
Work through the three documents 'the dog sat', 'the cat ran', and 'the dog ran'. First tokenize each one, then build the shared vocabulary, then write the count vector for each document in the sorted feature order.
Hints
- Tokenize each document by splitting on the spaces so that every word becomes its own token.
- Collect the distinct words from all three documents, keeping the word the only once, and sort them alphabetically.
- Each vector should have one entry per vocabulary word, and a word that does not appear in a document gets a zero.
Summary of the Process
- 1Bag-of-Words processing runs three stages in order: tokenization, vocabulary building, and encoding, and each stage uses the output of the one before it.
- 2Tokenization splits each document into tokens, usually on whitespace and punctuation, and the rest of the process works with those tokens rather than the original sentence.
- 3Vocabulary building merges every distinct word from all documents into one shared, numbered list, so each unique word gets a fixed feature position.
- 4Encoding counts how often each vocabulary word appears in each document, producing one vector per document with one feature per unique word in the whole dataset.
- 5Word order is discarded by the representation, so documents that differ only in order produce identical vectors.
At a glance
- Bag-of-Words processing runs tokenization, then vocabulary building, then encoding, and each stage depends on the output of the previous one.
- The shared vocabulary gives every unique word in the whole dataset one fixed feature position, so all document vectors line up feature-by-feature.
- Each document's vector is a count of vocabulary words, which means word order is lost and documents that differ only in order look identical.
- Mistakes such as inconsistent casing, unstripped punctuation, or a separate vocabulary per document produce vectors that cannot be correctly compared.