Bag-of-Words, TF-IDF, and Cosine Similarity
Explore techniques to convert product reviews into numerical features using bag-of-words and TF-IDF. Learn how to weight distinct terms and rank similarities between documents with cosine similarity to improve text retrieval and analysis. This lesson helps you understand how to represent text data numerically and measure its relevance across a corpus.
A complaint reading battery drains after two hours needs a way to find related past reviews without hand-written matching rules. Because normalization has already turned text into consistent tokens, we can now convert each review into numbers, weight the useful terms, and rank reviews by similarity.
A corpus is the complete set of documents we search. For this lesson, the corpus contains short product reviews such as battery drains quickly, battery lasts all day, and charger stopped working. The vocabulary is the set of unique tokens found across that corpus. A bag-of-words (BoW) represents each document by counting how often every vocabulary term appears.
BoW ignores word order. The reviews battery drains quickly and quickly drains battery therefore receive identical counts. That loss is deliberate here because the immediate task is retrieval based on shared terms, not an interpretation of sentence structure.
Count terms with bag-of-words
The retrieval pipeline begins by fitting CountVectorizer on the review corpus. CountVectorizer creates a vocabulary and produces a document-term matrix, where each row represents one review and each column represents one vocabulary term.
Lines 5–18: The code defines a corpus of 12 short product reviews.
Lines 20–25:
CountVectorizer().fit_transform(reviews)learns the corpus vocabulary and returns a sparse document-term matrix; printing ...