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:
- Collect a sentence or document from a defined source.
- Normalize or clean the text as appropriate for the task.
- Tokenize it into words, subwords, characters, or other units.
- Map tokens to vocabulary identifiers or construct numerical features.
- Pass the resulting representation to an algorithm or model.
- Evaluate whether the model performs the intended task correctly.
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
| Operation | Meaning | Example or caution |
|---|---|---|
| Unicode normalization | Standardizes equivalent character encodings. | A visibly identical character may have more than one underlying encoding. |
| Whitespace normalization | Makes spacing consistent when spacing is not meaningful. | Multiple spaces become one space. |
| Case normalization | Converts text to a consistent case. | Apple becomes apple, potentially losing a company-name cue. |
| Punctuation handling | Keeps, removes, or separates punctuation. | A question mark can signal a question; apostrophes affect contractions. |
| URL and markup handling | Removes, extracts, or replaces HTML and URLs. | A URL may itself be relevant in phishing detection. |
| Stop-word removal | Removes frequent words from some feature representations. | Removing not can reverse sentiment. |
| Stemming | Reduces words to heuristic stems. | connected may become connect. |
| Lemmatization | Maps inflected forms to dictionary base forms using linguistic analysis. | running can map to run depending on context. |
| Language identification | Detects 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
| Type | Units | Strengths | Limitations |
|---|---|---|---|
| Word-level | Complete words or word-like segments | Intuitive for many traditional NLP tasks | Large vocabulary; difficulties with rare or new words |
| Subword-level | Whole common words and fragments of less common words | Balances vocabulary size and coverage | Splits can be unintuitive; vary by tokenizer |
| Character-level | Individual characters or code points | Can represent unfamiliar spellings | Longer sequences; semantic patterns are harder to learn directly |
| Byte-level | Individual bytes, sometimes merged into larger units | Broad coverage of input encodings | Tokens 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:
| Token | ID |
|---|---|
[PAD] | 0 |
[UNK] | 1 |
machine | 2 |
learning | 3 |
helps | 4 |
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:
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]:
| Document | cats | chase | mice |
|---|---|---|---|
cats chase mice | 1 | 1 | 1 |
mice chase cats | 1 | 1 | 1 |
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 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:
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:
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
| Representation | Main unit | Common use |
|---|---|---|
| Token embedding | Individual token | Input to a language model or contextual processing |
| Contextual token embedding | Token within a particular sequence | Sequence labeling, language understanding |
| Sentence embedding | Sentence or short passage | Semantic search, similarity, clustering |
| Document embedding | Longer passage or document | Retrieval, 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:
where is the vocabulary size and is the embedding dimension. For token ID , the embedding is row .
If and , the table contains scalar values. During training, a learned embedding table can be updated through gradient-based optimization along with other model parameters.
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 and , cosine similarity is:
It ranges from to 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
| Need | Reasonable starting point | What to test |
|---|---|---|
| Small labeled text classification dataset | TF-IDF with logistic regression or a linear SVM | Baseline accuracy, class balance, sparse features |
| Keyword-driven document matching | Lexical retrieval such as TF-IDF or BM25 | Exact-match recall, domain vocabulary |
| Semantic search with paraphrases | A suitable pretrained sentence-embedding model | Retrieval relevance, multilingual support, latency |
| Sequence labeling or context-sensitive text tasks | Contextual Transformer representations | Token alignment, context length, labeled performance |
| Resource-constrained deployment | Smaller sparse or compact embedding representations | Memory, 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:
| Question | Concept |
|---|---|
| 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
- Compare the effects of lowercasing and removing punctuation on a dataset containing proper names, negations, and sentiment labels.
- Use
TfidfVectorizerto inspect the most heavily weighted terms in three short documents. Explain why the values depend on the complete corpus. - Write a small vocabulary mapping and convert a token list into IDs. Explain why the IDs do not express semantic distance.
- Calculate cosine similarity for two vectors by hand and verify it using NumPy.
- Investigate the tokenizer of one specific pretrained model and compare its token count with the number of words in the same sentence.
- Compare a TF-IDF baseline with sentence embeddings for a small search task, using held-out queries and relevance judgments.
13. Related PlainCS articles
- Natural Language Processing Fundamentals — the broader tasks and workflow of NLP.
- Vectors and Matrices — the mathematics used to store numerical representations.
- Vector and Matrix Operations — dot products, norms, and matrix calculations.
- Data Cleaning and Preprocessing — general principles of preparing datasets.
- Feature Engineering, Encoding, and Scaling — structured-data representations and leakage-safe transformations.
- Information Retrieval and Search — lexical and semantic document retrieval.
- The Transformer Architecture — contextual representations and attention.
- Attention, Self-Attention, and Multi-Head Attention — how token representations exchange information.
- Retrieval-Augmented Generation — connecting retrieval with generation.
Some related routes belong to the planned knowledge map and may not yet be published.
14. References and further reading
- Jurafsky and Martin, Speech and Language Processing — textbook treatment of language processing and representations.
- scikit-learn: Text feature extraction — tokenization, count vectors, and TF-IDF implementations.
- PyTorch:
torch.nn.Embedding— embedding-table lookup and output shapes. - Hugging Face: Tokenizer summary — word, character, and subword tokenization methods.
- Mikolov et al. (2013), Efficient Estimation of Word Representations in Vector Space — early influential work on learned word vectors.
- Reimers and Gurevych (2019), Sentence-BERT — sentence embeddings for similarity search.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.