TF-IDF vectorization

Natural Language Processing (NLP) in Python

Fouad Trad

Machine Learning Engineer

From BoW to TF-IDF

  • BoW treats all words as equally important
  • TF-IDF fixes this by telling:
    • how often a word appears in a document
    • how meaningful that word is across a collection

 

Image showing the BoW representation of two sentences: 'I love this NLP course' and 'I enjoyed this project.'

Natural Language Processing (NLP) in Python

TF-IDF

Image showing that TF-IDF is the product of TF and IDF.

Natural Language Processing (NLP) in Python

TF-IDF

Image showing that TF-IDF is the product of TF and IDF.

  • TF: Term Frequency
    • How many times a word appears in a document
Natural Language Processing (NLP) in Python

TF-IDF

Image showing that TF-IDF is the product of TF and IDF.

  • TF: Term Frequency
    • How many times a word appears in a document
  • IDF: Inverse Document Frequency
    • How rare that word is across all documents

 

  • Word shows up in one document, not in others → high score
  • Word appears in every document → low score
Natural Language Processing (NLP) in Python

TF-IDF with code

reviews = [
    "I loved the movie. It was amazing!",
    "The movie was okay.",
    "I hated the movie. It was boring."
]

cleaned_reviews = [preprocess(review) for review in reviews] print(cleaned_reviews)
['i loved the movie it was amazing', 
 'the movie was okay', 
 'i hated the movie it was boring']
Natural Language Processing (NLP) in Python

TF-IDF with code

from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(cleaned_reviews)
print(tfidf_matrix)
<Compressed Sparse Row sparse matrix of dtype 'float64'
    with 16 stored elements and shape (3, 9)>
Natural Language Processing (NLP) in Python

TF-IDF output

print(tfidf_matrix.toarray())
[[0.52523431 0.         0.         0.39945423 0.52523431 0.31021184   0.         0.31021184 0.31021184]
 [0.         0.         0.         0.         0.         0.41285857   0.69903033 0.41285857 0.41285857]
 [0.         0.52523431 0.52523431 0.39945423 0.         0.31021184   0.         0.31021184 0.31021184]]
vectorizer.get_feature_names_out()
['amazing' 'boring' 'hated' 'it' 'loved' 'movie' 'okay' 'the' 'was']
Natural Language Processing (NLP) in Python

Visualizing scores as heatmap

import pandas as pd

df_tfidf = pd.DataFrame(

tfidf_matrix.toarray(),
columns=vectorizer.get_feature_names_out() )
import seaborn as sns
import matplotlib.pyplot as plt

sns.heatmap(df_tfidf, annot=True)
plt.title("TF-IDF Scores Across Reviews") plt.xlabel("Terms") plt.ylabel("Documents") plt.show()

 

Heatmap of the TF-IDF representation of the dataset.

Natural Language Processing (NLP) in Python

Comparing with BoW

 

Heatmap of the BoW representation of the dataset.

 

Heatmap of the TF-IDF representation of the dataset.

Natural Language Processing (NLP) in Python

Let's practice!

Natural Language Processing (NLP) in Python

Preparing Video For Download...