Intermediate level · Module 4: Naive Bayes and Text Classification · Lesson 3 of 3
Imbalanced Classes and Per-Class Evaluation
Learners handle categories with few examples using class weights and resampling, and report precision, recall and F1 per class with macro averages.
In this lesson you will
- Handle class imbalance in text classification
- Report per-class and macro-averaged metrics
Key concepts
class imbalanceclass_weight='balanced'macro vs weighted averageprecision-recall trade-offdecision threshold
The lesson
In real enquiries, complaints may be only 10% of messages. A model can reach high accuracy by rarely predicting 'complaint', which is exactly the category that matters most. Per-class recall reveals this.
Options include class_weight='balanced' in logistic regression, collecting more examples of rare categories, and lowering the decision threshold for the important class (using predicted probabilities). Each option trades precision against recall.
Report per-class precision, recall and F1, and the macro average (each class counts equally). The weighted average and accuracy are dominated by the large classes.
Step by step
- Create an imbalanced version of the project data.
- Compare a standard and a class-weighted model with classification_report.
- Adjust the threshold for the most important class and plot precision and recall.
- Choose a setting and justify it in terms of the people affected.
Practice activity
Write a per-class evaluation and threshold choice for the project classifier.
Expected result: A clear per-class report and a threshold choice justified by its consequences.
Check your understanding
-
Why can accuracy be misleading with imbalanced classes?
Show answer
A model can score well by mostly predicting the large classes.
-
What does the macro average do?
Show answer
It averages the metric across classes, giving each class equal weight.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.