Artificial Intelligence • AI Application Domains • 17 min read

Text Processing, Tokenization, and Embeddings

Start with an example: From a sentence to numbers

Take the sentence “Cats chase birds.” A computer can store those characters, but a machine-learning model needs a representation it can operate on. One approach divides the sentence into tokens, assigns token IDs, then uses numerical features or learned vectors to represent the tokens.

For example, a tokenizer might produce ['Cats', 'chase', 'birds', '.']. Another tokenizer might split a word into smaller pieces. Neither result is a universal or linguistically perfect word boundary. The token IDs are just identifiers; they are not embeddings and do not by themselves represent meaning.

An embedding is a learned or constructed vector associated with a token, sentence, or document. Similar concepts may end up near each other in the representation space, depending on the model and training task. That makes embeddings useful for retrieval and similarity, but proximity is not proof that two texts have identical meaning.

Natural language processing (NLP) systems must turn written language into a representation that an algorithm can use. Computers can store text as character sequences, but most machine-learning methods operate on numbers. Text processing prepares language data, tokenization divides it into meaningful or computationally useful units, and text representations convert those units into numerical features. Embeddings are one important kind of numerical representation.

These are connected stages, but they are not interchangeable: cleaning text does not itself identify tokens, token identifiers are not semantic vectors, and an embedding does not guarantee that a system understands a sentence correctly.

1. The text-to-numbers pipeline

A typical NLP workflow is:

  1. Collect a sentence or document from a defined source.
  2. Normalize or clean the text as appropriate for the task.
  3. Tokenize it into words, subwords, characters, or other units.
  4. Map tokens to vocabulary identifiers or construct numerical features.
  5. Pass the resulting representation to an algorithm or model.
  6. Evaluate whether the model performs the intended task correctly.
Text processing pipeline from raw sentence through normalization, tokenization, numerical representations, and a model
A simplified NLP pipeline. Some modern systems combine preprocessing and tokenization, and the exact representation depends on the model.

Example: In an email spam classifier, the final model may receive a sparse vector representing word frequencies. In a Transformer language model, text is usually converted into subword token IDs, which are then looked up in a learned embedding table. Both begin with text but use different representations.

2. Text preprocessing

Text preprocessing is the set of transformations used to make raw text suitable for a specific computational task. It may correct input inconsistencies, remove unwanted artifacts, or standardize representations. There is no universally correct cleaning procedure: a transformation helpful for one task may destroy information required by another.

2.1 Common operations

OperationMeaningExample or caution
Unicode normalizationStandardizes equivalent character encodings.A visibly identical character may have more than one underlying encoding.
Whitespace normalizationMakes spacing consistent when spacing is not meaningful.Multiple spaces become one space.
Case normalizationConverts text to a consistent case.Apple becomes apple, potentially losing a company-name cue.
Punctuation handlingKeeps, removes, or separates punctuation.A question mark can signal a question; apostrophes affect contractions.
URL and markup handlingRemoves, extracts, or replaces HTML and URLs.A URL may itself be relevant in phishing detection.
Stop-word removalRemoves frequent words from some feature representations.Removing not can reverse sentiment.
StemmingReduces words to heuristic stems.connected may become connect.
LemmatizationMaps inflected forms to dictionary base forms using linguistic analysis.running can map to run depending on context.
Language identificationDetects the language or languages present.A multilingual message may require different processing choices.

Stemming and lemmatization are different. Stemming uses reduction rules and can produce forms that are not dictionary words. Lemmatization aims for a linguistically valid base form and may depend on part-of-speech information.

2.2 Why aggressive cleaning can be harmful

Consider the following messages:

  • I like this product.
  • I do not like this product.
  • I LIKE this product!!!

Removing stop words may delete not, losing negation. Deleting all punctuation and casing may discard intensity cues. For a modern pretrained Transformer, changing the text substantially can also make the input less like the data used during pretraining.

As a practical rule, start with the least destructive preprocessing that solves a demonstrated data-quality problem. Measure the effect using validation data instead of assuming that more cleaning always improves performance.

2.3 A small Python preprocessing example

import re
import unicodedata


def normalize_text(text: str) -> str:
    # Keep words, punctuation, and letter case intact.
    text = unicodedata.normalize("NFC", text)
    return re.sub(r"\s+", " ", text).strip()


message = "  Natural   language\nprocessing is useful!  "
print(normalize_text(message))
# Natural language processing is useful!

