Important Words
Words by the Numbers
Chapter 8 ยท What Makes a Word Important
Words by the Numbers 7 scored how hard a text is to read. This chapter asks which words in a text matter. The most frequent words are almost never the answer: the tops nearly every count, as Words by the Numbers 2 showed, and tells you nothing about a text. What you want is a word that is frequent here and rare elsewhere. Putting those two ideas into one number gives TF-IDF, the weighting behind keyword extraction and a good deal of classic search. The maths is one logarithm and one multiplication, and by the end you will have a working search ranker in a few dozen lines.
Frequent Here, Rare Elsewhere
The idea of weighting a word by how few documents contain it comes from Karen Spärck Jones. Her paper "A statistical interpretation of term specificity and its application in retrieval" appeared in the Journal of Documentation in 1972 (volume 28, pages 11 to 21, per the search). It counted the documents in a collection that contain a term and gave rare terms more weight; the name inverse document frequency came later. One explainer page credits the other half of the recipe, counting how often a term occurs in a document, to Hans Peter Luhn of IBM in the 1950s (the date 1957 appeared in my query, not in a page I could read, and only that one page mentioned Luhn, so check it). Search engines went on to refine the weighting. A family of formulas called BM25, from the Okapi system at City University London, is a descendant; the sources conflict on the date, giving 1994 in some places and 1995 in others, so I leave it at "mid 1990s". I did not check how modern search engines are built beyond that.
The Maths, Worked by Hand
Take a collection of N documents. For a word in one document, three numbers matter.
- tf, the term frequency: how many times the word occurs in the document, divided by the document's length in words (dividing makes long and short documents comparable).
- df, the document frequency: how many documents contain the word at least once.
- idf, the inverse document frequency:
ln(N / df), the natural logarithm of N divided by df. A word in every document hasln(1) = 0; a word in one of four documents hasln(4) = 1.386.
The score is tf × idf. The logarithm is there so that rarity helps without taking over: a word in 1 document out of 1,000 is not 1,000 times as informative as a word in every document, it is worth ln(1000) = 6.9. The base of the logarithm only rescales every score by the same factor, so the ranking does not depend on it. The first snippet applies this to four invented mini-documents about cats, dogs and a bank.
Look at document A, "the cat sat on the mat and the cat purred", which has 10 words. The table below does the sums for five of its words. The word the occurs 3 times, the most of any word, but it is in all four documents, so its idf is zero and so is its score. cat occurs twice in A and in one other document (df = 2); mat and purred occur once each and nowhere else (df = 1). The ranking comes out as a tie: a word that is twice as frequent in the document but twice as widespread (idf 0.693 against 1.386) scores exactly the same as a word that occurs once and nowhere else. That is the trade the formula makes, and the rest of the chapter is about whether it is a good one.
| Word in A | Count | tf (of 10) | df (of 4) | idf | tf × idf |
|---|---|---|---|---|---|
| the | 3 | 0.300 | 4 | 0.000 | 0.000 |
| on | 1 | 0.100 | 3 | 0.288 | 0.029 |
| sat | 1 | 0.100 | 2 | 0.693 | 0.069 |
| cat | 2 | 0.200 | 2 | 0.693 | 0.139 |
| mat | 1 | 0.100 | 1 | 1.386 | 0.139 |
| Weight | Rewards | Fails on |
|---|---|---|
| tf alone | words the author repeats | puts the and of at the top |
| idf alone | words few documents use | rewards a one-off typo as much as a key term |
| tf × idf | words repeated here and rare elsewhere | depends on what the other documents are |
Keywords from Whole Books
Now real text. The next snippet treats each of the four books (the same ones as Words by the Numbers 7) as one document, so N = 4, and prints for each book its most frequent words next to its top words by TF-IDF. With only four documents, idf can take just four values: 0 for a word in all four books, 0.288 for three, 0.693 for two and 1.386 for one.
| Book | Most frequent words | Top by TF-IDF |
|---|---|---|
| Alice in Wonderland | the, and, to, a, she, it | alice, mock, turtle, hatter, gryphon, rabbit |
| The Time Machine | the, i, and, of, a, to | traveller, morlocks, weena, machine, sphinx, medical |
| Pride and Prejudice | the, to, of, and, her, i | elizabeth, darcy, bennet, jane, bingley, mrs |
| The Federalist Papers | the, of, to, and, in, a | states, government, national, federal, executive, members |
The difference is dramatic. Raw frequency gives the same kind of list for every book. TF-IDF gives you, at a glance, names and places in the three novels (a Mock Turtle, a Gryphon, the Morlocks, the Bennets) and the vocabulary of government in the essays. Only 898 of the 14,115 distinct words occur in all four books, so they all score zero, and 8,709 occur in just one. The method is also blunt here: with so few documents, mrs ranks as a keyword of Pride and Prejudice simply because the other books use it less, and the Federalist list is generic (states, government) because the other three books say little about the subject. Keywords depend on the collection you compare against, a point Exercise 2 pushes further.
A Tiny Search Engine
Searching is keyword extraction run backwards. Instead of asking which words characterise a document, you give the words and ask which documents they characterise. The standard structure is an inverted index: a dictionary from each word to the documents containing it and the count in each, so a query only touches the documents that contain its words. To make the collection big enough to be interesting, the next snippet cuts every book into 500-word pieces and treats each piece as a document, 755 in all. A piece's score for a query is the sum, over the query words, of (1 + ln(count)) × idf. The 1 + ln(count) is a common softening (check how widely it is used): the tenth occurrence of a word should not count ten times as much as the first.
| Query (mine) | Expected book (mine) | Top 10 from that book |
|---|---|---|
| white rabbit | Alice in Wonderland | 10 |
| time traveller | The Time Machine | 10 |
| darcy bingley | Pride and Prejudice | 10 |
| union states constitution | The Federalist Papers | 10 |
| the of and to rabbit, with idf | Alice in Wonderland | 10 |
| the of and to rabbit, without idf | Alice in Wonderland | 4 |
Four things to take from the output. First, the ranker works on short queries, and the counts show why: the top piece for white rabbit has six of each word. Second, idf is what rescues the query that is padded with function words. Without it, the, of, and and to add the same weight as rabbit in every piece, and only 4 of the top 10 come from the right book; with it, all 10 do, because those four words appear in so many pieces that they weigh almost nothing. The last line of output is the extreme case: for the query "the of" every piece scores exactly zero, because both words are in all 755 pieces (ln(755 / 755) = 0). Third, the test is easy and I rigged it a little: the four books differ sharply in vocabulary, the queries are mine, and "right book" is a stand-in for "relevant", which is not the same thing. Fourth, the snippet scores every piece of a book on its own words, with no notion of word order, phrases or meaning, so a query like "white rabbit" would also reward a piece with six whites about something else (that was not tested here).
ln(N / df) of a word that is not in the index (a division by zero, or a quiet skip as the snippet does); comparing scores across queries as if they were probabilities (they are only for ranking within one query); leaving markup, headers and page numbers in the text, so that illustration becomes a keyword; ignoring word forms (rabbit and rabbits are separate words here); not normalising by document length when documents differ in size; and judging a ranker only on queries you designed to succeed.
Using the four invented mini-documents, compute idf for df = 1 to 4 under two formulas: the plain ln(N / df) and a smoothed ln(1 + N / df). Print the top three words per document under each. Which variant lets the back into the top three, and is that a good thing?
Use the 755 pieces as the collection and extract keywords for each book by adding up the TF-IDF of each word over the book's pieces. Print the top eight, first with every word allowed and then ignoring any word that occurs in more than 20% of the pieces. Which words appear in the first list and not in the second, and why did the first list differ from the one built on four documents?
๐ View solutionEvaluate the search ranker on eight natural-language queries (two per book, each padded with words like the and and). For three scoring schemes (raw count, softened count, softened count times idf), print how many of the top 10 pieces come from the book you expected, with a total at the bottom. Which scheme degrades most when the query is full of common words?
๐ View solutionQuick Reference
- tf: count of the word in the document divided by the document's length
- df: number of documents containing the word at least once
- idf:
math.log(N / df); zero for a word in every document,ln(4) = 1.386for one in one of four - TF-IDF:
tf * idf; high for words frequent here and rare elsewhere - Collection matters: keywords change when the other documents change (with four books, mrs was a keyword of one)
- Inverted index:
{word: {doc_id: count}}, so a query only visits the documents that contain its words - Ranking: sum
(1 + math.log(count)) * idfover the query words; in the test, 10 of 10 right with idf and 4 of 10 without on a query padded with common words - Variants: smoothed idf such as
ln(1 + N / df)keeps common words from scoring zero (Exercise 1); BM25 is a descendant used in search engines - Source conflict: the Okapi BM25 work is dated 1994 in some sources and 1995 in others