Course contents 05 / 28

05 / 28 · Classical NLP

Bag of words and TF-IDF

Count vectors, explicitly defined TF-IDF, cosine ranking, and a reproducible logistic fit on four newly authored documents.

On this page 6

Four equipment-desk messages are enough to build a complete text representation by hand. We can count their words, rank them for a query, and fit a small classifier. The same calculation also reveals exactly what this representation cannot distinguish.

Baseline: counting tokens#

Fix a vocabulary with VV entries and an order for those entries. For document dd, let xdjx_{dj} be the number of occurrences of vocabulary token jj. The vector xd∈RVx_d\in\mathbb R^V is a bag-of-words representation: it retains multiplicities and discards order. The word bag distinguishes counts from a set, which records presence only.

The vocabulary is fitted on permitted training text. At prediction time, its order remains fixed. A token absent from the vocabulary contributes no coordinate under the simple policy used here. A document containing only unknown tokens therefore becomes a zero vector. Record this case rather than pretending that zero means an ordinary average document.

Our complete constructed collection is:

DocumentText
1desk lamp lamp pickup
2desk lamp return
3desk tripod return
4desk tripod tripod pickup

We use whitespace tokens and the vocabulary order desk, lamp, pickup, return, tripod. The count matrix is

X=(12100110101001110102).X=\begin{pmatrix} 1&2&1&0&0\\ 1&1&0&1&0\\ 1&0&0&1&1\\ 1&0&1&0&2 \end{pmatrix}.

Rows are documents and columns are vocabulary entries. Twelve of the twenty cells are nonzero. Larger vocabularies often make each document sparse because one document contains only a subset of all possible tokens. Sparse storage records the occupied coordinates rather than allocating every zero. Its benefit depends on the number of nonzeros and indexing overhead; a tiny dense matrix like ours does not demonstrate a storage benchmark.

A linear classifier on counts#

For binary classification, a linear score has the form zd=b+w⊤xdz_d=b+w^\top x_d. Each coefficient adds evidence when its token occurs, and the intercept supplies a default score. A logistic model converts the score to σ(zd)=1/(1+e−zd)\sigma(z_d)=1/(1+e^{-z_d}).

As an inference example, set the coefficient of return to two, pickup to minus one, all other coefficients to zero, and the intercept to minus one half. The four scores become −1.5,1.5,1.5,−1.5-1.5,1.5,1.5,-1.5. These coefficients are supplied by us. The calculation illustrates how a prediction is assembled; it is not a fitted performance result.

To learn coefficients, minimize a defined objective on labeled training rows. Logistic regression develops the model; for binary labels the unregularized loss per row is log⁡(1+ez)−yz\log(1+e^z)-yz. Its derivative with respect to the score is σ(z)−y\sigma(z)-y. Multiplying by each feature gives its gradient contribution. Regularization controls the coefficient scale, while held-out evaluation determines whether the fitted relationship generalizes.

Worked example#

For document 2, the vector is (1,1,0,1,0)(1,1,0,1,0). The hand-set score is −0.5+2=1.5-0.5+2=1.5: return contributes two and neither desk nor lamp changes the score. For document 1, repeating lamp does not matter under these particular coefficients, but pickup contributes minus one, giving −1.5-1.5.

If lamp had a nonzero coefficient, its repetition would multiply that contribution. A binary-presence representation would use one instead of two. Choosing counts, presence, or a transformed frequency is part of the representation and changes the model being fitted.

Where raw counts fail#

Counts confound topic and length. Copying a document twice doubles every count, which doubles a dot product with a fixed query vector even though the content has only repeated. The effect can be appropriate when repetition conveys evidence and inappropriate when it merely reflects formatting or message length.

Some tokens occur across nearly every document. desk occurs in all four of ours and cannot distinguish them by presence. A token appearing in fewer documents can be more discriminative for retrieval. That does not imply that every rare token is useful: a unique typo or random identifier is also rare.

