The Vector Space Model and TF-IDF
Documents and queries as weighted term vectors — where inverse document frequency is the self-information of a term, and cosine normalization quotients document length away
Overview & motivation
The retrieval problem told us that retrieval is ranking by a relevance functional , and that cosine similarity is a natural choice for it — but it left the vectors abstract. The vector space model fills them in. A document becomes a point in a space with one axis per vocabulary word, its coordinate along each axis a weight for that term, and a query becomes a point in the same space; we rank by how aligned the two are. The entire art is in the weights, and two questions decide them: how much should repeating a word matter, and how much should a word matter at all?
The answers are term frequency and inverse document frequency. The first question has an easy direction — a document that says interest ten times is more about interest than one that says it once — and a subtler truth: not ten times more. The second has a sharper answer than it first appears: a word’s weight should be its surprise. A term that occurs in every document tells you nothing about which one you want; a rare term, when it appears, is strong evidence. We will make that intuition exact — inverse document frequency is precisely the self-information of a term’s presence — and it is the one genuine theorem in a topic otherwise built from honest conventions.
Before the algebra, drag the two toggles and watch the weights at work:
- 1.10-K · net interest margin sensitivity0.313
- 2.10-K · foreign-exchange risk0.248
- 3.10-K · boilerplate legal0.219
- 4.Earnings call · brief update0.160
- 5.News · Fed rate decision0.160
- 6.Earnings call · long Q&A (padded)0.100
Cosine normalization is all-or-nothing — it divides by the whole document norm. BM25 turns this into a dial (the b parameter) and adds a saturation ceiling.
Make the stakes concrete with the corpus this series carries throughout. A bank’s ninety-minute earnings call, transcribed, repeats interest and rate a dozen times each as conversational filler, padded out with hundreds of words about logistics, headcount, and guidance. A single sentence in the same company’s 10-K states the fact a risk analyst wants — that its net interest margin is sensitive to rate moves, its real interest rate exposure. Score these by the raw dot product of their term-weight vectors and the long transcript wins, not because it is more relevant but because length gives it more terms to accumulate. That is the length-hijack failure the retrieval problem warned us about when magnitude was free to vary, and cosine normalization is the vector space model’s answer to it. Panel C above stages exactly this: switch normalization off and the padded transcript seizes the top spot; switch it on and the concise filing surfaces.
What we cover
- Documents and queries as sparse term-weight vectors.
- Term frequency and the sublinear transform that makes repetition saturate — and why it is strictly increasing and concave.
- Inverse document frequency, and the theorem that it is the self-information of a term’s presence.
- The TF-IDF weight, assembled from the two.
- Cosine normalization, and how it quotients away the document-length magnitude.
- Where TF-IDF falls short — the two gaps that motivate BM25.
Documents and queries as term-weight vectors
Fix a vocabulary, the set of distinct terms across the collection, and give it an arbitrary but fixed order . Every document and every query then lives in the same -dimensional space, one coordinate per term.
Definition 1 (Vocabulary, term-vector space, and the bag of words).
Let be the vocabulary. A document is the vector whose coordinate is a weight , and a query is the vector in the same space. A weight of means term is absent from , so each document vector is sparse: its only nonzero coordinates are the distinct terms it contains. This representation is the bag of words — it records which terms occur, and with what weight, but discards their order.
This is the first concrete instance of the relevance functional from the retrieval problem: with documents and queries pinned down as vectors, becomes a similarity score on , and we are free to reuse the dot product, the Euclidean norm, and the cosine of the linear-algebra we already have. What remains is to choose the weights, and we build them in two independent pieces: a within-document piece (how often the term occurs here) and a collection-wide piece (how discriminating the term is at all).
Term frequency and sublinear scaling
The within-document piece is term frequency, the raw count of how many times occurs in . Used directly, raw count overpays for repetition: it treats the difference between one occurrence and two as worth exactly the difference between one hundred and one hundred and one. The fix is to scale the count so each additional occurrence is worth strictly less than the one before it.
Definition 2 (Sublinear term frequency).
The sublinear-scaled term frequency is
The choice of “diminishing returns” is not arbitrary hand-waving; it is a precise analytic property, and we can state and prove exactly what it means.
Proposition 1 (Sublinear tf is strictly increasing and strictly concave).
On , the map is strictly increasing and strictly concave. Consequently each additional occurrence of a term adds strictly less weight than the occurrence before it.
Proof.
Differentiate. The first derivative is strictly positive for , so is strictly increasing: more occurrences never lower the weight. The second derivative is strictly negative, so is strictly concave — this is the second-derivative criterion for concavity from the mean-value and Taylor theory. Strict concavity is exactly “diminishing returns”: the increment is itself decreasing in , so the jump from one occurrence to two exceeds the jump from two to three, and so on. The companion harness asserts both signs numerically on a dense grid in test_sublinear_tf_monotone_concave.
Hold on to one feature of this curve for later: it is concave, but it is unbounded. As the count grows, keeps rising, slowly but without ceiling. That is the seam at which BM25 will eventually depart from TF-IDF.
Inverse document frequency as self-information
The collection-wide piece is inverse document frequency, and here the topic earns its rigor. Let be the document frequency of term — the number of documents, out of , in which it appears — and define
The usual story stops at intuition: rare terms are informative, common terms are not, and the logarithm tames the range. We can do better and say exactly what quantity IDF is.
Definition 3 (Self-information).
The self-information (or pointwise surprise) of an event with probability is — the number of units of information carried by learning that occurred, large when is unlikely and zero when is certain. Measured with , the unit is the bit. This is the building block of Shannon entropy.
Theorem 1 (IDF is the self-information of a term's presence).
Draw a document uniformly at random from the collection of documents, and let be the event that the drawn document contains term , so that . Then the self-information of is exactly the inverse document frequency:
Proof.
The probability that a uniformly drawn document contains is the fraction of documents that do, . Substitute into the definition of self-information and simplify the logarithm of a quotient:
The identity is exact, and it holds in any base — base 2 reads the weight out in bits. test_idf_is_self_information checks it to machine precision for every term in the corpus.
So inverse document frequency is not a weighting trick; it is the surprise of a term’s presence, in bits. Two corollaries make the reading vivid, and the laboratory’s first panel shows both on our corpus. A term that appears in every document, , has and carries bits — finding it is no surprise at all, so it can do nothing to discriminate one document from another. In the finance corpus, rate occurs in all six documents and registers exactly bits; it is dead weight. A term appearing in a single document, , carries the maximum bits. Between them, exposure (in four of six documents) carries about bits and interest (in five) about — the rarer term is the louder signal.
Remark (A practical smoothing, and an honest flag).
The theorem is exact for the textbook form , and that is the form whose self-information reading we just proved. In practice we make two adjustments. We avoid dividing by zero for an out-of-vocabulary term, and — the reason it matters here — we keep a term that happens to appear in every document from vanishing entirely, since a universal-but-not-quite-uninformative word should still carry a whisper of weight. A standard remedy is the smoothed form , which stays strictly positive; it is what we use for the scoring below and what the laboratory ranks with. Smoothing is a convention, not a theorem — so we flag it as one, exactly as BM25 will flag the Jeffreys correction in its own relevance weight.
The TF-IDF weight
The two pieces multiply. A term earns weight in a document only if it is both present often enough to matter and discriminating enough to be worth counting.
Definition 4 (TF-IDF weight).
The TF-IDF weight of term in document is the product of its scaled term frequency and its inverse document frequency,
and the document vector is .
The product structure is the whole design. If a term is absent, and the weight is zero; if a term is everywhere, and the weight is zero again. Only a term that is both present and surprising contributes — term frequency says “this document uses the word,” inverse document frequency says “and the word is worth listening to.”
Cosine normalization and the length problem
With weight vectors in hand, the obvious score is the dot product . It has the pathology the retrieval problem diagnosed geometrically: it grows with the magnitude of , and a long document has a large magnitude for no better reason than that it contains many terms. The cure is to compare direction rather than magnitude — to score by the cosine of the angle between the vectors.
Definition 5 (Cosine similarity).
The cosine similarity of query and document is
the dot product of the two vectors after each has been normalized to unit length.
That this removes the length advantage is, again, something we can prove rather than assert.
Proposition 2 (Cosine is invariant to pure magnitude).
Let and replace by — an idealized “same document, scaled up” in which every term keeps its proportions. Then the cosine is unchanged while the raw dot product scales by :
Proof.
The dot product is linear in each argument, so — the raw score scales straight up with . The norm is absolutely homogeneous, for , so in the cosine the factor of appears once in the numerator and once in the denominator and cancels:
test_cosine_normalization_invariant confirms this on the corpus for .
This is precisely the “on the unit sphere the rankings coincide” result from the retrieval problem, now doing real work. The laboratory’s third panel makes it concrete on the finance corpus. Score with the raw dot product and the padded transcript tops the list at — its sheer length lets it out-accumulate everything. Switch on cosine normalization and the transcript’s enormous norm, swollen by hundreds of filler terms, divides its score down to the bottom; the concise on-point 10-K rises to first at a cosine of . Same query, same documents, one toggle, opposite winners — the lexical-retrieval echo of the dot-product-versus-cosine divergence the retrieval problem drew in two dimensions.
Where TF-IDF falls short: the bridge to BM25
Cosine TF-IDF is a strong, honest baseline, but it is a geometry, and two structural limits separate it from the probabilistic retrieval the next topic builds. Both are visible in the panels above.
Proposition 3 (Two structural gaps).
- Sublinear term frequency is unbounded. By Proposition 1, is concave but has no ceiling, so a single document repeating one query term enough times can still run away with the score. BM25 replaces the transform with a saturating one, , bounded above by .
- Cosine length normalization is document-global and untunable. The norm depends on every term in the document and applies all-or-nothing. BM25 normalizes by document length alone, through a single scalar with a dial that ranges from no normalization to full.
The first gap is the one to internalize, because it is the cleanest contrast. Sublinear tf and BM25’s saturating factor are both increasing and both concave — but one rises forever and the other levels off at a finite ceiling. The harness makes the difference quantitative in test_sublinear_unbounded_vs_bm25_bounded: as the count grows, climbs past any fixed bound while the BM25 factor stays pinned below . Neither limit is a flaw in TF-IDF so much as the boundary of what a fixed geometry can express. Crossing it — turning the all-or-nothing norm into a tunable dial, and the unbounded log into a saturating curve — is exactly the work of the Binary Independence Model and BM25, and the IDF factor we derived here carries over unchanged as the term-weighting core they inherit.
Finance case study
Honest caveats
Implementation
The companion notebook (notebookPath) builds the inverted index, computes IDF in both the textbook and smoothed forms so the self-information identity is visible alongside the form used for scoring, assembles TF-IDF weight vectors, and ranks by both the raw dot product and cosine. Its verification harness asserts every claim made above: that IDF equals the self-information to machine precision, that sublinear tf is increasing and concave on a dense grid, that cosine is invariant to magnitude scaling, that sublinear tf outgrows BM25’s bounded factor, and — the headline — the length-hijack flip on the shared finance corpus.
Running it prints the claims back as passing assertions. The IDF table shows the surprise of each query term in bits ( for interest, for the universal rate, for exposure). The finance demo then scores the six-document corpus for “interest rate exposure” two ways: by the raw tf-idf dot product, where the padded transcript ranks first at , and by cosine, where the concise on-point filing surfaces to first at while the transcript falls to last. That cosine ranking is cross-checked against scikit-learn’s TfidfVectorizer, so any divergence would flag a genuine bug rather than a known formula difference. The interactive laboratory mirrors these numbers to the decimal — the math, the viz, and the notebook are three views of one computation.
Connections
- this topic instantiates the relevance functional defined there: documents and queries become weighted term vectors and rel(q,d) becomes their cosine similarity, with cosine normalization addressing the exact off-sphere magnitude divergence that topic formalizes the-retrieval-problem
- BM25 refines this topic point for point — it reuses the IDF factor introduced here, replaces unbounded sublinear tf with a saturating transform, and replaces untunable cosine length normalization with the tunable b parameter, so this topic is the lexical foundation BM25 sharpens bm25-binary-independence-model
References & Further Reading
- book Introduction to Information Retrieval — Manning, Raghavan & Schütze (2008) Chapters 6–7: term weighting, the vector space model, tf-idf, and cosine scoring
- paper A Statistical Interpretation of Term Specificity and its Application in Retrieval — Spärck Jones (1972) The original inverse document frequency paper; term specificity as a collection statistic
- paper Understanding Inverse Document Frequency: On Theoretical Arguments for IDF — Robertson (2004) The information-theoretic reading of IDF as self-information that this topic follows
- paper Term-Weighting Approaches in Automatic Text Retrieval — Salton & Buckley (1988) The systematic tf-idf weighting-scheme comparison and the case for cosine normalization
- documentation scikit-learn: tf-idf term weighting (TfidfVectorizer) The reference implementation the notebook cross-checks its cosine ranking against