Sub topic 3
Contextual Embeddings and Cosine Similarity
This chapter assumes you know Python lists and dictionaries, precision, recall, and F1, and that a transformer language model turns text into vectors. Each token gets one vector, and that vector depends on the tokens around it.
Contextual embeddings and cosine similarity
A contextual embedding is a vector for a token that changes with its sentence. The word "bank" gets different vectors in "river bank" and "bank loan." Cosine similarity measures the angle between two vectors. It ranges from -1 to 1 and ignores vector length.
import numpy as np
def cosine(u, v):
return float(np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)))
print(cosine(np.array([1.0, 0.0]), np.array([1.0, 1.0]))) # about 0.7071
print(cosine(np.array([1.0, 2.0]), np.array([2.0, 4.0]))) # 1.0, same directionBERTScore: greedy matching of token embeddings
BERTScore embeds every candidate token and every reference token, then builds a matrix of cosine similarities between them. Each candidate token takes its best reference match, and precision averages those best matches. Each reference token takes its best candidate match, and recall averages those. F1 combines the two.
from bert_score import score
candidates = ["The cat sat on the mat."]
references = ["A cat was sitting on the rug."]
P, R, F1 = score(candidates, references, lang="en")
print(F1.mean().item())BERTScore options: IDF weighting and baseline rescaling
IDF (inverse document frequency) weighting gives rare tokens more weight, so matching "Paris" counts for more than matching "the." Pass idf=True to score() to turn it on.
Raw BERTScore values cluster high, often near 0.8 to 0.9, which makes differences hard to read. Baseline rescaling subtracts the score that random sentence pairs receive, so rescale_with_baseline=True spreads the values out. Rescaled scores can be negative, and they are not percentages.
What these metrics miss: paraphrase, factuality, and human correlation
Overlap metrics such as BLEU and ROUGE penalize valid paraphrases that use different words. Embedding metrics handle paraphrase better, but they can still rate a factual error highly, because one changed word such as "not" barely moves the vectors. How well any metric tracks human judgment depends on the task, language, and dataset, so check that correlation on your own labeled examples before you rely on a score.
Choosing and reporting metrics for your task
Report the library and its version, the model name, and every setting, including idf and rescale_with_baseline. Use SacreBLEU for BLEU, ROUGE for summarization recall, and BERTScore as a semantic check alongside them. For high-stakes uses, pair automatic scores with human review.
Exercise
Exercise
In the cosine example, why does the second call return 1.0 even though the second vector is twice as long as the first?
Show answer
Cosine similarity depends only on the angle between the vectors. Both vectors point in the same direction, so the angle is zero and the cosine is 1.0. Vector length is divided out in the formula.