From Text to Vectors, and What Vectors Are For
See what an embedding model returns for a piece of text, why texts with similar meaning end up close together, where that breaks down, and which jobs the vectors do besides search.
Contentsand lesson path
On this page
- Why it matters
- What an embedding model returns
- Close in meaning, close in space
- What vectors are for, and what they miss
- Check your understanding
- Apply it
- Review prompt
Lessons of Embeddings
- From Text to Vectors, and What Vectors Are For Concept · 15 min
- Similarity by Hand and in NumPy Worked example · 20 min
- Lab: Embed a Corpus in Batches Lab · 25 min
- Comparing Two Embedding Models Lab · 25 min
- Check: Similarity and Model Choice Knowledge check · 6 questions
What you will learn
- Compute cosine similarity and explain how normalization and dimensionality affect results.
Prerequisites: Data Handling
01. Why it matters
A customer types locked out of my account into your help centre. The article that answers it says Reset your password from the sign-in page. The two texts share no words, so a keyword search finds nothing, yet a person sees at once that they belong together.
An embedding model closes that gap. It turns a piece of text into a fixed-length list of numbers, a vector, and it was trained so that texts with similar meaning get vectors that point in similar directions. Search then becomes geometry: embed the question, find the stored vectors closest to it, and return their texts.
Every retrieval system in the rest of this track (vector search, RAG, grounded answers with citations) depends on this step. If the right passage does not land near the question, no later stage can bring it back. This lesson shows what a model returns, how closeness behaves on real sentences, where it misleads you, and what else the same vectors are good for.
02. What an embedding model returns
The examples use Sentence Transformers, a widely used Python library for running open embedding models on your own machine, and all-MiniLM-L6-v2, a small English model that runs comfortably on a laptop CPU. Install it in a virtual environment. It pulls in PyTorch, and the first run downloads the model (about 90 MB) into the Hugging Face cache. The outputs below come from Python 3.12 and sentence-transformers 6.3.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "sentence-transformers>=6,<7"import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
texts = [
'How do I reset my password?',
'Invoice',
'Scheduled exports run every night at 02:00 UTC. Each export is kept for 30 days, '
'then deleted. You can download an export again at any time before that.',
]
vectors = model.encode(texts)
print(vectors.shape, vectors.dtype)
print(vectors[0][:5].round(3))
print(np.linalg.norm(vectors, axis=1).round(3))
print(model.max_seq_length)(3, 384) float32
[ 0.007 -0.063 -0.072 -0.032 -0.043]
[1. 1. 1.]
256Read the output line by line:
- One row per text, always 384 numbers. A single word and a three-sentence paragraph both become 384 numbers. That is the model's dimension, fixed by the model, not by the input; other models use 768, 1,024, 1,536 or 3,072.
- The numbers mean nothing on their own. No position stands for "billing" or "password". Meaning lives in how whole vectors relate to each other.
- Every length is 1. This model scales each vector to length 1 as its last step. Not every model does; the next lesson shows why it matters.
- 256 is the input limit in tokens. Anything after the first 256 tokens is cut off without warning, so the vector describes only the start of a long text. This is one reason documents are split into chunks before embedding.
Inside, the model tokenises the text much as an LLM does, runs a transformer encoder that gives one vector per token, and averages those into one vector. It generates no text, and the same input with the same model version gives the same vector, apart from tiny floating-point differences between machines.
03. Close in meaning, close in space
The usual measure of closeness is cosine similarity: 1 when two vectors point the same way, 0 when they are unrelated, negative when they point in opposite directions. For text embeddings most pairs land between 0 and 1. The next lesson computes it by hand; here model.similarity does it for you. Compare one question with five other texts:
from sentence_transformers import SentenceTransformer
query = 'How do I reset my password?'
others = [
"I forgot my login details and can't sign in.",
'How do I change the password on my Wi-Fi router?',
'The billing address on my receipt is incorrect.',
'Làm sao để đặt lại mật khẩu?', # Vietnamese: "How do I reset my password?"
'Our invoice shows the wrong VAT number.',
]
def show(model: SentenceTransformer, prefix: str = '') -> None:
q = model.encode([prefix + query])
docs = model.encode([prefix + text for text in others])
scores = model.similarity(q, docs)[0].tolist()
for score, text in sorted(zip(scores, others), reverse=True):
print(f' {score:.2f} {text}')
print('all-MiniLM-L6-v2')
show(SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2'))all-MiniLM-L6-v2
0.63 I forgot my login details and can't sign in.
0.58 How do I change the password on my Wi-Fi router?
0.25 The billing address on my receipt is incorrect.
0.12 Làm sao để đặt lại mật khẩu?
0.11 Our invoice shows the wrong VAT number.The paraphrase wins even though it shares no keyword with the question. The billing texts score low. Two results deserve a second look:
- The Wi-Fi router question scores 0.58, close behind the true match. It shares the words and the topic, just not the intent. Embeddings capture topic and wording as well as meaning, so near misses often rank high.
- The Vietnamese translation of the question scores 0.12, as low as an unrelated invoice.
all-MiniLM-L6-v2was trained on English text, so it cannot see that the two sentences mean the same thing.
Now add a multilingual model to the end of the file and run it again.
print('multilingual-e5-small')
# This model expects a prefix on every input. To compare texts like with like,
# its model card says to put 'query: ' on both sides.
show(SentenceTransformer('intfloat/multilingual-e5-small'), prefix='query: ')multilingual-e5-small
0.92 How do I change the password on my Wi-Fi router?
0.86 Làm sao để đặt lại mật khẩu?
0.85 I forgot my login details and can't sign in.
0.82 The billing address on my receipt is incorrect.
0.79 Our invoice shows the wrong VAT number.Three things changed, and each matters later:
- Languages. The multilingual model puts the Vietnamese question right next to the English one (0.86). An English-only model fails users who write in other languages, and it fails them silently.
- Score scale. Every score sits between 0.79 and 0.92; this model is known to put most scores between about 0.7 and 1.0. So 0.8 means "unrelated" here, while 0.6 means "very close" for MiniLM. A score only means something next to other scores from the same model: a cut-off such as 0.5 must be chosen again for each model, and vectors from two models cannot be compared at all.
- Ranking. The multilingual model ranks the Wi-Fi question first. Two reasonable models disagree on five sentences, and only an evaluation on your own queries settles which serves you better; the last lesson of this skill builds one.
04. What vectors are for, and what they miss
Once texts are vectors, many jobs reduce to "find what is near" or "find what is far":
- Semantic search and RAG retrieval: embed every chunk once, embed each question as it arrives, return the nearest chunks.
- Classification: give a new ticket the label of its most similar labelled tickets, or train a small classifier on the vectors.
- Clustering: group thousands of tickets into themes with k-means or HDBSCAN, then read a few per group to name it.
- Deduplication: pairs above a high cut-off, tuned for your model, are likely near-duplicates.
- Recommendations: related articles are the nearest neighbours of the one being read.
- Outlier detection: a text far from everything else may be a new kind of complaint, spam or an unexpected language.
You can run the model yourself, as here, or call a hosted embeddings API. Hosted models need no hardware and bill per token, but your text leaves your network and the provider decides when a model is retired. Local open-weight models keep data in house and let you pin an exact version, but you pay for and run the machine. The two labs in this skill use both.
Similarity also misleads in predictable ways. Run this short check:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
pairs = [
('The mobile app works offline.', 'The mobile app does not work offline.'),
('The mobile app works offline.', 'You can use the phone app without internet.'),
('Export fails with ERR-4031', 'Export fails with ERR-4032'),
]
for a, b in pairs:
score = model.similarity(model.encode([a]), model.encode([b]))[0, 0]
print(f'{score:.2f} {a} | {b}')0.93 The mobile app works offline. | The mobile app does not work offline.
0.69 The mobile app works offline. | You can use the phone app without internet.
0.99 Export fails with ERR-4031 | Export fails with ERR-403205. Check your understanding
06. Apply it
This skill's practice project compares a hosted and a local model on 500 short documents and 20 labelled queries. Start collecting the data now:
- Gather about 500 short texts from your own work: help articles, FAQ answers, ticket summaries or product descriptions. Save them as
docs.jsonlwith a stabledoc_idand atextper line. - Write 20 questions a real user might ask, in the languages your users write in, and note for each the
doc_idthat answers it. Phrase some of them without the words the document uses. - Run
nearby.pywith three of your questions against a handful of documents and write down one result that surprised you, and why.
07. Review prompt
Without scrolling up, explain to a colleague what an embedding model returns for a sentence, why the length of that output does not depend on the sentence, and what happens to text beyond the model's token limit. Then name four jobs besides search that embeddings can do, and two situations where a high similarity score would mislead you.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.