Evaluating embeddings
嵌入质量评测
Build a small retrieval audit with graded relevance, explicit averaging and separate representation/index errors.
embedding-evaluationStart with the problem
An embedding is a means to a task. A vector that groups paraphrases well may rank a specialist query poorly; a high average can hide a failed domain. Before choosing a model, decide what the system must retrieve or predict, which errors matter and what data are permitted during fitting.
The original MTEB paper separates task families such as classification, clustering, sentence similarity and retrieval rather than treating one score as universal. BEIR evaluates retrieval across different domains and shows why strong in-domain results need not transfer. We use their fixed paper versions as methodological references, not as current model rankings. MTEB: Massive Text Embedding Benchmark — arXiv v1; BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models — arXiv v1
Our small evaluator compares dot-product and cosine ranking on four queries and six already supplied vectors. It exposes the effect of vector norms, graded relevance, domain weighting, missing judgments and deterministic ties. It does not run a language model or reproduce either benchmark.
Definitions and derivation
For query q and document d, a dot product preserves their magnitudes, while cosine removes them. Positive per-document rescaling can therefore change dot ranking without changing cosine ranking:
Cosine is undefined for a zero vector; reject it rather than quietly producing NaNs. Rank by decreasing score, breaking exact ties by stable document ID. IDs must be unique so one retrieved item cannot be counted twice.
For a query with positive relevance set R and top-k list, recall measures how many relevant items are recovered; truncated reciprocal rank measures the first hit. Our graded nDCG explicitly uses exponential gain, which is not a claim about the exact gain convention of every benchmark implementation:
The sum stops at the number actually retrieved if it is below k. IDCG sorts all known positive grades ideally. An empty positive-judgment set gives no recall denominator and no positive ideal gain; this evaluator returns None, to be reported separately. That does not establish that the query has no relevant documents in reality.
Average query scores or first average within each domain. The two answer different questions:
Query averaging weights domains by query count; equal-domain averaging gives a small domain the same aggregate weight as a large one. Report the weighting choice. BEIR’s discussion of rank-aware graded evaluation motivates nDCG; our k=2 and gain convention are explicit teaching choices. BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models — arXiv v1
Run the calculation
Run CPython 3.12.4 and NumPy 1.26.4. Three queries belong to domain A, one to domain B. A large-norm document attracts the dot-product queries. Cosine fixes the three A rankings but still misses the B query. Consequently cosine’s query-average Recall, MRR and nDCG@2 are all 0.75, while their equal-domain averages are all 0.5. Dot-product query-average nDCG@2 is about 0.304089350. No encoder fitting, relevance tuning or real-text speed measurement occurs in this calculation.
import numpy as np
DOC_IDS=['d0','d1','d2','d3','d4','d5']
DOCS=np.array([[1.,0],[.9,.1],[0,1],[.1,.9],[2,2],[-1,0]])
QUERIES=np.array([[1.,0],[.9,.1],[0,1],[-1,0]])
JUDGMENTS=[{'d0':2,'d1':1},{'d1':2,'d0':1},{'d2':2,'d3':1},{'d4':1}]
DOMAINS=['A','A','A','B']
def ranking(query,documents,ids,cosine=True):
q=np.asarray(query,dtype=float);d=np.asarray(documents,dtype=float)
if len(ids)!=len(d) or len(set(ids))!=len(ids) or not np.isfinite(d).all() or not np.isfinite(q).all():raise ValueError('Use finite vectors and unique matching document IDs.')
if cosine:
norms=np.linalg.norm(d,axis=1);qn=np.linalg.norm(q)
if qn==0 or np.any(norms==0):raise ValueError('Cosine similarity needs nonzero vectors.')
scores=d@q/(norms*qn)
else:scores=d@q
return [key for key,score in sorted(zip(ids,scores),key=lambda item:(-item[1],item[0]))]
def metrics(order,relevance,k=2):
if len(order)!=len(set(order)) or k<1 or any(not np.isfinite(v) or v<0 for v in relevance.values()):raise ValueError('Use unique ranked IDs and positive k.')
positives={key for key,value in relevance.items() if value>0}
if not positives:return None
top=order[:k];hits=[i+1 for i,key in enumerate(top) if key in positives];gains=np.array([2.**relevance.get(key,0)-1 for key in top]);discount=np.log2(np.arange(2,len(top)+2));dcg=float(np.sum(gains/discount));ideal=sorted([2.**v-1 for v in relevance.values() if v>0],reverse=True)[:k];idcg=float(np.sum(np.array(ideal)/np.log2(np.arange(2,len(ideal)+2))))
return np.array([len(hits)/len(positives),0. if not hits else 1/hits[0],dcg/idcg])
def evaluate(cosine=True):
rows=np.array([metrics(ranking(q,DOCS,DOC_IDS,cosine),r) for q,r in zip(QUERIES,JUDGMENTS)]);domain_means=[rows[np.array(DOMAINS)==domain].mean(axis=0) for domain in sorted(set(DOMAINS))];return rows,rows.mean(axis=0),np.mean(domain_means,axis=0)
if __name__=='__main__':
for cosine in (False,True):
rows,micro,macro=evaluate(cosine);print('cosine' if cosine else 'dot product','per-query Recall/MRR/nDCG@2',rows.round(9).tolist());print('query mean',micro.round(9).tolist(),'equal-domain mean',macro.round(9).tolist())
print('no positive judgments',metrics(DOC_IDS,{},2),'policy: exclude and report separately, not a measured zero')
dot product per-query Recall/MRR/nDCG@2 [[0.5, 0.5, 0.521296029], [0.5, 0.5, 0.173765343], [0.5, 0.5, 0.521296029], [0.0, 0.0, 0.0]]
query mean [0.375, 0.375, 0.30408935] equal-domain mean [0.25, 0.25, 0.202726233]
cosine per-query Recall/MRR/nDCG@2 [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]
query mean [0.75, 0.75, 0.75] equal-domain mean [0.5, 0.5, 0.5]
no positive judgments None policy: exclude and report separately, not a measured zero
When the method fails
Incomplete judgments can penalize a genuinely useful unjudged result. Near-duplicate documents can inflate retrieval success, and overlap between pretraining, tuning and test material can make a benchmark easier without improving the intended application. Keep corpus versions, query IDs, relevance files and split rules alongside the scores.
Exact vector comparison over M documents of dimension d costs per query; sorting all scores costs here. Approximate search introduces another source of misses. Evaluate representation quality with exact search first when feasible, then measure the index’s recall and latency separately. BM25 is an appropriate lexical baseline for many text-retrieval settings; this vector-only example has no text with which to run it. BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models — arXiv v1
A deployment report should combine the relevant quality measures with memory, encoding cost, query latency and failures by domain or query type. Choose prompts, normalization, chunking and pooling using validation data. MTEB’s task diversity supports this broader view; a leaderboard average is not a substitute for testing the user’s workload. MTEB: Massive Text Embedding Benchmark — arXiv v1
Exercises with answers
- Why does cosine produce both 0.75 and 0.5 as valid averages here?
Answer 1: It scores one on all three A queries and zero on the B query. Query weighting gives 3/4; equal-domain weighting gives (1+0)/2.
- Can multiplying a document vector by ten change cosine rank?
Answer 2: Not for a positive scaling and nonzero vectors; it can change dot-product rank.
- How does this evaluator handle an empty positive-judgment set?
Answer 3: It returns None and requires separate reporting; it does not call the result a measured zero recall.
- What additional experiment is needed after switching to an approximate index?
Answer 4: Measure index recall relative to exact ranking as well as latency and memory; representation and index errors must not be conflated.
Sources and next steps
Read MTEB v1 Section 3.2 for task-specific protocols and BEIR v1 Section 4.2 for graded, rank-aware evaluation. Preserve exact versions when reproducing them: this chapter’s exponential gain and k=2 are not promised to match their implementation defaults. Continue with linear probes and the planned retrieval metrics chapter. MTEB: Massive Text Embedding Benchmark — arXiv v1; BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models — arXiv v1
Make a prediction, then check
A model scores 1 on three domain-A queries and 0 on one domain-B query. Its equal-domain average is?
Learning objectives
- Calculate ranking metrics with explicit gain, tie and missing-judgment policies.
- Separate query-weighted quality, domain balance and index approximation.
Prerequisites & connections
Explore related knowledge →References
- MTEB: Massive Text Embedding Benchmark — arXiv v1
Niklas Muennighoff; Nouamane Tazi; Loïc Magne; Nils Reimers · 2022 - BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models — arXiv v1
Nandan Thakur; Nils Reimers; Andreas Rücklé; Abhishek Srivastava; Iryna Gurevych · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, executable examples and corresponding bilingual equations, code and exercises. Not independent human or second-agent review.
- Four CPython 3.12.4 checks per chapter: spectra and exact recurrence with scale-aware tolerances, frozen ridge probes, literal graded retrieval metrics, whitening/SVD constraints, finite balancing marginals and stopped targets, pseudo-label denominator, exact noise expectation and temperature-weighted distillation as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; no real image/text benchmark reproduction claimed.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- MTEB: Massive Text Embedding Benchmark — arXiv v1 · Version 1 physical page 3, Section 3.2 task families and retrieval/reranking protocols; arXiv submission history confirms first version 2022-10-13.
- BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models — arXiv v1 · Version 1 physical pages 6–7, Section 4.2 nDCG@10 and TREC evaluation, Table 2 in-domain markings and cross-domain comparisons.
Related topics