Tf–idf
In the vast oceans of text data we navigate daily, how do computers discern what's truly important? Tf–idf, or Term frequency–inverse document frequency, is a deceptively simple yet profoundly powerful algorithm that helps answer this question by quantifying the relevance of a word to a document within a larger collection. It's a foundational concept that underpins many of the search and recommendation systems we use every day, enabling machines to understand the unique characteristics of documents and surface the most meaningful information. Tf-idf is a statistical measure that quantifies a word's importance to a document by balancing its local frequency with its global rarity across an entire collection. This algorithm is a cornerstone of modern information retrieval, widely used by search engines and recommender systems to effectively rank and filter text data. Despite its heuristic origins, Tf-idf has deep theoretical links to information theory, providing a robust mathematical basis for its surprising effectiveness in identifying relevant content.
AI Summary
In the vast oceans of text data we navigate daily, how do computers discern what's truly important? Tf–idf, or Term frequency–inverse document frequency, is a deceptively simple yet profoundly powerful algorithm that helps answer this question by quantifying the relevance of a word to a document within a larger collection. It's a foundational concept that underpins many of the search and recommendation systems we use every day, enabling machines to understand the unique characteristics of documents and surface the most meaningful information.
- Tf-idf is a statistical measure that quantifies a word's importance to a document by balancing its local frequency with its global rarity across an entire collection.
- This algorithm is a cornerstone of modern information retrieval, widely used by search engines and recommender systems to effectively rank and filter text data.
- Despite its heuristic origins, Tf-idf has deep theoretical links to information theory, providing a robust mathematical basis for its surprising effectiveness in identifying relevant content.
The Language of Importance
Imagine trying to find the most relevant document in a library filled with millions of books, simply by counting how many times a particular word appears. You'd quickly realize words like 'the' or 'and' appear everywhere, telling you almost nothing about a document's true subject. This is the problem Tf–idf was designed to solve, moving beyond mere presence to actual significance.
Tf–idf stands for Term frequency–inverse document frequency. It's an ingenious weighting scheme that helps computers understand which words truly distinguish one document from another. Think of it as a sophisticated filter, highlighting the words that carry the most unique information.
This algorithm isn't just an academic curiosity; it's a workhorse of the digital age. A 2015 survey revealed that a staggering 83% of text-based recommender systems in digital libraries relied on Tf–idf, and variations of it are central to how search engines rank results, guiding you to the information you seek.
Term Frequency: How Often Does it Appear?
The first part of Tf–idf is 'Term Frequency,' or TF. This is the simpler half, measuring how often a specific term (t) appears within a particular document (d). The most straightforward way to calculate it is a raw count — simply how many times the word shows up.
Here, 'f{t,d}' represents the raw count of term 't' in document 'd'. However, a longer document will naturally have higher raw counts for all its words. To level the playing field, TF is often normalized by dividing the term count by the total number of words in that document, giving us a relative frequency.
tf(t, d) = f_{t,d}This normalized version tells us the proportion of a document that a particular term occupies. For instance, if 'apple' appears 5 times in a 100-word document, its TF would be 0.05. This helps ensure that document length doesn't unfairly inflate a term's perceived importance.
tf(t, d) = \frac{f_{t,d}}{\sum_{t' \in d} f_{t',d}}Inverse Document Frequency: How Unique is it?
Now for the 'Inverse Document Frequency,' or IDF — this is where the magic truly happens. IDF measures how unique or rare a term is across the entire collection of documents. Words that appear in almost every document, like 'is' or 'a,' carry very little specific information, no matter how often they appear in one particular text.
The genius behind IDF dates back to 1972, when computer scientist Karen Spärck Jones introduced the concept of 'term-specificity.' She observed that the true significance of a term could be quantified as an inverse function of the number of documents in which it occurs. A word that's common everywhere isn't particularly helpful for distinguishing one document from another.
The IDF formula involves a logarithm. Here, 'N' is the total number of documents in our collection, and the denominator is the number of documents that contain our specific term 't'. Taking the logarithm dampens the effect of extreme ratios and ensures that terms appearing in very few documents get a significant boost, while omnipresent words are heavily penalized.
idf(t, D) = \log \frac{N}{|\{d \in D : t \in d\}|}Combining the Powers: The Tf–idf Score
The final Tf–idf score is the product of these two components: Term Frequency multiplied by Inverse Document Frequency. This simple multiplication yields a powerful metric that captures both the local importance of a word within a document and its global rarity across the entire corpus.
A high Tf–idf score indicates a word that appears frequently in a specific document but is relatively rare in other documents across the collection. Such a word is highly characteristic of that particular document, making it an excellent indicator of its content or topic.
tfidf(t, d, D) = tf(t, d) \times idf(t, D)
Conversely, a low Tf–idf score would be assigned to words that are either very common everywhere (high IDF penalty) or very rare even in the document itself (low TF). This ingenious balancing act effectively filters out noise and spotlights the semantic jewels within mountains of text.
The Theory Behind the Magic
While Tf–idf has been a pragmatic success for decades, its deep theoretical underpinnings were a subject of extensive research. Many wondered why this seemingly heuristic approach worked so incredibly well. Researchers have spent years trying to find robust information-theoretic justifications for its effectiveness.
It turns out that Tf–idf is deeply connected to concepts from information theory, such as mutual information. In essence, each Tf–idf score can be interpreted as the 'bit of information' provided by a specific term within a document, helping us understand the joint informational content of that document-term pair.
Further demonstrating its statistical robustness, Tf–idf also shows strong links to statistical hypothesis testing, specifically related to the negative logarithmically transformed p-value from a one-tailed Fisher's exact test under certain idealized assumptions. This connection provides a powerful mathematical validation for its intuitive effectiveness.
Beyond Just Words
The core idea behind Tf–idf — weighting entities based on their local frequency and global rarity — isn't limited to just words. This versatile concept has been applied to various forms of data. For instance, it's been used to weight citations in academic papers, giving more importance to uncommon citations shared between documents.
Researchers have also adapted Tf–idf to 'visual words' in image and video processing for object matching, and even to entire sentences for summarization tasks. This demonstrates the profound impact and adaptability of Karen Spärck Jones's original insight, transforming how computers categorize and understand not just text, but information in many forms.
Derivatives and Innovations
The enduring utility of Tf–idf has inspired many derivatives. TF-PDF, for example, measures how often a term occurs in different domains to identify emerging topics. Another, TF–IDuF, calculates IDF based on a user's personal document collections, making it suitable for personalized recommendations without needing a global corpus.
Even sentiment analysis benefits from its principles. DELTA TF-IDF, for instance, focuses on the difference in a term's importance across two specific classes, like positive versus negative reviews. This helps identify words that are strong indicators of sentiment, leading to more accurate text classification models.
From identifying relevant articles on a search engine to powering personalized recommendations, Tf–idf remains a fundamental and elegant solution to a complex problem. It continues to be a testament to how combining simple statistical measures can unlock profound insights from the ever-growing deluge of information.
Article
Tf–idf
In information retrieval, tf–idf (term frequency–inverse document frequency, TFIDF, TFIDF, TF–IDF, or Tf–idf) is a measure of importance of a word to a document in a collection or corpus, adjusted for the fact that some words appear more frequently in general. Like the bag-of-words model, it models a document as a multiset of words, without word order. It is a refinement over the simple bag-of-words model, by allowing the weight of words to depend on the rest of the corpus.
It was often used as a weighting factor in searches of information retrieval, text mining, and user modeling. A survey conducted in 2015 showed that 83% of text-based recommender systems in digital libraries used tf–idf. Variations of the tf–idf weighting scheme were often used by search engines as a central tool in scoring and ranking a document's relevance given a user query. In applied search engine optimization practice, tf–idf is also described as a method for analysing term importance within web pages and supporting semantic SEO techniques. One of the simplest ranking functions is computed by summing the tf–idf for each query term; many more sophisticated ranking functions are variants of this simple model.
Motivations
Tf–idf
Karen Spärck Jones (1972) conceived a statistical interpretation of term-specificity called Inverse Document Frequency (idf), which became a cornerstone of term weighting:
The specificity of a term can be quantified as an inverse function of the number of documents in which it occurs.
For example, the df (document frequency) and idf for some words in Shakespeare's 37 plays might be represented as follows:
<table><thead><tr><th>Word</th><th>df</th><th>idf</th></tr></thead><tbody><tr><td>Romeo</td><td>1</td><td>1.57</td></tr><tr><td>salad</td><td>2</td><td>1.27</td></tr><tr><td>Falstaff</td><td>4</td><td>0.966</td></tr><tr><td>forest</td><td>12</td><td>0.489</td></tr><tr><td>battle</td><td>21</td><td>0.246</td></tr><tr><td>wit</td><td>34</td><td>0.037</td></tr><tr><td>fool</td><td>36</td><td>0.012</td></tr><tr><td>good</td><td>37</td><td>0</td></tr><tr><td>sweet</td><td>37</td><td>0</td></tr></tbody></table>
We see that "Romeo", "Falstaff", and "salad" appears in very few plays, so seeing these words, one could get a good idea as to which play it might be. In contrast, "good" and "sweet" appears in every play and are completely uninformative as to which play it is.
Definition
Tf–idf
• The tf–idf is the product of two statistics, term frequency and inverse document frequency. There are various ways for determining the exact values of both statistics. • A formula that aims to define the importance of a keyword or phrase within a document or a web page.
<table><thead><tr><th>weighting scheme</th><th>tf weight</th></tr></thead><tbody><tr><td>binary</td><td>{\displaystyle {0,1}}</td></tr><tr><td>raw count</td><td>{\displaystyle f{t,d}}</td></tr><tr><td>term frequency</td><td>{\displaystyle f{t,d}{\Bigg /}{\sum {t'\in d}{f{t',d}}}}</td></tr><tr><td>log normalization</td><td>{\displaystyle \log(1+f{t,d})}</td></tr><tr><td>double normalization 0.5</td><td>{\displaystyle 0.5+0.5\cdot {\frac {f{t,d}}{\max {\{t'\in d\}}{f{t',d}}}}}</td></tr><tr><td>double normalization K</td><td>{\displaystyle K+(1-K){\frac {f{t,d}}{\max {\{t'\in d\}}{f{t',d}}}}}</td></tr></tbody></table>
Term frequency
Term frequency, tf(t,d), is the relative frequency of term t within document d,
${\displaystyle \mathrm {tf} (t,d)={\frac {f{t,d}}{\sum {t'\in d}{f{t',d}}}}}$,
where ft,d is the raw count of a term in a document, i.e., the number of times that term t occurs in document d. Note the denominator is simply the total number of terms in document d (counting each occurrence of the same term separately). There are various other ways to define term frequency:
• the raw count itself: tf(t,d) = ft,d • Boolean "frequencies": tf(t,d) = 1 if t occurs in d and 0 otherwise; • logarithmically scaled frequency: tf(t,d) = log (1 + ft,d); • augmented frequency, to prevent a bias towards longer documents, e.g. raw frequency divided by the raw frequency of the most frequently occurring term in the document:
${\displaystyle \mathrm {tf} (t,d)=0.5+0.5\cdot {\frac {f{t,d}}{\max\{f{t',d}:t'\in d\}}}}$
Inverse document frequency
<table><thead><tr><th>weighting scheme</th><th>idf weight ({\displaystyle n{t}=|\{d\in D:t\in d\}|})</th></tr></thead><tbody><tr><td>unary</td><td>1</td></tr><tr><td>inverse document frequency</td><td>{\displaystyle \log {\frac {N}{n{t}}}=-\log {\frac {n{t}}{N}}}</td></tr><tr><td>inverse document frequency smooth</td><td>{\displaystyle \log \left({\frac {N}{1+n{t}}}\right)+1}</td></tr><tr><td>inverse document frequency max</td><td>{\displaystyle \log \left({\frac {\max {\{t'\in d\}}n{t'}}{1+n{t}}}\right)}</td></tr><tr><td>probabilistic inverse document frequency</td><td>{\displaystyle \log {\frac {N-n{t}}{n{t}}}}</td></tr></tbody></table>
Plot of different inverse document frequency functions: standard, smooth, probabilistic.
The inverse document frequency is a measure of how much information the word provides, i.e., how common or rare it is across all documents. It is the logarithmically scaled inverse fraction of the documents that contain the word (obtained by dividing the total number of documents by the number of documents containing the term, and then taking the logarithm of that quotient):
${\displaystyle \mathrm {idf} (t,D)=\log {\frac {N}{n{t}}}}$
• ${\displaystyle D}$: is the set of all documents in the corpus • ${\displaystyle N={|D|}}$: total number of documents in the corpus • ${\displaystyle n{t}=|\{d\in D:t\in d\}|}$ : number of documents where the term ${\displaystyle t}$ appears (i.e., ${\displaystyle \mathrm {tf} (t,d)\neq 0}$). If the term is not in the corpus, this will lead to a division-by-zero. It is therefore common to adjust the numerator to ${\displaystyle 1+N}$ and the denominator to ${\displaystyle 1+|\{d\in D:t\in d\}|}$.
Term frequency–inverse document frequency
<table><thead><tr><th>weighting scheme</th><th>tf-idf</th></tr></thead><tbody><tr><td>count-idf</td><td>{\displaystyle f{t,d}\cdot \log {\frac {N}{n{t}}}}</td></tr><tr><td>double normalization-idf</td><td>{\displaystyle \left(0.5+0.5{\frac {f{t,q}}{\max {t}f{t,q}}}\right)\cdot \log {\frac {N}{n{t}}}}</td></tr><tr><td>log normalization-idf</td><td>{\displaystyle (1+\log f{t,d})\cdot \log {\frac {N}{n{t}}}}</td></tr></tbody></table>
${\displaystyle \mathrm {tfidf} (t,d,D)=\mathrm {tf} (t,d)\cdot \mathrm {idf} (t,D)}$
A high weight in tf–idf is reached by a high term frequency (in the given document) and a low document frequency of the term in the whole collection of documents; the weights hence tend to filter out common terms. Since the ratio inside the idf's log function is always greater than or equal to 1, the value of idf (and tf–idf) is greater than or equal to 0. As a term appears in more documents, the ratio inside the logarithm approaches 1, bringing the idf and tf–idf closer to 0.
Justification of idf
Tf–idf
Idf was introduced as "term specificity" by Karen Spärck Jones in a 1972 paper. Although it has worked well as a heuristic, its theoretical foundations have been troublesome for at least three decades afterward, with many researchers trying to find information theoretic justifications for it.
Spärck Jones's own explanation did not propose much theory, aside from a connection to Zipf's law. Attempts have been made to put idf on a probabilistic footing, by estimating the probability that a given document d contains a term t as the relative document frequency,
${\displaystyle P(t|D)={\frac {|\{d\in D:t\in d\}|}{N}},}$
${\displaystyle {\begin{aligned}\mathrm {idf} &=-\log P(t|D)\\&=\log {\frac {1}{P(t|D)}}\\&=\log {\frac {N}{|\{d\in D:t\in d\}|}}\end{aligned}}}$
Namely, the inverse document frequency is the logarithm of "inverse" relative document frequency.
This probabilistic interpretation in turn takes the same form as that of self-information. However, applying such information-theoretic notions to problems in information retrieval leads to problems when trying to define the appropriate event spaces for the required probability distributions: not only documents need to be taken into account, but also queries and terms.
Link with information theory
Tf–idf
Both term frequency and inverse document frequency can be formulated in terms of information theory; it helps to understand why their product has a meaning in terms of joint informational content of a document. A characteristic assumption about the distribution ${\displaystyle p(d,t)}$ is that:
${\displaystyle p(d|t)={\frac {1}{|\{d\in D:t\in d\}|}}}$
This assumption and its implications, according to Aizawa: "represent the heuristic that tf–idf employs."
The conditional entropy of a "randomly chosen" document in the corpus ${\displaystyle D}$, conditional to the fact it contains a specific term ${\displaystyle t}$ (and assuming that all documents have equal probability to be chosen) is:
${\displaystyle H({\cal {D}}|{\cal {T}}=t)=-\sum {d}p{d|t}\log p{d|t}=-\log {\frac {1}{|\{d\in D:t\in d\}|}}=\log {\frac {|\{d\in D:t\in d\}|}{|D|}}+\log |D|=-\mathrm {idf} (t)+\log |D|}$
In terms of notation, ${\displaystyle {\cal {D}}}$ and ${\displaystyle {\cal {T}}}$ are "random variables" corresponding to respectively draw a document or a term. The mutual information can be expressed as
${\displaystyle M({\cal {T}};{\cal {D}})=H({\cal {D}})-H({\cal {D}}|{\cal {T}})=\sum {t}p{t}\cdot (H({\cal {D}})-H({\cal {D}}|W=t))=\sum {t}p{t}\cdot \mathrm {idf} (t)}$
The last step is to expand ${\displaystyle p{t}}$, the unconditional probability to draw a term, with respect to the (random) choice of a document, to obtain:
${\displaystyle M({\cal {T}};{\cal {D}})=\sum {t,d}p{t|d}\cdot p{d}\cdot \mathrm {idf} (t)=\sum {t,d}\mathrm {tf} (t,d)\cdot {\frac {1}{|D|}}\cdot \mathrm {idf} (t)={\frac {1}{|D|}}\sum {t,d}\mathrm {tf} (t,d)\cdot \mathrm {idf} (t).}$
This expression shows that summing the Tf–idf of all possible terms and documents recovers the mutual information between documents and term taking into account all the specificities of their joint distribution. Each Tf–idf hence carries the "bit of information" attached to a term x document pair.
Link with statistical theory
Tf–idf
Tf–idf is closely related to the negative logarithmically transformed p-value from a one-tailed formulation of Fisher's exact test when the underlying corpus documents satisfy certain idealized assumptions.
Example of tf–idf
Tf–idf
Suppose that we have term count tables of a corpus consisting of only two documents:
"This is a sample A." "This is another example, another example, example."
The calculation of tf–idf for the term "this" is performed as follows:
In its raw frequency form, tf is just the frequency of the "this" for each document. In each document, the word "this" appears once; but as the document 2 has more words, its relative frequency is smaller.
${\displaystyle \mathrm {tf} ({\mathsf {''this''}},d{1})={\frac {1}{5}}=0.2}$ ${\displaystyle \mathrm {tf} ({\mathsf {''this''}},d{2})={\frac {1}{7}}\approx 0.14}$
An idf is constant per corpus, and accounts for the ratio of documents that include the word "this". In this case, we have a corpus of two documents and all of them include the word "this".
${\displaystyle \mathrm {idf} ({\mathsf {''this''}},D)=\log \left({\frac {2}{2}}\right)=0}$
So tf–idf is zero for the word "this", which implies that the word is not very informative as it appears in all documents.
${\displaystyle \mathrm {tfidf} ({\mathsf {''this''}},d{1},D)=0.2\times 0=0}$ ${\displaystyle \mathrm {tfidf} ({\mathsf {''this''}},d{2},D)=0.14\times 0=0}$
The word "example" is more interesting - it occurs three times, but only in the second document:
${\displaystyle \mathrm {tf} ({\mathsf {''example''}},d{1})={\frac {0}{5}}=0}$ ${\displaystyle \mathrm {tf} ({\mathsf {''example''}},d{2})={\frac {3}{7}}\approx 0.429}$ ${\displaystyle \mathrm {idf} ({\mathsf {''example''}},D)=\log \left({\frac {2}{1}}\right)=0.301}$
${\displaystyle \mathrm {tfidf} ({\mathsf {''example''}},d{1},D)=\mathrm {tf} ({\mathsf {''example''}},d{1})\times \mathrm {idf} ({\mathsf {''example''}},D)=0\times 0.301=0}$ ${\displaystyle \mathrm {tfidf} ({\mathsf {''example''}},d{2},D)=\mathrm {tf} ({\mathsf {''example''}},d{2})\times \mathrm {idf} ({\mathsf {''example''}},D)=0.429\times 0.301\approx 0.129}$
(using the base 10 logarithm).
Beyond terms
Tf–idf
The idea behind tf–idf also applies to entities other than terms. In 1998, the concept of idf was applied to citations. The authors argued that "if a very uncommon citation is shared by two documents, this should be weighted more highly than a citation made by a large number of documents". In addition, tf–idf was applied to "visual words" with the purpose of conducting object matching in videos, and entire sentences. However, the concept of tf–idf did not prove to be more effective in all cases than a plain tf scheme (without idf). When tf–idf was applied to citations, researchers could find no improvement over a simple citation-count weight that had no idf component.
Derivatives
Tf–idf
A number of term-weighting schemes have derived from tf–idf. One of them is TF–PDF (term frequency proportional document frequency). TF–PDF was introduced in 2001 in the context of identifying emerging topics in the media. The PDF component measures the difference of how often a term occurs in different domains. Another derivate is TF–IDuF. In TF–IDuF, idf is not calculated based on the document corpus that is to be searched or recommended. Instead, idf is calculated on users' personal document collections. The authors report that TF–IDuF was equally effective as tf–idf but could also be applied in situations when, e.g., a user modeling system has no access to a global document corpus. The DELTA TF-IDF derivative uses the difference in importance of a term across two specific classes, like positive and negative sentiment. For example, it can assign a high score to a word like "excellent" in positive reviews and a low score to the same word in negative reviews. This helps identify words that strongly indicate the sentiment of a document, potentially leading to improved accuracy in text classification tasks.
External links and suggested reading
Tf–idf
• Gensim is a Python library for vector space modeling and includes tf–idf weighting. • Anatomy of a search engine Archived 2009-03-10 at the Wayback Machine • tf–idf and related definitions as used in Lucene • TfidfTransformer in scikit-learn • Text to Matrix Generator (TMG) MATLAB toolbox that can be used for various tasks in text mining (TM) specifically i) indexing, ii) retrieval, iii) dimensionality reduction, iv) clustering, v) classification. The indexing step offers the user the ability to apply local and global weighting methods, including tf–idf. • Term-frequency explained Explanation of term-frequency