Vector-space retrieval: rank directions, not just counts
向量空间检索
Rank lexical vectors with cosine and expose zero vectors, word-order loss and weighting choices.
vector-space-retrievalThe same direction at different lengths
Compare vectors (1,1) and (4,4) with query (1,0). Their raw dot products are 1 and 4, but they point in the same direction. Cosine assigns both about 0.707107. This can prevent a larger vector magnitude from dominating a comparison, but it does not make the representation understand the text.
Vector-space retrieval represents queries and documents in a common coordinate system and ranks their similarity. Here a coordinate is an indexed word, not a learned semantic feature. Our records “repair bicycle brake cable” and “brake cable bicycle repair” have the same counts and therefore identical vectors, although only the first contains the phrase “bicycle brake.” The IIR textbook connects lexical vectors, length normalization and this loss of word order. IIR, section 6.3
Specify the coordinates and weights
Fit a vocabulary on the document collection. N includes all nine records, including the empty one; df_t counts records containing term t. This differs from the nonempty-field statistic chosen in our BM25 example. We use natural logarithms, a smoothed IDF and logarithmic term frequency:
A document vector v_d contains these weights in the fixed vocabulary order. The query uses the same vocabulary and IDF; query terms outside it contribute no coordinate. Normalize nonzero vectors by their Euclidean norm. We choose a zero-vector fallback for empty or entirely unknown inputs:
For nonzero query and document vectors, the score is their cosine. The zero fallback produces score zero by policy; mathematically, the cosine of a zero vector is undefined.
Scaling an already formed vector by a positive constant preserves its direction and cosine:
This statement concerns the weighted vector. Duplicating raw text before applying logarithmic TF need not multiply every weighted coordinate by the same constant. Do not turn cosine’s scale invariance into a blanket claim that repeating a document never affects a retrieval score.
For two nonzero normalized vectors, expanding squared Euclidean distance gives another view of the same ordering:
Thus minimizing that distance is equivalent to maximizing cosine on the unit sphere. The identity does not apply unchanged to the zero-vector fallback, whose squared norm is zero rather than one.
Rank sixteen lexical coordinates
Run with Python 3.12 and NumPy 1.26.4. The program builds sixteen vocabulary coordinates from nine original fragments, computes document and query weights, normalizes them and scores all documents. It returns only positive scores and breaks ties by ascending ID. It also computes a variant with document IDF disabled while retaining query IDF, to make query/document weighting asymmetry explicit.
import json,math,re
from collections import Counter,defaultdict
DOCUMENTS=(
'repair bicycle brake cable',
'bicycle brake adjustment guide',
'bicycle paint blue frame',
'car brake cable repair',
'cycle stopping wire replacement',
'repair bicycle brake cable cable cable',
'',
'brake cable bicycle repair',
'cell cycle stopping research',
)
def tokens(text):
if not isinstance(text,str) or len(text)>2000:raise ValueError('text of at most2000 characters required')
return re.findall(r'[a-z]+',text.lower())
def corpus(documents):
if not isinstance(documents,(list,tuple)) or not 1<=len(documents)<=100:raise ValueError('one to100 documents required')
return [tokens(d) for d in documents]
import numpy as np
def fit(documents=DOCUMENTS):
rows=corpus(documents);vocab=sorted(set(t for ts in rows for t in ts));counts=[Counter(ts) for ts in rows];df=np.array([sum(t in c for c in counts) for t in vocab]);idf=np.log((1+len(rows))/(1+df))+1
return dict(vocab=vocab,idf=idf,counts=counts)
def weights(counts,vocab,idf,use_idf=True):
v=np.array([1+math.log(counts[t]) if counts[t]>0 else 0. for t in vocab]);return v*idf if use_idf else v
def unit(v):
v=np.asarray(v,dtype=float)
if v.ndim!=1 or not np.isfinite(v).all():raise ValueError('finite vector required')
# Rescale before squaring so finite extreme inputs retain their direction.
scale=float(np.max(np.abs(v))) if v.size else 0.
if scale==0:return np.zeros_like(v)
w=v/scale;return w/np.linalg.norm(w)
def rank(query,documents=DOCUMENTS,document_idf=True):
model=fit(documents);vocab=model['vocab'];idf=model['idf'];q=unit(weights(Counter(tokens(query)),vocab,idf));matrix=np.array([unit(weights(c,vocab,idf,document_idf)) for c in model['counts']]);scores=matrix@q
return [dict(doc=i,score=float(scores[i])) for i in sorted(range(len(scores)),key=lambda i:(-scores[i],i)) if scores[i]>0]
def demo():
model=fit();vocab=model['vocab'];idf=model['idf'];q=weights(Counter(tokens('bicycle brake cable')),vocab,idf);matrix=np.array([weights(c,vocab,idf) for c in model['counts']]);normed=np.array([unit(v) for v in matrix]);scores=normed@unit(q)
geometry=[]
for scale in [.5,1,2,4]:
v=np.array([1.,1.])*scale;query=np.array([1.,0.]);geometry.append(dict(scale=scale,dot=float(v@query),cosine=float(unit(v)@unit(query)),squared_distance=float(np.sum((unit(v)-unit(query))**2))))
return dict(documents=list(DOCUMENTS),vocabulary=vocab,idf=idf.tolist(),vectors=matrix.tolist(),normalized_vectors=normed.tolist(),query_vector=q.tolist(),scores=scores.tolist(),ranking=rank('bicycle brake cable'),document_without_idf=rank('bicycle brake cable',document_idf=False),order_collision=bool(np.array_equal(matrix[0],matrix[7])),geometry=geometry,unknown_query=rank('quasar'),empty_query=rank(''),scope='Sparse lexical coordinates stored densely for nine authored documents; no learned embeddings. Smoothed IDF, log TF and cosine are explicit conventions.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
For “bicycle brake cable,” the highest scores are approximately 0.866666 for record 5 and 0.849494 for records 0 and 7. Repeating cable in record 5 changes its direction; it does not simply multiply its vector. Records 0 and 7 remain tied because their word counts match. Record 4’s alternative vocabulary gives no overlap with the query, despite its declared relevance in the introductory retrieval task.
Turning off document IDF changes the leading scores to about 0.886341,0.864733,0.864733. It happens to preserve the order on this fixture; that is a computed result, not a theorem about all collections. A weighting configuration belongs in a reproducibility record alongside the vocabulary and corpus snapshot.
The geometry experiment multiplies (1,1) by 0.5,1,2,4. Raw dot product against (1,0) changes from 0.5 to 4, while cosine stays near 0.707107 and normalized squared distance near 0.585786. Normalization rescales by the largest absolute component before taking a norm, avoiding overflow and underflow for finite vectors such as (1e308,1e308) and (1e-308,1e-308). A naive direct norm failed that boundary test.
For T tokens, N documents and V vocabulary entries, this dense teaching implementation uses O(T+NV) preparation work and O(NV) vector storage. Scoring is O(NV) plus O(N log N) sorting. Sparse vectors and postings can avoid many zero-coordinate operations; dense storage here makes every coordinate easy to inspect.
“TF-IDF” does not identify a unique scorer
Lucene’s fixed ClassicSimilarity API documents sqrt(TF), a smoothed IDF and a field-length norm. Our log-TF cosine is a different combination, even though both belong to the broad lexical-weighting family. Matching a familiar name is insufficient for implementation equivalence. ClassicSimilarity
Compare against raw term overlap and a declared BM25 baseline using fixed development and test queries. Refit document representations when the corpus or vocabulary changes, and apply the same analyzer to queries. A query should not secretly alter the fitted IDF using its own text. Unknown words need an explicit policy: omission, lexical expansion or another retrieval channel; returning an empty list is the policy demonstrated here.
Cosine does not restore word order, resolve polysemy or connect unshared synonyms. An identical vector is a collision in this representation, not proof that two passages make identical claims. Position-aware matching and learned representations address different missing information. The existing TF-IDF article explains feature weights; this topic focuses on how those vectors become a ranked retrieval system.
Which invariance is actually guaranteed?
- Compute cosine between (1,1) and (1,0).
Answer: The dot product is one and the norms are sqrt(2) and one, so cosine is 1/sqrt(2), about 0.707107.
- Why do records 0 and 7 tie despite different word order?
Answer: The representation stores word counts in fixed coordinates. Their counts, weights and normalized vectors match, so every query gives them the same cosine score.
- Does multiplying a formed vector by four have the same invariance guarantee as repeating raw text four times before log-TF weighting?
Answer: No. The first is a uniform vector scaling. In the second, 1+log(4f)=1+log(f)+log(4); coordinates with different original frequencies need not share a common multiplicative change.
- What should happen when every query word is outside the fitted vocabulary?
Answer: The query vector is zero. This implementation returns no positive-scoring documents and does not divide by zero. An application can choose another fallback, but must define and evaluate it explicitly.
Geometry does not choose the vocabulary
The textbook develops cosine scoring and normalized lexical vectors; the Lucene API illustrates a different historical weighting choice. The numerical fixture and stable-normalization checks are original. They verify the chosen representation and its limits, without claiming a learned embedding model or benchmark advantage.
Make a prediction, then check
Can bag-of-words cosine distinguish two documents containing the same word counts in different orders?
Learning objectives
- Connect normalization, dot-product ranking, weighting asymmetry and lexical representation limits.
- Run the original small corpus and explain a failure case.
Prerequisites & connections
Explore related knowledge →References
- An Introduction to Information Retrieval — online draft, April 1, 2009
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2009 - ClassicSimilarity — Lucene 9.12.3 core API
Apache Lucene contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review. Read tf/idf/lengthNorm method definitions; sqrt TF and field-length normalization differ from our log-TF cosine. 5 paired equations and four explained exercises. Lexical coordinates, weighting asymmetry, order collision, normalized-distance identity and zero/OOV policy checked; stable norm fixes finite overflow/underflow.
- Lexical coordinates, weighting asymmetry, order collision, normalized-distance identity and zero/OOV policy checked; stable norm fixes finite overflow/underflow.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- An Introduction to Information Retrieval — online draft, April 1, 2009 · Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review.
- ClassicSimilarity — Lucene 9.12.3 core API · Read tf/idf/lengthNorm method definitions; sqrt TF and field-length normalization differ from our log-TF cosine.
Related topics