Order is absent by construction. lamp before tripod and tripod before lamp have identical counts. A deterministic function of those counts must give them the same result, although the requested order differs. No change to the classifier’s optimizer repairs that representation collision.

Word bigrams add coordinates for adjacent pairs and can distinguish these two requests. They also expand the candidate vocabulary and require evidence for more combinations. Character n-grams can share fragments across inflections or misspellings, with a different balance between coverage and noise. These are representation changes to validate, not automatic improvements.

TF-IDF: reweighting the counts#

Let NN be the number of fitting documents, and let dfj\mathrm{df}_j count documents containing token jj at least once. Document frequency is a count of rows with a nonzero entry, not the total occurrences in a column. In our matrix, lamp occurs three times but appears in two documents.

There are several TF-IDF conventions. We explicitly use the smoothed convention documented by scikit-learn:

idfj=1+log⁡N+1dfj+1.\mathrm{idf}_j=1+\log\frac{N+1}{\mathrm{df}_j+1}.

The logarithm is natural. The added counts avoid a zero denominator for a retained vocabulary item with no occurrence in the fitting collection; the outer one keeps an everywhere-present token at weight one. This is a defined weighting scheme, not a theorem that it optimizes every task. Another convention might omit these additions and yield different values.

With raw count term frequency, set udj=xdjidfju_{dj}=x_{dj}\mathrm{idf}_j. A token’s relative weight decreases as its document frequency increases. Repetition still increases the weight linearly. A sublinear alternative uses 1+log⁡xdj1+\log x_{dj} for positive counts and zero for absent tokens, but we do not mix that alternative into the results below.

Finally, for a nonzero vector, define vd=ud/∥ud∥2v_d=u_d/\lVert u_d\rVert_2. A zero vector remains zero under our explicit policy. Normalization puts nonzero documents on the unit sphere. For two such vectors, their dot product equals cosine similarity. Doubling all counts in one document doubles its unnormalized vector and norm, leaving the normalized direction unchanged.

Fit the vocabulary and IDF on training documents only for a classifier evaluation. Queries and evaluation documents use the frozen weights. In a search index, the document collection may itself define the fitting corpus, but comparisons across index revisions must record that boundary. Adding documents changes IDF and can change rankings even when a particular document’s text is unchanged.

Worked example, continued#

Here N=4N=4 and document frequencies are (4,2,2,2,2)(4,2,2,2,2). Therefore desk has weight one; each other token has weight a=1+log⁡(5/3)≈1.510826a=1+\log(5/3)\approx1.510826. Document 1 has unnormalized vector (1,2a,a,0,0)(1,2a,a,0,0) and norm 1+5a2\sqrt{1+5a^2}. Its normalized vector is approximately

v1=(0.283833,  0.857643,  0.428821,  0,  0).v_1=(0.283833,\;0.857643,\;0.428821,\;0,\;0).

The query lamp pickup uses the same vocabulary and IDF. Its unnormalized vector is (0,a,a,0,0)(0,a,a,0,0), so the normalized query has the two nonzero coordinates 1/21/\sqrt2. The query-document dot products are:

DocumentCosine similarity
10.909668
20.452855
30
40.303223

Document 1 ranks first, followed by 2, 4, and 3. Document 2 matches lamp; document 4 matches pickup, but its repeated tripod contribution increases the normalization denominator. Document 3 shares neither query token, so its dot product is zero. The absence of desk from the query means that coordinate contributes no numerator term, while its document weight still affects each norm.

These are exact consequences of the chosen representation up to displayed rounding. A cosine of 0.909668 is not a probability that the document is relevant. The query has no independently collected relevance labels, so the ranking calculation does not establish retrieval effectiveness on a population.

A fitted model on the constructed collection#

We can also execute a small optimization without claiming external benchmark accuracy. Assign label one to the two return documents and zero to the two pickup documents. Fit logistic regression on the normalized TF-IDF vectors, starting all parameters at zero. The objective is mean binary log loss plus 0.1∥w∥22/20.1\lVert w\rVert_2^2/2, with no penalty on the intercept.