This function normalizes Unicode and whitespace only. It is a preparation step, not a complete tokenizer.

3. Tokenization

Tokenization is the process of segmenting text into units called tokens. A token may be a word, part of a word, a character, punctuation, or a special marker, depending on the tokenizer.

For Machine learning is useful!, a simple word-and-punctuation tokenizer could output:

["Machine", "learning", "is", "useful", "!"]

A subword tokenizer might split a long or uncommon word into several pieces. Those splits depend on the tokenizer’s learned vocabulary; there is no single universal sequence of subword tokens.

3.1 Types of tokenization

TypeUnitsStrengthsLimitations
Word-levelComplete words or word-like segmentsIntuitive for many traditional NLP tasksLarge vocabulary; difficulties with rare or new words
Subword-levelWhole common words and fragments of less common wordsBalances vocabulary size and coverageSplits can be unintuitive; vary by tokenizer
Character-levelIndividual characters or code pointsCan represent unfamiliar spellingsLonger sequences; semantic patterns are harder to learn directly
Byte-levelIndividual bytes, sometimes merged into larger unitsBroad coverage of input encodingsTokens may not align with visible characters or words

The appropriate method depends on the language, model, dataset, and computational budget. Languages without consistent spaces between words, code-mixed text, and multilingual documents need special attention.

3.2 Subword tokenization

Modern language models commonly use subword tokenization. Typical algorithm families include Byte Pair Encoding (BPE), WordPiece, and Unigram language-model tokenization. They build or use a limited vocabulary that can represent many words through combinations of tokens.

For example, an illustrative tokenizer could encode unhappiness as:

["un", "happi", "ness"]

This is not a claim about the exact output of any specific model. Token boundaries depend on the tokenizer and its vocabulary.

3.3 Token vocabulary and token IDs

A vocabulary is a mapping between tokens and numeric identifiers. Suppose a tiny illustrative vocabulary contains:

TokenID
[PAD]0
[UNK]1
machine2
learning3
helps4

The text machine learning helps can then become [2, 3, 4].

Token IDs are categorical labels, not measurements. ID 4 is not twice the meaning of ID 2. A model needs a representation such as one-hot features or learned embeddings to work with these identities.

Special tokens depend on the model. Examples include padding markers, beginning- or end-of-sequence markers, and unknown-token markers. Not every tokenizer uses all of them.

3.4 Token count is not word count

A single word may correspond to several tokens, while a punctuation mark may be its own token. Token counts affect context-window limits, memory use, processing time, and sometimes API billing. To measure token count, use the tokenizer of the particular model rather than estimating directly from the number of words.

4. Traditional numerical text representations

A text representation converts a document into features a model can process. Traditional methods often produce sparse vectors: vectors with many zeros, especially when the vocabulary is large.

4.1 One-hot representation

A one-hot vector has one 1 at the position corresponding to a token and 0 elsewhere. With the vocabulary [cat, dog, bird], dog becomes:

xdog=[0,1,0]\mathbf{x}_{\text{dog}} = [0,1,0]

This represents token identity but provides no built-in measure of semantic similarity. The vector length also grows with vocabulary size.

4.2 Bag-of-words

Bag-of-words (BoW) represents each document through counts or presence indicators for vocabulary terms. It generally ignores token order.

For the vocabulary [cats, chase, mice]:

Documentcatschasemice
cats chase mice111
mice chase cats111

Both produce the same count vector, even though their meaning can differ. This is the key limitation of ignoring order.

4.3 N-grams

An n-gram is a contiguous sequence of nn units, often words or characters. Word bigrams for cats chase mice are cats chase and chase mice. Adding n-grams can preserve some local order, but increases the possible feature space.

4.4 TF-IDF

Term Frequency–Inverse Document Frequency (TF-IDF) weights terms using their frequency within a document and how common they are across a collection. The idea is to reduce the relative impact of words occurring in nearly every document while retaining terms that help distinguish documents.

A common conceptual form is:

TFIDF⁡(t,d)=TF⁡(t,d)×IDF⁡(t)\operatorname{TFIDF}(t,d) = \operatorname{TF}(t,d) \times \operatorname{IDF}(t)

Different libraries use slightly different formulas, smoothing, and normalization. TF-IDF captures useful lexical patterns but does not inherently understand synonyms or sentence meaning.

