AI & Machine Learning

What Are Embeddings?

Python Docker Neural Networks LLMs RAG Prompt Engineering AI Agents Databases SQL Data Science Clustering Transformers Embeddings Vector Search Semantic Search Anomaly Detection
1,594 words Includes Code
Embeddings tutorial showing text-to-vector pipeline, semantic clusters in vector space, and cosine similarity visualization with similar, unrelated, and opposite vectors
📌 Key Takeaway

Embeddings convert text into numerical vectors where meaningful relationships become mathematical distances. Words with similar meanings cluster together in vector space. Cosine similarity measures how close two vectors are — enabling semantic search, recommendations, and RAG systems.

When you search for "pet care tips" and find results about "how to train a puppy," the system did not match exact words. It matched meaning. That is the power of embeddings.

This tutorial explains how AI converts meaning into numbers, from tokenization through vector space to semantic search — with a complete Python implementation.

Table of Contents


1. What Are Embeddings?

An embedding is a numerical representation of a word, sentence, or document in a continuous vector space. Each piece of text becomes a list of numbers (a vector), and the positions of these vectors encode meaning.

Analogy: GPS Coordinates for Meaning

Just as GPS coordinates (40.7128, -74.0060) place New York on a map, embeddings place words in "meaning space."

"cat" → [0.9, 0.8, 0.1, 0.2] — near "dog" and "kitten"
"car" → [0.1, 0.2, 0.9, 0.8] — near "truck" and "vehicle"
"apple" → [0.2, 0.15, 0.1, 0.9] — near "banana" and "fruit"

Similar meanings → close vectors. Different meanings → far vectors.

Embeddings are learned during training. The model discovers that "cat" and "dog" appear in similar contexts, so their vectors end up close together. No one manually assigns these positions — the model learns them from data.


2. Text → Tokens → Embeddings → Vectors

The complete pipeline from raw text to usable vectors:

① RAW TEXT "The cat sat on the mat"
(tokenization)
② TOKENS ["The", "cat", "sat", "on", "the", "mat"]
(token IDs)
③ TOKEN IDS [0, 2, 4, 5, 1, 6]
(embedding lookup)
④ EMBEDDINGS [vec_0, vec_2, vec_4, vec_5, vec_1, vec_6]
(pooling or averaging)
⑤ SENTENCE [0.75, 0.70, 0.20, 0.30] (single vector)

Word embeddings represent individual words. Sentence embeddings represent entire sentences by combining (pooling) the word vectors. Modern embedding models like OpenAI's text-embedding-3 or sentence-transformers produce sentence-level vectors directly.


3. Understanding Vector Space

Embeddings live in a high-dimensional space where each dimension captures some aspect of meaning:

DimensionMay EncodeExample
Dim 1Living vs non-living"cat" high, "car" low
Dim 2Animate vs inanimate"dog" high, "table" low
Dim 3Mechanical vs organic"car" high, "cat" low
Dim 4Food vs non-food"apple" high, "car" low

Important: These dimensions are not explicitly labeled. The model discovers useful dimensions automatically during training. In real models with 768–3,072 dimensions, the learned patterns are far more nuanced than simple categories.

See Transformers Explained for how embeddings are computed within transformer architectures.


4. Cosine Similarity

Cosine similarity measures the angle between two vectors — how "pointing in the same direction" they are.

FORMULA:
cos(A, B) = (A · B) / (|A| × |B|)

A · B = dot product (sum of element-wise products)
|A| = magnitude (Euclidean norm)

RANGE:
+1.0 → Identical direction (very similar)
0.0 → Orthogonal (unrelated)
-1.0 → Opposite direction (very different)

Why cosine, not Euclidean distance? Cosine similarity is insensitive to vector magnitude — it only cares about direction. Two vectors pointing the same way but with different lengths will have high cosine similarity. This makes it ideal for text, where the "direction" encodes meaning.

Visual Intuition

