Sub topic 11
Contextual Embeddings and Cosine Similarity
This chapter assumes that you know basic Python, precision and recall, and the general idea of word embeddings and transformer language models. You will learn how a text metric can compare meaning rather than only matching exact words.
Why context changes an embedding
An embedding is a list of numbers that represents a token, word, or sentence. Similar meanings should produce vectors that point in similar directions.
Older word embeddings usually assigned one fixed vector to each word. For example, the word bank had one vector whether it meant a financial institution or the side of a river. This is a problem because the same word can have different meanings.
A contextual embedding is a vector calculated from the token and the words around it. A transformer language model reads the whole sequence, then produces a vector for each token. Therefore, the vector for bank can differ in these sentences:
- “She deposited money at the bank.”
- “They sat beside the river bank.”
The surrounding words help the model represent the intended meaning.
Cosine similarity
Cosine similarity measures the angle between two vectors. It ignores their overall length and focuses on direction:
cosine similarity = (A · B) / (||A|| × ||B||)
The result is usually between -1 and 1:
| Similarity | Interpretation |
|---|---|
| Near 1 | The vectors point in similar directions |
| Near 0 | The vectors have little directional relationship |
| Near -1 | The vectors point in opposite directions |
For language embeddings, higher cosine similarity often suggests that two tokens have similar meaning in their contexts. It does not prove that the sentences are factually equivalent.
Here is a small example using made-up vectors:
import math
def cosine_similarity(a, b):
dot_product = sum(x * y for x, y in zip(a, b))
length_a = math.sqrt(sum(x * x for x in a))
length_b = math.sqrt(sum(y * y for y in b))
if length_a == 0 or length_b == 0:
return 0.0
return dot_product / (length_a * length_b)
financial_bank = [0.9, 0.1, 0.0]
river_bank = [0.1, 0.9, 0.0]
financial_money = [0.8, 0.2, 0.0]
print(cosine_similarity(financial_bank, financial_money))
print(cosine_similarity(financial_bank, river_bank))The first result is high because the financial vectors point in similar directions. The second result is lower because the contexts differ. Real systems do not use hand-written vectors. A pretrained transformer creates them from learned parameters.
From embeddings to text comparison
A metric such as BERTScore obtains contextual embeddings for the tokens in a candidate sentence and a reference sentence. It then compares candidate tokens with reference tokens using cosine similarity.
This helps with paraphrases. For example, automobile may match car even though their surface forms are different. The model can also use context to distinguish meanings of the same word.
However, embedding similarity is still only a proxy for quality. A fluent sentence containing a false claim can receive high similarity if its wording and topic resemble the reference. A model can also assign high similarity to related words that are not interchangeable in a specific fact.
The next step is to use these token-level similarities to calculate precision, recall, and F1 for a complete candidate-reference pair.
Exercise
Why can the word bank receive different contextual embeddings in two sentences?
Show answer
A transformer uses surrounding tokens to infer which meaning is intended, so the vector for bank changes with its context.