When using Bag of Words or TF-IDF to turn text into numbers for models, the key metrics depend on the task. For classification, accuracy, precision, and recall matter because they show how well the model understands the text features. For ranking or search tasks, precision and recall help measure if the important words are captured well. These metrics tell us if the chosen text representation helps the model make good decisions.
Bag of Words and TF-IDF in ML Python - Model Metrics & Evaluation
Imagine a spam email classifier using TF-IDF features. Here is a confusion matrix after testing 100 emails:
| | Predicted Spam | Predicted Not Spam |
|-----------------|----------------|--------------------|
| Actual Spam | True Positives (TP) = 40 | False Negatives (FN) = 5 |
| Actual Not Spam | False Positives (FP) = 10 | True Negatives (TN) = 45 |
Total emails = 40 + 10 + 5 + 45 = 100
From this, we calculate:
- Precision = TP / (TP + FP) = 40 / (40 + 10) = 0.8
- Recall = TP / (TP + FN) = 40 / (40 + 5) = 0.89
- Accuracy = (TP + TN) / Total = (40 + 45) / 100 = 0.85
Using Bag of Words or TF-IDF, sometimes the model finds many spam emails but also marks some good emails as spam (high recall, lower precision). Other times, it only marks very sure spam emails (high precision, lower recall).
Example 1: If you want to avoid missing spam (catch all spam), prioritize high recall. You accept some good emails wrongly marked as spam.
Example 2: If you want to avoid marking good emails as spam, prioritize high precision. You accept missing some spam emails.
Choosing Bag of Words or TF-IDF affects this tradeoff because TF-IDF downweights common words, helping precision by focusing on important words.
For text classification using Bag of Words or TF-IDF:
- Good: Precision and recall above 0.8 means the model finds most relevant texts and avoids many mistakes.
- Bad: Precision or recall below 0.5 means the model either misses many relevant texts or marks many irrelevant texts.
- Accuracy alone can be misleading if classes are imbalanced (e.g., spam is rare).
- Accuracy Paradox: High accuracy can happen if most texts belong to one class, but the model fails on the minority class.
- Data Leakage: If the text features leak future information, metrics look better but model fails in real use.
- Overfitting: Very high training metrics but low test metrics means the model memorized training texts, not learned general patterns.
- Ignoring Class Imbalance: Not using precision and recall can hide poor performance on rare classes.
Your spam detection model using TF-IDF has 98% accuracy but only 12% recall on spam emails. Is it good for production?
Answer: No. The model misses 88% of spam emails (low recall), so it fails to catch most spam even if overall accuracy looks high. This is bad for user experience.
Practice
Solution
Step 1: Understand Bag of Words concept
Bag of Words counts how many times each word appears, ignoring order.Step 2: Identify what is counted
It counts word frequency, not order, sentiment, or length.Final Answer:
The frequency of each word appearing in the document -> Option BQuick Check:
Bag of Words = word counts [OK]
- Thinking Bag of Words considers word order
- Confusing frequency with sentiment
- Assuming it measures document length
Solution
Step 1: Import and initialize CountVectorizer
Correct import is from sklearn.feature_extraction.text import CountVectorizer and then create an instance.Step 2: Fit and transform documents
Use fit_transform to learn vocabulary and create the matrix in one step.Final Answer:
from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() matrix = vectorizer.fit_transform(documents) -> Option DQuick Check:
CountVectorizer + fit_transform = Bag of Words matrix [OK]
- Using transform without fit first
- Importing TfidfVectorizer instead of CountVectorizer
- Calling fit without transform or fit_transform
from sklearn.feature_extraction.text import TfidfVectorizer docs = ['cat dog', 'dog mouse', 'cat mouse mouse'] vectorizer = TfidfVectorizer() X = vectorizer.fit_transform(docs) print(X.shape)
Solution
Step 1: Count unique words across all documents
The words are 'cat', 'dog', 'mouse'. 'mouse' appears twice but counts once. So unique words = 3.Step 2: Check if TfidfVectorizer adds extra tokens
TfidfVectorizer by default tokenizes and counts unique words. Here, it finds 3 unique words: 'cat', 'dog', 'mouse'. So matrix shape is (number of docs, number of unique words) = (3,3).Step 3: Verify options
(3, 3) is (3,3), matching our count. But (3, 4) is (3,4), which suggests 4 unique words. Let's check if any extra token is created.Step 4: Check for default token pattern
By default, TfidfVectorizer splits on word boundaries, so no extra tokens. So shape is (3,3).Final Answer:
(3, 3) -> Option CQuick Check:
Docs=3, unique words=3, shape=(3,3) [OK]
- Counting repeated words multiple times
- Confusing rows and columns in shape
- Assuming extra tokens are added automatically
from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer() docs = ['apple orange', 'banana apple'] X = vectorizer.transform(docs) print(X.toarray())
Solution
Step 1: Understand TfidfVectorizer usage
Before calling transform, vectorizer must learn vocabulary using fit or fit_transform.Step 2: Identify error cause
Code calls transform directly without fitting, so vocabulary is unknown, causing error.Final Answer:
fit_transform should be used before transform to learn vocabulary -> Option AQuick Check:
fit_transform first, then transform [OK]
- Calling transform without fit
- Assuming toarray() is invalid (it is valid)
- Thinking TfidfVectorizer can't handle multiple docs
doc1 = 'apple apple orange' and doc2 = 'apple banana banana'. Using TF-IDF, which word will have the highest weight in doc2 and why?Solution
Step 1: Understand TF-IDF weighting
TF-IDF gives higher weight to words frequent in one document but rare across all documents.Step 2: Analyze word frequencies
'banana' appears twice in doc2 but not in doc1, so it is rare overall but frequent in doc2.Step 3: Compare with other words
'apple' appears in both docs, so its IDF is lower. 'orange' is not in doc2, so no weight there.Final Answer:
'banana', because it appears frequently in doc2 but less in doc1 -> Option AQuick Check:
TF-IDF favors unique frequent words [OK]
- Choosing common words across docs as highest weight
- Confusing frequency with uniqueness
- Ignoring that words not in doc have zero weight
Ready to prove it?
Pass the test and this pattern moves unknown