5. What is a text embedding?

An embedding is a learned or constructed numerical vector representing an item in a continuous vector space. Text embeddings may represent tokens, words, sentences, passages, or whole documents.

For example, a hypothetical model might assign the word cat a vector:

ecat=[0.12,−0.44,0.81,0.07]\mathbf{e}_{\text{cat}} = [0.12, -0.44, 0.81, 0.07]

The four values here are illustrative and are not taken from a real embedding model. Production embeddings usually have many more dimensions. The individual dimensions generally do not correspond to simple human-readable concepts.

Embedding models attempt to place items with useful relationships near one another according to their training objective. Closeness is task-dependent, however: two texts can be topically similar without making equivalent claims.

5.1 Static word embeddings

A static word embedding assigns a word (or vocabulary item) a fixed vector regardless of the surrounding sentence. Well-known methods include Word2Vec and GloVe.

This is useful but limited for ambiguous words. In river bank and bank account, the token bank may receive the same static vector even though the intended meanings differ.

5.2 Contextual embeddings

A contextual embedding depends on the surrounding tokens. Transformer-based models can produce different representations for bank in the two sentences above.

Contextual embeddings are a core part of modern language models. The final representation may be a token vector from an intermediate layer, a pooled document vector, or an output from a model specifically trained to embed sentences.

5.3 Token embeddings versus sentence embeddings

RepresentationMain unitCommon use
Token embeddingIndividual tokenInput to a language model or contextual processing
Contextual token embeddingToken within a particular sequenceSequence labeling, language understanding
Sentence embeddingSentence or short passageSemantic search, similarity, clustering
Document embeddingLonger passage or documentRetrieval, organization, recommendation

Do not assume that averaging arbitrary language-model token embeddings always produces a strong sentence embedding. Models trained specifically for similarity or retrieval often perform better on those tasks.

6. The embedding layer in a neural network

A neural network commonly stores token embeddings in a matrix:

E∈RV×dE \in \mathbb{R}^{V \times d}

where VV is the vocabulary size and dd is the embedding dimension. For token ID ii, the embedding is row EiE_i.

If V=10,000V=10{,}000 and d=128d=128, the table contains 1,280,0001{,}280{,}000 scalar values. During training, a learned embedding table can be updated through gradient-based optimization along with other model parameters.

Token identifiers look up rows in an embedding table and return fixed-length vectors
An embedding lookup selects a row of learned numbers. The example values are illustrative, not semantic scores.

Position information is typically added or otherwise incorporated later because a basic embedding lookup by itself does not encode word order. Learn more in The Transformer Architecture.

7. Measuring similarity between embeddings

Two commonly used measures are the dot product and cosine similarity. For nonzero vectors a\mathbf{a} and b\mathbf{b}, cosine similarity is:

cosine⁡(a,b)=a⋅b∥a∥2 ∥b∥2\operatorname{cosine}(\mathbf{a},\mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\|_2\,\|\mathbf{b}\|_2}

It ranges from −1-1 to 11 for real-valued vectors and measures the angle between them. For a particular embedding system, greater cosine similarity may indicate greater semantic relatedness, but the score is not automatically a calibrated probability of relevance.

Example: A semantic search system can embed a user query and candidate passages, compare their vectors, retrieve high-scoring passages, and optionally rerank them. Accuracy depends on the embedding model, domain, chunking, and evaluation data. See Information Retrieval and Search.

8. Practical Python examples

8.1 Tokenize and build TF-IDF features

This example uses scikit-learn’s default word-level tokenizer, which lowercases text and, by default, ignores single-character tokens and punctuation. It demonstrates one tokenizer, not a model-independent definition of tokens.

from sklearn.feature_extraction.text import TfidfVectorizer

texts = [
    "Machine learning uses data.",
    "Language models learn from text data.",
    "Machine translation processes language.",
]

vectorizer = TfidfVectorizer()
features = vectorizer.fit_transform(texts)

print("Vocabulary:", vectorizer.get_feature_names_out().tolist())
print("Matrix shape:", features.shape)
print("First document vector:", features[0].toarray().round(3))

Each row corresponds to a document and each column to a vocabulary term. Fit the vocabulary and IDF weights only on training data in a real ML experiment. Validation and test data should be transformed with the already fitted vectorizer to avoid data leakage.

8.2 Compare vectors using cosine similarity

import numpy as np

