# Term Frequency and Inverse Document Frequency (tf-idf) Using Tidy Data Principles In tidytext: Text Mining using 'dplyr', 'ggplot2', and Other Tidy Tools

library(knitr)
opts_chunk$set( warning = FALSE, message = FALSE, eval = requireNamespace("ggplot2", quietly = TRUE) )  library(ggplot2) theme_set(theme_light())  A central question in text mining and natural language processing is how to quantify what a document is about. Can we do this by looking at the words that make up the document? One measure of how important a word may be is its term frequency (tf), how frequently a word occurs in a document. There are words in a document, however, that occur many times but may not be important; in English, these are probably words like "the", "is", "of", and so forth. We might take the approach of adding words like these to a list of stop words and removing them before analysis, but it is possible that some of these words might be more important in some documents than others. A list of stop words is not a sophisticated approach to adjusting term frequency for commonly used words. Another approach is to look at a term's inverse document frequency (idf), which decreases the weight for commonly used words and increases the weight for words that are not used very much in a collection of documents. This can be combined with term frequency to calculate a term's tf-idf, the frequency of a term adjusted for how rarely it is used. It is intended to measure how important a word is to a document in a collection (or corpus) of documents. It is a rule-of-thumb or heuristic quantity; while it has proved useful in text mining, search engines, etc., its theoretical foundations are considered less than firm by information theory experts. The inverse document frequency for any given term is defined as $$idf(\text{term}) = \ln{\left(\frac{n_{\text{documents}}}{n_{\text{documents containing term}}}\right)}$$ We can use tidy data principles, as described in the main vignette, to approach tf-idf analysis and use consistent, effective tools to quantify how important various terms are in a document that is part of a collection. Let's look at the published novels of Jane Austen and examine first term frequency, then tf-idf. We can start just by using dplyr verbs such as group_by and join. What are the most commonly used words in Jane Austen's novels? (Let's also calculate the total words in each novel here, for later use.) library(dplyr) library(janeaustenr) library(tidytext) book_words <- austen_books() %>% unnest_tokens(word, text) %>% count(book, word, sort = TRUE) total_words <- book_words %>% group_by(book) %>% summarize(total = sum(n)) book_words <- left_join(book_words, total_words) book_words  The usual suspects are here, "the", "and", "to", and so forth. Let's look at the distribution of n/total for each novel, the number of times a word appears in a novel divided by the total number of terms (words) in that novel. This is exactly what term frequency is. library(ggplot2) ggplot(book_words, aes(n/total, fill = book)) + geom_histogram(show.legend = FALSE) + xlim(NA, 0.0009) + facet_wrap(~book, ncol = 2, scales = "free_y")  There are very long tails to the right for these novels (those extremely common words!) that we have not shown in these plots. These plots exhibit similar distributions for all the novels, with many words that occur rarely and fewer words that occur frequently. The idea of tf-idf is to find the important words for the content of each document by decreasing the weight for commonly used words and increasing the weight for words that are not used very much in a collection or corpus of documents, in this case, the group of Jane Austen's novels as a whole. Calculating tf-idf attempts to find the words that are important (i.e., common) in a text, but not too common. Let's do that now. book_words <- book_words %>% bind_tf_idf(word, book, n) book_words  Notice that idf and thus tf-idf are zero for these extremely common words. These are all words that appear in all six of Jane Austen's novels, so the idf term (which will then be the natural log of 1) is zero. The inverse document frequency (and thus tf-idf) is very low (near zero) for words that occur in many of the documents in a collection; this is how this approach decreases the weight for common words. The inverse document frequency will be a higher number for words that occur in fewer of the documents in the collection. Let's look at terms with high tf-idf in Jane Austen's works. book_words %>% select(-total) %>% arrange(desc(tf_idf))  Here we see all proper nouns, names that are in fact important in these novels. None of them occur in all of novels, and they are important, characteristic words for each text. Some of the values for idf are the same for different terms because there are 6 documents in this corpus and we are seeing the numerical value for$\ln(6/1)$,$\ln(6/2)\$, etc. Let's look specifically at Pride and Prejudice.

book_words %>%
filter(book == "Pride & Prejudice") %>%
select(-total) %>%
arrange(desc(tf_idf))


These words are, as measured by tf-idf, the most important to Pride and Prejudice and most readers would likely agree.

## Try the tidytext package in your browser

Any scripts or data that you put into this service are public.

tidytext documentation built on Jan. 8, 2023, 1:12 a.m.
{"ft_lang_label":"__label__en","ft_lang_prob":0.93349236,"math_prob":0.8876355,"size":5196,"snap":"2023-40-2023-50","text_gpt3_token_len":1203,"char_repetition_ratio":0.14194915,"word_repetition_ratio":0.030805686,"special_character_ratio":0.2334488,"punctuation_ratio":0.09876543,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.98886675,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-09-29T01:01:17Z\",\"WARC-Record-ID\":\"<urn:uuid:1b8d4f04-5a9c-467d-898e-31ff95ae974a>\",\"Content-Length\":\"30944\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:6b6e5fe2-8eaf-4108-8f47-190326700284>\",\"WARC-Concurrent-To\":\"<urn:uuid:87f2db59-c57f-4a7e-ba78-b850d2d1dc19>\",\"WARC-IP-Address\":\"51.81.83.12\",\"WARC-Target-URI\":\"https://rdrr.io/cran/tidytext/f/vignettes/tf_idf.Rmd\",\"WARC-Payload-Digest\":\"sha1:BRMTYJCYDVGWZIWVYWOSHPOYOIFXCGZK\",\"WARC-Block-Digest\":\"sha1:SITBZVRGNME7XU4VJSQ76CK4MDPX3DXO\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233510462.75_warc_CC-MAIN-20230928230810-20230929020810-00402.warc.gz\"}"}