An embedding is a list of numbers (a vector) that represents the meaning of text, images or other data. Similar meanings get nearby vectors, which lets computers search by meaning, cluster documents and power RAG chatbots.
What You Will Learn
- What embeddings are
- Cosine similarity
- Keyword vectors (TF-IDF) vs semantic embeddings
- Create embeddings with sentence-transformers and APIs
- Uses: search, clustering, recommendations, RAG
Cosine Similarity
import numpy as np
cos = lambda x, y: x @ y / (np.linalg.norm(x) * np.linalg.norm(y))
king_like = np.array([0.2, 0.9, 0.1])
queen_like = np.array([0.25, 0.8, 0.05])
apple_like = np.array([0.9, 0.1, 0.4])
print(round(cos(king_like, queen_like), 3), round(cos(king_like, apple_like), 3))
0.995 0.338
Explanation: Cosine similarity measures the angle between vectors: 1 = same direction (same meaning), 0 = unrelated. Real embeddings have hundreds or thousands of dimensions (e.g. 384, 768, 1536), but the maths is identical.
Keyword Vectors: TF-IDF
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
docs = ["How do I reset my password?",
"Steps to change account password",
"Best biryani restaurants in Ludhiana",
"Where can I eat good biryani?"]
vec = TfidfVectorizer().fit(docs)
E = vec.transform(docs)
print(cosine_similarity(E).round(2))
print(cosine_similarity(vec.transform(["forgot password"]), E).round(2))
[[1. 0.13 0. 0. ] [0.13 1. 0. 0. ] [0. 0. 1. 0.13] [0. 0. 0.13 1. ]] [[0.37 0.37 0. 0. ]]
Explanation: TF-IDF only matches shared words. The two password questions score just 0.13 because they share one word, and a query like “I can’t log in” would score 0 against both. Semantic embeddings fix this by learning meaning from massive text, so “can’t log in”, “reset password” and “forgot password” land close together.
Semantic Embeddings
# pip install sentence-transformers
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2") # small, free, 384 dimensions
emb = model.encode(docs + ["I can't log in to my account"], normalize_embeddings=True)
print(util.cos_sim(emb[-1], emb[:-1]))
Explanation: Expect the login query to score clearly higher against the two password documents than against the biryani ones, even with no shared words. API alternatives: OpenAI text-embedding-3-small, Google, Cohere, Voyage. Multilingual models (e.g. paraphrase-multilingual-MiniLM-L12-v2) match Hindi and English queries to the same meaning.
What Embeddings Are Used For
| Use | How |
|---|---|
| Semantic search | Embed documents once, embed the query, return nearest vectors |
| RAG | Retrieve relevant chunks for an LLM – RAG, PDF Q&A project |
| Clustering & topics | K-Means on embeddings – K-Means |
| Recommendations | Similar products, articles or jobs |
| Classification | Embeddings as features for logistic regression |
| Deduplication | Find near-duplicate questions or tickets |
Storing Embeddings
For thousands of vectors a NumPy array is enough. For millions, use a vector database or index – FAISS, Chroma, Qdrant, pgvector, Pinecone – see Vector Databases.
Series
Generative AI series: Intro to GenAI · LLM Fundamentals · Tokenization · Embeddings · Prompt Engineering · RAG · Vector DBs · Function Calling · AI Agents · Agent Frameworks · MCP · Hallucinations · Run LLMs Locally · Diffusion Models
Interview Questions
Q: What is an embedding?
A dense vector representing the meaning of data so that similar items are close in vector space.
Q: Why cosine similarity?
It compares direction regardless of vector length, which works well for text embeddings.
Q: TF-IDF vs embeddings?
TF-IDF matches exact words; embeddings capture meaning, synonyms and paraphrases.
Practice Exercises
- Add 10 FAQ sentences and build a search function that returns the top 3 for any query.
- Cluster 100 news headlines using sentence-transformer embeddings and K-Means.
Summary
Embeddings turn meaning into vectors; cosine similarity finds related items. They power semantic search, recommendations, clustering and RAG.
Next: Vector Databases · RAG
Machine Learning Tutorials, Courses and Certifications