What Are Embeddings?
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
- What Are Embeddings?
- Text → Tokens → Embeddings → Vectors
- Understanding Vector Space
- Cosine Similarity
- Worked Example with Python
- Nearest Neighbors
- Semantic Search
- How Many Dimensions?
- Real-World Applications
- Mini-Project: Document Search Engine
- FAQ
- Conclusion
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.
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:
↓ (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:
| Dimension | May Encode | Example |
|---|---|---|
| Dim 1 | Living vs non-living | "cat" high, "car" low |
| Dim 2 | Animate vs inanimate | "dog" high, "table" low |
| Dim 3 | Mechanical vs organic | "car" high, "cat" low |
| Dim 4 | Food 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.
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
| Angle | Cosine | Meaning | Example |
|---|---|---|---|
| 0° | 1.00 | Identical direction | "happy" ↔ "joyful" |
| 30° | 0.87 | Very similar | "cat" ↔ "dog" |
| 60° | 0.50 | Somewhat related | "cat" ↔ "pet" |
| 90° | 0.00 | Unrelated | "cat" ↔ "quantum" |
| 180° | -1.00 | Opposite | "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
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:
→ 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.
7. Semantic Search
Semantic search uses embeddings to find results based on meaning, not just keywords:
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?
| Model | Dimensions | Use Case |
|---|---|---|
| Word2Vec | 100–300 | Word-level similarity |
| GloVe | 50–300 | Word-level similarity |
| all-MiniLM-L6-v2 | 384 | Sentence similarity, fast |
| text-embedding-3-small | 1,536 | General-purpose embeddings |
| text-embedding-3-large | 3,072 | High-accuracy retrieval |
| BGE-large-en | 1,024 | Open-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
| Application | How Embeddings Help | Example |
|---|---|---|
| Semantic Search | Find by meaning, not keywords | "pet care" → finds "puppy training" |
| RAG Systems | Retrieve relevant documents for LLMs | Chatbot answers from your docs |
| Recommendations | Suggest similar items | "You liked X, try Y" |
| Clustering | Group similar documents | Auto-categorize support tickets |
| Deduplication | Find near-duplicate content | Detect plagiarism |
| Anomaly Detection | Find outliers in vector space | Fraud 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?
What is the difference between word and sentence embeddings?
Why cosine similarity instead of Euclidean distance?
Can embeddings capture context?
How does this relate to RAG?
What is a vector database?
Try These BestWordz Tools
- Standard Deviation Calculator — Understand vector magnitude and distance concepts
- Regex Tester — Pattern matching, analogous to embedding-based similarity
- All BestWordz Tools — Explore the complete tool library
Continue Learning
- RAG Architecture Explained — How embeddings power retrieval-augmented generation
- Transformers Explained — The architecture behind modern embedding models
- What Is an LLM? Beginner's Guide — Foundational concepts
- How LLMs Generate Text — Tokens, probabilities, and generation
- Context Engineering Explained — Using embeddings in context design
- Prompt Engineering Tutorial — Better prompts for better results
- How AI Coding Agents Work — Embeddings in agent workflows
Try the Standard Deviation Calculator
Put what you've learned into practice with this free BestWordz tool.
💬 Discuss this topic
Have questions or insights about What Are Embeddings?? Join the BestWordz Community.
Continue Learning: RAG Fundamentals
From embeddings to production RAG systems
📚 Related Articles
What Is an Embedding?
Embeddings transform text into numerical vectors that capture meaning. Semantically similar texts p…
CybersecurityThe 10-Stage Data Science Roadmap
Data science in 2026 spans far beyond machine learning. A complete data scientist needs Python, sta…
CybersecurityFrom Prompt Crafting to System Design
Key Takeaway --> 🎯 Context engineering is the skill of designing what an AI system knows, s…
AI & Machine LearningAI → Machine Learning → Deep Learning
Key Takeaway A Large Language Model (LLM) is a neural network trained on massive text data to predi…
CybersecurityThe 10-Stage CS Learning Roadmap
A computer science education in 2026 requires more than traditional coursework. Today's students ne…
AI & Machine LearningWhy Do We Need Vector Databases?
Vector databases are specialized systems for storing and searching embedding vectors. FAISS is a hi…
🔧 Related Tools
Standard Deviation Calculator
Compute the standard deviation of a data set — sample or population — with variance, mean, and coun…
Try it now →Regex Tester
Test regular expressions live: matches with positions, capture groups, and flag validation.
Try it now →AES-256-GCM Encrypt
Encrypt text with AES-256-GCM - the recommended encryption standard.
Try it now →URL Decoder
Encode and decode URL data, entirely in your browser.
Try it now →💬 Discuss on BestWordz Community
Join the conversation about Python, Docker, Neural Networks on the BestWordz Community forum.
Visit Forum →