query = np.array([1.0, 1.0, 0.0])
passage = np.array([2.0, 2.0, 0.0])
unrelated = np.array([0.0, 0.0, 1.0])


def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
    denominator = np.linalg.norm(a) * np.linalg.norm(b)
    if denominator == 0:
        raise ValueError("Cosine similarity is undefined for zero vectors")
    return float(np.dot(a, b) / denominator)


print(round(cosine_similarity(query, passage), 3))   # 1.0
print(round(cosine_similarity(query, unrelated), 3))  # 0.0

These small, manually chosen vectors illustrate the mathematics; they are not embeddings produced by a language model.

8.3 Look up embeddings using PyTorch

import torch

# Vocabulary: five tokens, each represented by four learned values.
embedding = torch.nn.Embedding(num_embeddings=5, embedding_dim=4)
ids = torch.tensor([[2, 3, 4], [1, 2, 0]])

vectors = embedding(ids)
print(ids.shape)      # torch.Size([2, 3])
print(vectors.shape)  # torch.Size([2, 3, 4])

The output shape is [batch_size, sequence_length, embedding_dimension]. Initially the table contains randomly initialized trainable parameters. These are not pretrained semantic embeddings until they have been trained for a meaningful objective.

9. Choosing a representation

NeedReasonable starting pointWhat to test
Small labeled text classification datasetTF-IDF with logistic regression or a linear SVMBaseline accuracy, class balance, sparse features
Keyword-driven document matchingLexical retrieval such as TF-IDF or BM25Exact-match recall, domain vocabulary
Semantic search with paraphrasesA suitable pretrained sentence-embedding modelRetrieval relevance, multilingual support, latency
Sequence labeling or context-sensitive text tasksContextual Transformer representationsToken alignment, context length, labeled performance
Resource-constrained deploymentSmaller sparse or compact embedding representationsMemory, speed, quality trade-offs

The most complicated representation is not necessarily the best. A well-evaluated TF-IDF classifier can outperform an unadapted embedding pipeline on some small, task-specific datasets.

10. Common mistakes and limitations

  • Confusing tokens with words: token splits and token counts vary by model.
  • Interpreting token IDs as numeric magnitudes: IDs are vocabulary indices only.
  • Assuming preprocessing is always beneficial: removing negation, punctuation, or capitalization can harm performance.
  • Assuming embeddings contain factual truth: nearby vectors can represent similar wording even when the claims conflict.
  • Comparing vectors from different embedding models directly: dimensions and coordinate spaces may not be compatible.
  • Fitting a vectorizer before the train/test split: vocabulary and IDF statistics can leak information from evaluation data.
  • Ignoring language and domain differences: an English general-purpose model may perform poorly on specialized vocabulary or multilingual text.
  • Ignoring input length: truncation may remove crucial context, and long documents often require chunking or a different architecture.

Representations can also capture social biases, sensitive attributes, and private information present in training data. Evaluate them with representative data and the intended deployment context.

11. How these ideas connect

The three core ideas serve different roles:

QuestionConcept
How should inconsistent input be prepared?Text processing
What units should the system recognize?Tokenization
How can those units be represented numerically?Feature extraction or embeddings
How can context change a token’s representation?Contextual modeling
How can related passages be retrieved?Similarity search and information retrieval

For example, a document-retrieval pipeline could normalize documents, tokenize them with a specified embedding model’s tokenizer, create passage embeddings, build an index, and retrieve candidates for a query. An NLP classifier could instead create TF-IDF features and train a simple predictive model. Their early steps overlap but their objectives and evaluation metrics differ.

12. Practice exercises

  1. Compare the effects of lowercasing and removing punctuation on a dataset containing proper names, negations, and sentiment labels.
  2. Use TfidfVectorizer to inspect the most heavily weighted terms in three short documents. Explain why the values depend on the complete corpus.
  3. Write a small vocabulary mapping and convert a token list into IDs. Explain why the IDs do not express semantic distance.
  4. Calculate cosine similarity for two vectors by hand and verify it using NumPy.
  5. Investigate the tokenizer of one specific pretrained model and compare its token count with the number of words in the same sentence.
  6. Compare a TF-IDF baseline with sentence embeddings for a small search task, using held-out queries and relevance judgments.

Some related routes belong to the planned knowledge map and may not yet be published.

14. References and further reading

Related articles in

Image preview

Fit