Embeddings & semantic similarity
Embed text and rank documents by cosine similarity.
By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.
In short
An embedding turns text into a list of numbers so that similar meanings land close together. Comparing vectors with cosine similarity lets you find relevant text even when the words differ.
Think of it like this: Embeddings place texts on a map where nearby points mean similar things.
Explained simply
Computers are good with numbers, not meaning. An embedding model turns a piece of text into a long list of numbers, called a vector. It is trained so that texts with similar meaning get similar lists of numbers, even when they use different words.
Think of each vector as a point on a giant map with hundreds of directions instead of two. "How do I get a refund?" and "I want my money back" land close together. "Shipping to Canada" lands somewhere else.
To search by meaning, you turn all your documents into vectors once and save them. When a question comes in, you turn the question into a vector too, then find the saved vectors closest to it. Closeness is usually measured with cosine similarity, which compares the direction of two vectors.
This is called semantic search, and it is the first half of most AI apps that answer questions about your own documents. It is not magic, though: embeddings are weaker at exact codes, numbers and negation, so you test them on your own data.
Press Play on a diagram to walk through it one step at a time.
- Step 1Embed documents
Each text becomes a vector
- Step 2Embed the query
Use the same embedding model
- Step 3Cosine similarity
Score each document against the query
- Step 4Rank
Highest scores are most similar
- Quality
- Test on your own queries
- Public retrieval benchmarks for a shortlist
- Size
- Dimension drives storage and speed
- Max input tokens per text
- Languages
- English-only or multilingual
- Hosting
- API: no servers, per-token price
- Local: private, needs CPU or GPU
- Lock-in
- Switching means re-embedding everything
In depth
Where embeddings come from
An embedding model is usually a transformer encoder. It reads the text, produces a vector for every token, and then combines them into one vector for the whole text, often by averaging (mean pooling). The model is trained on huge numbers of pairs that belong together, such as a question and its answer, a title and its article. Training pulls matching pairs closer and pushes unrelated texts apart. This is called contrastive learning.
Every model outputs vectors of a fixed size, its dimension, whatever the length of the input. Common sizes are 384, 768, 1024 and higher; for example, the small open model all-MiniLM-L6-v2 outputs 384 numbers. Each model also has a maximum input length. Text beyond it is usually cut off silently, so a long document may be embedded from its first part only.
- Fixed dimension per model, any text length in
- Input beyond the model's limit is usually cut off
- Different models give incompatible vectors
- Changing models means re-embedding everything
- 1Text in
A sentence, paragraph or query
- 2Tokenise
Split into tokens, up to a length limit
- 3Encoder
A vector for every token
- 4Pool
Combine into one vector, often the mean
- 5Normalise
Scale to length 1 (many models do this)
Cosine, dot product and distance
Cosine similarity is the dot product of two vectors divided by the product of their lengths. It measures the angle between them: 1 means the same direction, 0 means unrelated, and negative values mean opposite directions, though with text embeddings most scores fall between 0 and 1.
If vectors are normalised to length 1, the dot product equals cosine similarity, and ranking by Euclidean distance gives the same order too. Many embedding APIs return normalised vectors, and libraries such as sentence-transformers can normalise for you. Then you can use the fastest operation, a plain dot product.
Scores are not comparable across models. A score of 0.8 may mean very similar in one model and only loosely related in another. Never hard-code a similarity threshold without checking it on labelled examples for that exact model.
- Angle between vectors
- Ignores vector length
- Higher means more similar
- Sum of element products
- Equals cosine for unit vectors
- Fastest to compute
- Straight-line distance
- Lower means more similar
- Same ranking as cosine for unit vectors
Generating embeddings: API or local model
With a hosted embedding API, you send a list of texts in one request and get a list of vectors back in the same order. Batch your requests (dozens to hundreds of texts per call, within the provider's limits), because one text per call is slow and hits rate limits. Embeddings are cheap per token compared with chat models, but re-embedding a large corpus still costs time and money, so store the results.
With a local model, such as one loaded through sentence-transformers, you call model.encode(texts) and pass normalize_embeddings=True. It runs on a CPU for small jobs and much faster on a GPU.
Some models are asymmetric: they expect queries and documents to be marked differently. The E5 family expects the prefixes query: and passage:, and some APIs have an input type option. Read the model card; skipping this can noticeably lower search quality.
- Batch texts per request
- Store vectors with the model name and version
- Use query and document prefixes if the model expects them
- Same model for queries and documents
Where embeddings struggle
Embeddings capture general meaning, which brings predictable blind spots. Negation is weak: refundable and not refundable can land close together because they share the topic. Exact identifiers such as SKU-4471, error codes and version numbers carry little meaning, so the right document may not rank first. Numbers and dates are treated as text, not values.
Long texts get blurred. A vector for a five-page document averages many topics, so it matches none of them strongly. This is why documents are split into chunks before embedding.
Domain language can also be a problem: a general model may not know that two internal product names mean the same thing. Fixes include hybrid search with keywords for exact terms, adding titles or synonyms to chunk text, trying a domain-specific model, and always testing retrieval on real questions.
Seeing your embeddings
You cannot look at 384 dimensions directly, but you can squash them into 2 for a picture. PCA (principal component analysis) is fast and keeps the broad structure. t-SNE and UMAP keep local neighbourhoods better, so clusters stand out more clearly.
Colour each point by a known label, such as product area or document type. Good embeddings show tight groups for each label; overlapping groups suggest the model cannot tell those topics apart, which predicts retrieval mistakes. Outliers are often parsing errors or empty chunks.
Treat the plot as a hint, not a measurement. Squashing hundreds of dimensions into two distorts distances, and t-SNE in particular can make the gaps between clusters look more meaningful than they are. Use real retrieval tests to decide.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Generate embeddings via an API~45m
- 2Compute cosine similarity~45m
- 3Rank documents for a query~45m
- 4Visualise similar texts~45m
Key points
- Always embed queries and documents with the same model.
- Cosine similarity compares direction, ranging roughly from -1 to 1.
- Embeddings capture meaning, so car and automobile end up close.
- Store vectors once at ingest time; only the query is embedded per search.
Key terms
Tap a card to flip it. 0/5 known
Examples
import math
def cosine(a: list[float], b: list[float]) -> float:
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.hypot(*a) * math.hypot(*b))
# Toy 3-d vectors; real ones come from an embedding model
docs = {'refund policy': [0.9, 0.1, 0.0], 'shipping times': [0.1, 0.9, 0.2]}
query = [0.8, 0.2, 0.1] # 'how do I get my money back?'
ranked = sorted(docs, key=lambda d: cosine(query, docs[d]), reverse=True)
print(ranked) # ['refund policy', 'shipping times']Ranking documents by cosine similarity to a query.
Semantic search with sentence-transformers
You want to find the right help article for a customer's question on your own machine. Step 1: install sentence-transformers and load a small model (it downloads once). Step 2: embed the documents with normalisation, so a dot product equals cosine similarity. Step 3: embed the question the same way. Step 4: score all documents with one matrix product and sort. The refund article should rank first even though the question never says refund.
# pip install sentence-transformers
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2") # 384 dimensions
docs = ["Refunds are paid to the original card within 5 days.",
"We ship to Canada and the US.",
"Reset your password from the login page."]
doc_vecs = model.encode(docs, normalize_embeddings=True)
q_vec = model.encode("How do I get my money back?", normalize_embeddings=True)
scores = doc_vecs @ q_vec # cosine, since vectors are unit length
for i in scores.argsort()[::-1]:
print(f"{scores[i]:.3f} {docs[i]}")A 2D picture of your documents
You suspect the billing and account help articles are confused in search. Step 1: embed every article. Step 2: reduce the vectors to 2 dimensions with PCA from scikit-learn. Step 3: plot them and colour by category. Step 4: if billing and account points overlap heavily, expect retrieval mix-ups between them; look at the overlapping articles and consider clearer titles or a better model. Remember the plot distorts distances, so confirm with real queries.
# pip install scikit-learn matplotlib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# vecs: array of shape (n_docs, 384); labels: one category per doc
points = PCA(n_components=2).fit_transform(vecs)
for label in sorted(set(labels)):
idx = [i for i, l in enumerate(labels) if l == label]
plt.scatter(points[idx, 0], points[idx, 1], label=label, s=12)
plt.legend()
plt.title("Help articles, PCA of embeddings")
plt.savefig("embeddings.png", dpi=150)Quick reference
- Same embedding model for documents and queries, always
- normalize_embeddings=True makes dot product equal cosine similarity
- Similarity scores are not comparable across models: calibrate thresholds per model
- Text past the model's max input length is usually cut off silently
- Batch texts per API call and store vectors with the model name
- E5-style models need query: and passage: prefixes
- Weak spots: negation, exact codes, numbers; add keyword search for those
- PCA, t-SNE or UMAP give a 2D picture; confirm with retrieval tests
Common mistakes
- Mixing vectors from different embedding models in one index.
- Expecting embeddings to match exact codes or IDs well.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Embed 5 sentences of your own and print the similarity matrix. Check that the two sentences you meant to be similar score highest together.
- Exercise 2medium
Write a function search(query, docs, k) that embeds the documents once (cached), embeds the query, and returns the top k documents with scores, using numpy argpartition for speed.
- Exercise 3hard
Test negation: make 10 pairs like refundable and not refundable. Measure how close each pair is, and compare with pairs of truly different topics. Write down what this means for your app.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is a good embedding dimension?
- Bigger vectors can capture more detail but cost more storage and slower search. Many apps do well with 384 to 1024 dimensions; pick based on retrieval tests, not size alone.
- Can I use a chat model to make embeddings?
- Use a model built for embeddings. Providers offer separate embedding models that are far cheaper and designed for similarity search.
- Do embeddings work across languages?
- Multilingual embedding models place a sentence and its translation close together, so a query in one language can find documents in another. English-only models do this poorly.
- Is cosine similarity the same as accuracy?
- No. It is a similarity score between two vectors. Whether the top results are actually right must be measured with labelled questions, using metrics like recall at k.