Use 400 full-batch gradient steps with learning rate 0.2. The regularized objective falls from 0.693147 to 0.550184. The intercept is −0.145358-0.145358. The fitted weights, rounded to six decimal places, are:

TokenWeight
desk0.251766
lamp−0.196273
pickup−0.772921
return1.153296
tripod−0.196273

In document order, the training probabilities are approximately 0.360389, 0.639749, 0.639749, and 0.360389.

All four training labels are recovered at threshold one half. There is no held-out set in this optimization demonstration, so this is a check of fitting mechanics, not a generalization estimate. The equality of the two pickup probabilities and the two return probabilities follows from symmetry between lamp and tripod in the supplied inputs and initialization.

The coefficients also show why interpreting one weight as a causal word effect is unsafe. desk appears in every raw document, yet its normalized coordinate differs with the document norm. The fitted model can use that difference. Coefficients describe a relationship in a particular representation and training collection; they do not tell us what would happen if we changed a word in a real causal process.

When a linear model on TF-IDF is the right choice#

A sparse linear model is a useful candidate when a task depends strongly on recurring lexical evidence and requires a transparent baseline. Individual score contributions can be inspected, fitting can be straightforward, and no pretrained language-model weights are needed. Whether it is sufficient is a validation question tied to language, domain, latency, and acceptable errors.

Check both what it gets wrong and why. A failure on an unseen synonym suggests a coverage problem. Failure to distinguish the two before requests follows from lost order. A stale IDF table reflects a changed representation distribution. These problems call for different experiments: richer features, context-sensitive representations, or an updated fitting/evaluation protocol.

For a new vocabulary item, silently extending the feature vector while leaving model weights unchanged does not define a learned behavior. Deploy vocabulary ordering, normalization, IDF, and coefficients as one compatible artifact. A model file without its vectorizer cannot reliably reproduce predictions.

What changed#

Raw counts now carry a corpus-relative weight and, in our chosen variant, a length normalization. The common desk coordinate has lower IDF than the distinguishing words, and duplicating all content does not change the normalized vector. The representation still loses word order and treats unknown tokens according to a fixed policy.

Limitations#

The fixture uses four short English documents and a deliberately simple whitespace tokenizer. It does not test multilingual segmentation, morphology, typo robustness, or realistic relevance judgments. The logistic fit uses only training observations. No external corpus or pretrained model is used.

Rare terms can be noise, repeated words can be meaningful, and normalized similarity can still favor the wrong document. TF-IDF supplies features and a geometric comparison; the downstream task needs an evaluation protocol and, where appropriate, a learned decision rule.

What you should remember#

Freeze vocabulary order and distinguish occurrence counts from document frequency. State the exact TF-IDF and normalization convention. Treat zero vectors explicitly and cosine scores as similarities. Inspect representation collisions before changing the classifier. A training fit on four invented documents is arithmetic evidence, not a benchmark claim.

Reproducible example#

  • The bag_of_words case in the standalone script contains every document, constructs counts and frozen IDF, computes query rankings, checks doubling invariance and the order collision, and runs the specified logistic fit. Centered finite differences check all six objective derivatives at the final parameters. Saved results include all vectors, coefficients, and probabilities. No external library or data download is required.

Next#

Counts can score a complete document but do not define how likely its order is. N-gram language models use a finite context to assign probabilities to successive tokens and expose the consequences of unseen continuations.

References#

  • Scikit-learn developers. Text feature extraction and TF-IDF weighting, version 1.9. Count/document-frequency definitions, smoothed IDF, sublinear frequency, and L2 normalization; no manual examples or implementation code reused.
  • Scikit-learn developers. Log loss, version 1.9. Categorical loss definition; derivatives and the constructed fit are calculated here.
  • Hugging Face course contributors. Tokenizers, revision 8b893f0. Vocabulary and unknown-input concepts; source examples, figures, and model artifacts are not reproduced.