sciencenotes.medium.com 4 min read Original Source

How to Calculate TF-IDF in Python

A code-based tutorial for cleaning, tokenization, lemmatization, calculating term frequency, and calculating TF-IDF for a collection of text documents in Python. You can also consider this tutorial as NLTK for beginners.

TF-IDF reflects the importance of a word to a document in a collection or corpus. In this tutorial, the final plan is to calculate TF-IDF for a collection of text documents. We go forward step by step.

  1. Cleaning each text document.
  2. Tokenizing, stemizing, and Lemmatizing each text document.
  3. Calculating Term Frequency (TF) for the collection of documents.
  4. Calculate Inverse Document Frequency (IDF) for the collection of documents.
  5. Calculate Term Frequency-Inverse Document Frequency (TF-IDF) for the collection of documents.

Here, suppose that the corpus C is the collection of text documents containing |d| number of documents. We need the following libraries.

[Embedded content: ea9f988a3dbd87d6bb2a343775253f89]

1. Text Cleaning

Preprocessing text data means removing tokens that are not helpful for the final model; for example, punctuations and numbers, meaningless words, common English stopwords, etc. However, it might differ for each text analysis task.

The first step in text preprocessing is to remove such words from the documents. In this part, I created a function called denoiser() to clean the data by removing the mentioned words/numbers using NLTK. denoiser() It takes the text in a document in raw format as input and returns the cleaned or denoised text.

denoiser() uses re, unicodedata, contractions, and nltk.corpus Python libraries. Using contractions, we convert words with ” ‘ ” to two separated words: e.g. “isn’t” turns to “is not”. It

  • removes all punctuations and numbers using re
  • removes common English stopwords using nltk.corpus.stopwords
  • removes non-ASCII characters using unicodedata.normalize
  • removes URLs, emails, and mentions
  • converts words to lower case

[Embedded content: acd51748092eca523f21de90b6a30b7b]

2. Text Tokenization and Lemmatization

Token is the smallest meaningful unit in the language processing, for example, works, characters, or subwords. Tokenization is a method for dividing a raw text into tokens.

[Embedded content: 45b2180d276088be127026021f8aa6d3]

After Tokenization, we apply stemming and lemmatization. The goal of both stemming and lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form. tokenizer() uses nltk Python libraries. It

  • Tokenizes each documnet using nltk.word_tokenize
  • Stemizes tokens
  • Lemmatizes tokens with respect to the verbs.

3. Term Frequency (TF)

The Term Frequency (TF) is the number of times a token occurs in a text document. For analysing multiple documents, TF score is relative to a specific document, therefore you need to normalize it by dividing with the total number of tokens appearing in the document.

A normalized TF score for a specific token t, in document d, is calculated as,

where nᵈ(t) is the number of times a token t appears in a document d. term_freq() function

  1. Takes a text document,
  2. Compute the length of documents,
  3. For each type in the document counts the number of occurrences,
  4. Saves the frequency of each type as the value of the time in the dictionary.
  5. Returns the dictionary.

[Embedded content: 4d865e01faad5817d344a102ff9058de]

4. Inverse Document Frequency (IDF)

The Inverse Document Frequency (IDF) counts the number of documents in the corpus and the number of documents containing a token. While the TF is calculated on a per-document basis, the IDF is computed on the basis of the entire corpus. The final IDF score of a token t in the corpus C is obtained by taking logarithm of document count in the corpus divided by the number of documents in the corpus containing a particular token. The IDF formula is given as

where I(t, d) is an indicator function that returns 1 if a token t exists in document d. |C| is the total number of documents in the corpus.

ind() function in the below code is the implementation of I(t, d). It is just an indicator function that takes a document and a token as inputs and returns 1 if a type belongs to the document and 0 otherwise.

[Embedded content: 753fe11595549730338aa9b494485a98]

Inv_DF() function takes two inputs: tokens and corpus. And

  1. For each type, counts the number of documents containing that type.
  2. ind() goes through all dictionaries in the TF file and checks if the type is in the list of keys of the dictionaries.
  3. It returns a dictionary. The keys of this dictionary are all types in the corpus, and the values are the number of documents containing that type.

5. Term Frequency Inverse Document Frequency (TF-IDF)

For a given token t and a document d in the corpus C, TF-IDF(t,d) is the product of TF(t,d) and IDF(t):

[Embedded content: 3e44df34c47dc48231b80365ce6ecc23]

Having TF and IDF functions from parts 2 and 3, it is easy to calculate TF-IDF.

tf_idf() function

  1. Takes the TF list (or a portion of it), and the IDF dictionary.
  2. For each dictionary in the TF list, it passes over all the keys, which are types, and for each key gets the value.
  3. This key has value in the IDF dictionary as well. So, within the for loop, it gets the value of that key in the IDF dictionary.
  4. Then the answer is the multiplication of these two values.
  5. Returns a dictionary that the keys are all types in the corpus and the values are the TF-IDF.

Wrap up

To wrap up, let’s try computing TD-IDF for 20 news groups data set.

[Embedded content: d246ac3a89f7e313ecb3f46c16bef2d9]

The above code returns TF-IDF for each token in the 20 news group dataset that is the corpus.

Wrap up:

In this tutorial, I shared tips to have organized and clean code or repository. You might find some or all the tips simple, which I believe they really are, but still handy.

Join Medium to read great tutorials and stories!
I write Machine Learning, Deep Learning and Data Science tutorials. Upgrade to read more.

sciencenotes.medium.com

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Build awareness and adoption for your tech startup with Circuit.