Intermediate level · Module 3: Tokens, Embeddings and Semantic Search · Lesson 2 of 3
Embeddings and Cosine Similarity
Learners create sentence embeddings with Sentence Transformers and compare meanings with cosine similarity.
In this lesson you will
- Create sentence embeddings
- Compute and interpret cosine similarity
Key concepts
embedding vectorSentence Transformerscosine similaritynormalisationsemantic similarity
The lesson
An embedding model maps text to a vector so that texts with similar meanings get similar vectors. all-MiniLM-L6-v2 (Apache-2.0) is a small Sentence Transformers model that runs on a CPU: model.encode(sentences) returns vectors.
Cosine similarity measures the angle between two vectors: close to 1 means very similar meaning, close to 0 unrelated. 'When must I pay the fees?' and 'Second-term fees are due by 14 March' score high even though they share few words.
Embedding quality depends on language. Many small models are trained mostly on English, so test them on any other language before relying on them.
Step by step
- Encode ten sentences with all-MiniLM-L6-v2.
- Compute the cosine similarity matrix.
- Find the most similar pairs.
- Test two sentences in another language and note the quality.
Ranking passages by meaning with cosine similarity
Toy embedding vectors show how a question about paying fees is matched to the right passage, even though they share few words.
import numpy as np # Toy 4-number embeddings (real models such as all-MiniLM-L6-v2 return 384 numbers)passages = { "fees-2026": ("Second-term fees are due by 14 March.", [0.9, 0.1, 0.0, 0.2]), "timetable": ("Python classes run Monday to Thursday.", [0.1, 0.9, 0.2, 0.0]), "admissions": ("Applicants need a school-leaving certificate.", [0.2, 0.1, 0.9, 0.1]),}question = "When must I pay the fees?"q = np.array([0.8, 0.0, 0.1, 0.3]) # the question's embedding def cosine(a, b): a, b = np.array(a), np.array(b) return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b))) ranked = sorted(passages.items(), key=lambda item: cosine(q, item[1][1]), reverse=True)for doc_id, (text, vec) in ranked: print(f"{cosine(q, vec):.3f} {doc_id:<11} {text}")
Output
0.978 fees-2026 Second-term fees are due by 14 March.
0.349 admissions Applicants need a school-leaving certificate.
0.125 timetable Python classes run Monday to Thursday.How it works
Cosine similarity is the dot product of two vectors divided by the product of their lengths. It is close to 1 when they point the same way, meaning similar meaning, and close to 0 when they are unrelated. The question shares only the word 'fees' with the first passage, but their embeddings point in almost the same direction (0.978), so the fees passage ranks first. The timetable passage is about something else and scores 0.125. In a real system, an embedding model produces the vectors (for example model.encode(texts) in Sentence Transformers), a vector database such as Chroma stores them, and the top passages are passed to the language model with their IDs, so that the answer can cite 'fees-2026'. The four-number vectors here are invented for teaching; real embeddings have hundreds of dimensions and are not interpretable one number at a time.
Key concepts
embedding vectorscosine similarityranking by meaningpassage IDs for citationstoy vs real embeddings
Practice activity
Build a similarity matrix for project sentences and interpret it.
Expected result: A correct matrix with sensible top pairs and a note on language limits.
Check your understanding
-
What does a cosine similarity near 1 mean?
Show answer
The texts have very similar meanings.
-
Why test embeddings on local-language text?
Show answer
Many models are trained mostly on English and may work poorly on other languages.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.