AngleCosineMeaningExample
1.00Identical direction"happy" ↔ "joyful"
30°0.87Very similar"cat" ↔ "dog"
60°0.50Somewhat related"cat" ↔ "pet"
90°0.00Unrelated"cat" ↔ "quantum"
180°-1.00Opposite"hot" ↔ "cold"

5. Worked Example with Python

Here is a complete, runnable Python implementation of cosine similarity:

import math

def cosine_similarity(a, b):
    """Compute cosine similarity between two vectors."""
    dot = sum(x * y for x, y in zip(a, b))
    mag_a = math.sqrt(sum(x * x for x in a))
    mag_b = math.sqrt(sum(x * x for x in b))
    return dot / (mag_a * mag_b)

# Example word embeddings (4-dimensional)
cat  = [0.9, 0.8, 0.1, 0.2]
dog  = [0.85, 0.78, 0.15, 0.25]
car  = [0.1, 0.2, 0.9, 0.8]

print(f"cat ↔ dog: {cosine_similarity(cat, dog):.4f}")
print(f"cat ↔ car: {cosine_similarity(cat, car):.4f}")

# Output:
# cat ↔ dog: 0.9977  (very similar — both animals)
# cat ↔ car: 0.3331  (dissimilar — different domain)

Step-by-Step Calculation

cos("cat", "dog"):

A = [0.9, 0.8, 0.1, 0.2]
B = [0.85, 0.78, 0.15, 0.25]

Dot product:
A · B = 0.9×0.85 + 0.8×0.78 + 0.1×0.15 + 0.2×0.25
     = 0.765 + 0.624 + 0.015 + 0.050 = 1.454

Magnitudes:
|A| = √(0.9² + 0.8² + 0.1² + 0.2²) = √(0.81+0.64+0.01+0.04) = √1.50 = 1.2247
|B| = √(0.85² + 0.78² + 0.15² + 0.25²) = √(0.7225+0.6084+0.0225+0.0625) = √1.4159 = 1.1899

Result:
cos = 1.454 / (1.2247 × 1.1899) = 1.454 / 1.4573 = 0.9977

6. Nearest Neighbors

Finding the most similar items to a query is called nearest neighbor search. For each candidate, compute cosine similarity and rank by score:

QUERY: "cat"

→ puppy: 0.9984 ████████████████████████████████████████
→ kitten: 0.9981 ███████████████████████████████████████
→ dog: 0.9977 ██████████████████████████████████████
→ car: 0.3331 █████████████

QUERY: "apple"

→ fruit: 0.9983 ███████████████████████████████████████
→ banana: 0.9977 ██████████████████████████████████████
→ truck: 0.7780 ████████████████████████████

At small scale, brute-force comparison works. At large scale (millions of vectors), you need approximate nearest neighbor (ANN) algorithms like FAISS, Annoy, or HNSW for efficient search.


Semantic search uses embeddings to find results based on meaning, not just keywords:

KEYWORD SEARCH vs SEMANTIC SEARCH:

Query: "teach me programming"

Keyword search finds documents containing "teach," "me," or "programming" literally.
Semantic search finds "Python tutorial" and "learn to code" — same meaning, different words.

Semantic search is the foundation of RAG (Retrieval-Augmented Generation) systems. When you ask a chatbot about your documents, it embeds your query, finds the most similar document chunks, and feeds them to the LLM.

Learn more in RAG Architecture Explained.


8. How Many Dimensions?

ModelDimensionsUse Case
Word2Vec100–300Word-level similarity
GloVe50–300Word-level similarity
all-MiniLM-L6-v2384Sentence similarity, fast
text-embedding-3-small1,536General-purpose embeddings
text-embedding-3-large3,072High-accuracy retrieval
BGE-large-en1,024Open-source, high quality

More dimensions ≠ always better. 384 dimensions from a well-trained model can outperform 3,072 from a poorly trained one. Quality depends on training data and architecture, not just dimension count.


9. Real-World Applications

