Sub topic 8
Handling Imbalanced Classes and the Neutral Label
Assume you know basic Python, can install packages with pip, and understand training data, test data, and predictions. This chapter focuses on a common evaluation problem: one sentiment class may have many more examples than another, and the neutral class may not have a clear boundary.
Why class imbalance matters
A dataset is imbalanced when its classes have different numbers of examples. For example, a support team may collect mostly neutral messages:
| Label | Number of examples |
|---|---|
| positive | 700 |
| neutral | 2,400 |
| negative | 300 |
A classifier that predicts neutral for every message gets 70% accuracy in this example. However, it completely misses positive and negative messages. Accuracy hides this failure.
Class imbalance can also affect training. The model sees many more neutral examples, so it may learn to prefer that label even when the text contains a clear opinion.
The neutral label needs a clear rule
Neutral can mean different things:
- The writer states information without expressing an opinion: “The package arrived on Tuesday.”
- The text contains mixed opinions: “The camera is excellent, but the battery is poor.”
- The sentiment is too weak or unclear to classify.
- The annotator could not agree on a positive or negative label.
These meanings produce different models. Write an annotation rule before labeling data. For example, you might define neutral as text with no overall positive or negative judgment. Then decide how to label mixed statements. You could use the overall sentiment, add a mixed label, or move to aspect-based sentiment.
Evaluate every class
Use precision, recall, and F1 score for each label:
- Precision asks: when the model predicts a class, how often is it correct?
- Recall asks: of all examples belonging to a class, how many did the model find?
- F1 combines precision and recall.
- A confusion matrix counts the actual label against the predicted label.
For imbalanced data, inspect macro F1 and weighted F1 separately. Macro F1 gives every class equal importance. Weighted F1 gives larger classes more influence.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
texts = [
"I love this product", "Excellent quality", "Fast and helpful service",
"The product is okay", "The order arrived Tuesday", "It has three colors",
"I hate this product", "Terrible quality", "The service was awful",
"Wonderful experience", "Nothing special", "It broke immediately",
]
labels = [
"pos", "pos", "pos", "neu", "neu", "neu",
"neg", "neg", "neg", "pos", "neu", "neg",
]
x_train, x_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.25, stratify=labels, random_state=42
)
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(class_weight="balanced", max_iter=1000),
)
model.fit(x_train, y_train)
predictions = model.predict(x_test)
print(classification_report(y_test, predictions, zero_division=0))
print(confusion_matrix(y_test, predictions, labels=["neg", "neu", "pos"]))stratify=labels keeps similar class proportions in the training and test sets. class_weight="balanced" gives more weight to examples from smaller classes. This is a useful baseline, not a guarantee of better performance. Compare it with a model that does not use class weights.
Other ways to handle imbalance
- Collect more examples for rare classes.
- Use stratified cross-validation.
- Set class weights from business costs, not only from class counts.
- Use targeted sampling carefully. Duplicating rare examples can cause overfitting.
- Report per-class results instead of only accuracy.
- Check performance separately for different sources, products, or time periods.
Exercise
Why can a classifier with high accuracy still be unsuitable for an imbalanced sentiment dataset?
Show answer
It may predict the majority class for most or all inputs, producing high accuracy while missing the minority classes. Per-class recall and macro F1 expose this problem.