In text classification, we want to know how well the model sorts texts into correct groups. The key metrics are Precision, Recall, and F1 score. Precision tells us how many texts labeled as a category really belong there. Recall tells us how many texts of a category the model found. F1 score balances both. These matter because sometimes we want to avoid wrong labels (high precision), or catch all relevant texts (high recall), depending on the task.
Text classification pipeline in ML Python - Model Metrics & Evaluation
| Predicted Positive | Predicted Negative |
|--------------------|--------------------|
| True Positive (TP): 80 | False Negative (FN): 20 |
| False Positive (FP): 10 | True Negative (TN): 90 |
Total samples = TP + FP + TN + FN = 80 + 10 + 90 + 20 = 200
Precision = TP / (TP + FP) = 80 / (80 + 10) = 0.89
Recall = TP / (TP + FN) = 80 / (80 + 20) = 0.80
F1 Score = 2 * (Precision * Recall) / (Precision + Recall) = 2 * (0.89 * 0.80) / (0.89 + 0.80) ≈ 0.84
Imagine a spam email filter:
- High Precision: Few good emails are wrongly marked as spam. Users don't miss important emails.
- High Recall: Most spam emails are caught, but some good emails might be wrongly marked as spam.
Depending on what matters more, we adjust the model. For spam, high precision is often preferred to avoid losing good emails.
In contrast, for a news topic classifier, high recall might be more important to find all relevant articles.
Good metrics: Precision and recall both above 0.8 means the model labels texts correctly and finds most relevant texts.
Bad metrics: Precision or recall below 0.5 means many wrong labels or many missed texts. For example, precision 0.3 means many false positives.
Accuracy alone can be misleading if classes are unbalanced. For example, 90% accuracy might happen if the model always predicts the majority class.
- Accuracy paradox: High accuracy but poor precision or recall due to unbalanced classes.
- Data leakage: When test data leaks into training, metrics look unrealistically high.
- Overfitting: Very high training metrics but low test metrics means the model memorizes training data, not generalizing well.
- Ignoring class imbalance: Not using metrics like F1 or weighted scores can hide poor performance on smaller classes.
Your text classification model has 98% accuracy but only 12% recall on a rare class. Is it good for production?
Answer: No. The model misses most examples of the rare class (low recall). Even with high accuracy, it fails to find important texts in that class. This is a problem if catching that class matters.
Practice
Solution
Step 1: Understand the role of a pipeline
A pipeline processes raw input data step-by-step to prepare it for a model.Step 2: Identify the pipeline's function in text classification
It converts text into numbers and then classifies the text into categories.Final Answer:
To convert raw text into numbers and classify it -> Option DQuick Check:
Text classification pipeline = convert + classify [OK]
- Confusing classification with text generation
- Thinking pipeline stores data only
- Mixing translation with classification
Solution
Step 1: Recall the Pipeline syntax in scikit-learn
Pipeline expects a list of tuples, each tuple with a name and a transformer or estimator.Step 2: Check each option's syntax
Pipeline([('vect', CountVectorizer()), ('clf', LogisticRegression())]) uses a list of tuples correctly. Options A, B, and C use wrong syntax (missing list, wrong brackets, or invalid keyword arguments).Final Answer:
Pipeline([('vect', CountVectorizer()), ('clf', LogisticRegression())]) -> Option CQuick Check:
Pipeline needs list of (name, step) tuples [OK]
- Using parentheses instead of list brackets
- Passing dictionary instead of list
- Using keyword arguments inside Pipeline
print(pipeline.predict(['I love this movie']))?
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
pipeline = Pipeline([
('vect', CountVectorizer()),
('clf', LogisticRegression())
])
pipeline.fit(['I love this movie', 'I hate this movie'], [1, 0])
print(pipeline.predict(['I love this movie']))Solution
Step 1: Understand the training data and labels
The model is trained with two texts: 'I love this movie' labeled 1 (positive), and 'I hate this movie' labeled 0 (negative).Step 2: Predict the label for 'I love this movie'
Since this exact text was labeled 1 during training, the model should predict 1.Final Answer:
[1] -> Option AQuick Check:
Same text as positive label predicts 1 [OK]
- Assuming prediction returns multiple labels
- Forgetting to fit the model before predict
- Confusing label 0 and 1
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
pipeline = Pipeline([
('tfidf', TfidfVectorizer),
('clf', MultinomialNB())
])
pipeline.fit(['spam message', 'ham message'], [1, 0])Solution
Step 1: Check the pipeline step definitions
The 'tfidf' step uses TfidfVectorizer without parentheses, so it's a class, not an instance.Step 2: Understand the need for instantiation
Pipeline steps require instances of transformers/estimators, so TfidfVectorizer() with parentheses is needed.Final Answer:
TfidfVectorizer is not instantiated with parentheses -> Option BQuick Check:
Instantiate transformers with () [OK]
- Forgetting parentheses when creating transformer
- Changing model type unnecessarily
- Using wrong data types for labels
- Using dict instead of list for pipeline steps
Solution
Step 1: Understand pipeline order and custom steps
Text cleaning must happen before vectorization to affect input text properly.Step 2: Implement custom cleaning as a transformer
Creating a custom transformer class allows integration into the pipeline before vectorizer.Step 3: Evaluate other options
Add text cleaning code inside the LogisticRegression model is wrong because models don't clean text. Clean text after vectorization step in the pipeline is too late to clean text. Use CountVectorizer with lowercase=True and skip custom cleaning only lowercases but does not remove punctuation.Final Answer:
Create a custom transformer class for cleaning, then add it before vectorizer in the pipeline -> Option AQuick Check:
Custom cleaning before vectorizer = Create a custom transformer class for cleaning, then add it before vectorizer in the pipeline [OK]
- Trying to clean text inside the model
- Cleaning text after vectorization
- Relying only on vectorizer lowercase without punctuation removal
Ready to prove it?
Pass the test and this pattern moves unknown