ApplicationHow Embeddings HelpExample
Semantic SearchFind by meaning, not keywords"pet care" → finds "puppy training"
RAG SystemsRetrieve relevant documents for LLMsChatbot answers from your docs
RecommendationsSuggest similar items"You liked X, try Y"
ClusteringGroup similar documentsAuto-categorize support tickets
DeduplicationFind near-duplicate contentDetect plagiarism
Anomaly DetectionFind outliers in vector spaceFraud detection

10. Mini-Project: Document Search Engine

Build a simple document search engine using embeddings and cosine similarity:

import math

def cosine_similarity(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    mag_a = math.sqrt(sum(x * x for x in a))
    mag_b = math.sqrt(sum(x * x for x in b))
    return dot / (mag_a * mag_b)

# Document embeddings (in production, use an embedding model)
docs = [
    {"title": "Intro to Python", "vec": [0.8, 0.7, 0.2, 0.1]},
    {"title": "Data Science",    "vec": [0.75, 0.65, 0.35, 0.15]},
    {"title": "Web Dev with Flask", "vec": [0.5, 0.4, 0.6, 0.3]},
    {"title": "Docker Guide",      "vec": [0.2, 0.15, 0.8, 0.5]},
]

def search(query_vec, docs, k=3):
    results = []
    for doc in docs:
        sim = cosine_similarity(query_vec, doc["vec"])
        results.append((doc["title"], sim))
    results.sort(key=lambda x: -x[1])
    return results[:k]

# Search
query = [0.82, 0.72, 0.18, 0.12]  # "learn Python basics"
for title, score in search(query, docs):
    print(f"[{score:.3f}] {title}")

# Output:
# [1.000] Intro to Python
# [0.984] Data Science
# [0.915] Web Dev with Flask

In production, you would replace the hand-crafted vectors with real embeddings from a model like sentence-transformers or OpenAI's text-embedding-3-small, and use a vector database like Chroma, Pinecone, or Weaviate for efficient search at scale.


11. FAQ

How are embeddings created?
Embeddings are learned during neural network training. The model adjusts vector positions so that words appearing in similar contexts end up close together. You can train your own or use pre-trained models like Word2Vec, GloVe, or sentence-transformers.
What is the difference between word and sentence embeddings?
Word embeddings represent individual words (Word2Vec, GloVe). Sentence embeddings represent entire sentences or paragraphs (sentence-transformers, OpenAI embeddings). Sentence embeddings capture contextual meaning that word embeddings miss.
Why cosine similarity instead of Euclidean distance?
Cosine similarity measures direction (angle), not magnitude. Two vectors pointing the same way but with different lengths will have high cosine similarity. For text embeddings, direction encodes meaning while magnitude is less informative.
Can embeddings capture context?
Modern embedding models (sentence-transformers, OpenAI embeddings) produce contextual embeddings — the same word gets different vectors in different sentences. "Bank" near "river" differs from "Bank" near "money."
How does this relate to RAG?
RAG (Retrieval-Augmented Generation) uses embeddings to find relevant documents. When you ask a question, it embeds your query, searches for the most similar document chunks using cosine similarity, and feeds them to the LLM as context. See RAG Architecture Explained.
What is a vector database?
A database optimized for storing and searching high-dimensional vectors. Instead of SQL queries, you search by similarity. Examples: Chroma, Pinecone, Weaviate, Milvus, FAISS. They use approximate nearest neighbor (ANN) algorithms for fast search at scale.

Try These BestWordz Tools

Continue Learning

Try the Standard Deviation Calculator

Put what you've learned into practice with this free BestWordz tool.

Open Tool →

Continue Learning: RAG Fundamentals

From embeddings to production RAG systems

  1. The Five Types of Agent Memory
  2. Why RAG Exists: The Hallucination Problem
  3. What Are Embeddings? (this article)
  4. Hybrid Search: Combining BM25 and Vector Search
  5. RAG Architecture Explained: Every Component of a Retrieval-Augmented AI System

💬 Discuss on BestWordz Community

Join the conversation about Python, Docker, Neural Networks on the BestWordz Community forum.

Visit Forum →