Concepts / Tokenization in Text Processing

Tokenization in Text Processing

Bag-of-Words processing runs three stages in order: tokenization, vocabulary building, and encoding.

  • Programming
Interactive lab

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

  1. Standardize: lowercase and delete punctuation.
  2. Split on whitespace into tokens.
  3. Build the vocabulary: 0 = padding, 1 = [UNK], then words by frequency (ties: first appearance), capped at max tokens.
  4. Map each token to its id (1 if it did not make the vocabulary), then pad with 0 or truncate to the sequence length.
  5. 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.

Educational simulation

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?

  • Yes, the vectors are identical

  • No, the word order makes them differ

Reveal answer
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.

Raw documentstext stringsTokenizationdocuments to tokensVocabulary buildingtokens to one numbered listEncodingtokens plus vocabulary tocountsCount vectorsone vector per documententerstoken listsshared listcounts
What each stage receives and produces, and the order in which the stages run so that each output feeds the next.

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.

Worked example

Tokenizing 'the cat sat'

Split the document 'the cat sat' into tokens.

  1. 1
    Identify the separators

    The document contains spaces between its words, so whitespace is the separator that divides it.

  2. 2
    Split on the spaces

    Splitting on the spaces produces three pieces: the, cat, and sat.

  3. 3
    Keep the tokens

    Each piece is now one token. The document is no longer a single string with an order to it.

Result

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.

Worked example

Building a Vocabulary from Two Documents

Build the shared vocabulary for the documents 'the cat sat' and 'the dog sat down'.

  1. 1
    Tokenize the first document

    'the cat sat' yields the, cat, and sat.

  2. 2
    Tokenize the second document

    'the dog sat down' yields the, dog, sat, and down.

  3. 3
    Merge the token lists

    The word the appears in both documents, but it occupies a single slot in the vocabulary rather than two.

  4. 4
    Sort alphabetically

    Sorting the distinct words gives a fixed order that every document will share.

Result

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.

catfeature 0dogfeature 1downfeature 2satfeature 3thefeature 4
Each unique word in the whole dataset occupies one fixed position, and every document's vector uses these same positions.

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.

Worked example

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.

  1. 1
    Read the vocabulary order

    The five features are cat, dog, down, sat, and the, in that order.

  2. 2
    Count the first document

    'the cat sat' contains cat once, dog zero times, down zero times, sat once, and the once.

  3. 3
    Count the second document

    'the dog sat down' contains cat zero times, dog once, down once, sat once, and the once.

  4. 4
    Write 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.

Result

'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.

cat: 1cat: 1cat: 2sat: 1sat: 1sat: 1
Two documents with the same words in a different order produce identical counts, while a document with a different word count produces different counts.

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 like

    Giving 'the cat sat' a vocabulary of cat, sat, the and 'the dog sat down' a vocabulary of dog, down, sat, the.

    Why it fails

    Each 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 instead

    Build one vocabulary from all documents and use it to encode every document.

  • Common mistake

    Skipping or inconsistent tokenization of punctuation

    What it looks like

    Leaving 'sat.' as a single token in one document while tokenizing 'sat' plainly in another.

    Why it fails

    Tokenization 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 instead

    Apply 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 like

    Counting 'The' and 'the' as two separate vocabulary words.

    Why it fails

    If 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 instead

    Decide 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 like

    Assuming 'dog sat down' and 'down sat dog' give different vectors because the sentences look different.

    Why it fails

    After tokenization the document is a bag of words, so the order is not part of the vector at all.

    Do this instead

    Treat 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 like

    Writing a four-number vector for 'the dog sat down' when the vocabulary has five words.

    Why it fails

    Each 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 instead

    Check that every vector has exactly as many entries as the vocabulary has words.

Tracing a New Document Set

MEDIUM

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

  1. 1
    Bag-of-Words processing runs three stages in order: tokenization, vocabulary building, and encoding, and each stage uses the output of the one before it.
  2. 2
    Tokenization 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.
  3. 3
    Vocabulary building merges every distinct word from all documents into one shared, numbered list, so each unique word gets a fixed feature position.
  4. 4
    Encoding 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.
  5. 5
    Word 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.

Related concepts

More concepts starting with T