Sub topic 8
Handling Imbalanced Classes and the Neutral Label
This chapter covers two problems that appear in almost every real sentiment dataset. Some classes have far fewer examples than others, and the "neutral" class is hard to define. It assumes you can train the TF-IDF and logistic regression baseline from the previous chapters and read a classification report with precision, recall, F1 and a confusion matrix.
Why imbalance misleads you
Review data is rarely balanced. Customers who are happy or angry write reviews, and people with a flat opinion mostly don't. A typical product dataset might be 70% positive, 20% negative and 10% neutral. Social posts about a brand can lean the other way, with many neutral news-style posts and few strong opinions.
Accuracy hides the problem. A model that always predicts "positive" on the dataset above scores 70% accuracy and is useless. Look at per-class numbers instead:
| Metric | What it tells you under imbalance |
|---|---|
| Accuracy | Dominated by the majority class. Can look good for a model that ignores minority classes. |
| Per-class recall | The share of real minority examples the model finds. Usually the first number to collapse. |
| Per-class precision | How often a minority prediction is correct. |
| Macro F1 | The unweighted mean of per-class F1. Each class counts equally, so a failing minority class pulls it down. |
| Weighted F1 | Averages F1 weighted by class size. It behaves like accuracy and can hide the same problem. |
Report macro F1 and the per-class rows whenever the classes are uneven. Which class matters most depends on the application. A complaint-routing system cares most about negative recall. A brand-monitoring dashboard may care about all three.
What "neutral" actually means
Neutral is not one thing. Annotators and models use it for at least three different situations:
- No opinion. The text is factual: "The package arrived Tuesday."
- Mixed opinion. The text has positive and negative parts that roughly cancel: "Great screen, terrible battery."
- Unclear opinion. The writer's attitude cannot be recovered without context: "Well, that happened."
If your labels mix these meanings, the neutral class will look like noise to the model, and its F1 will stay low no matter what you do about imbalance. Decide on a definition before labeling, and write it in your annotation guide with examples of each case.
You have several ways to handle the problem:
- Keep three classes when the application needs to separate "no opinion" from opinion. Add a separate "mixed" label if the mixed case matters.
- Collapse to two classes (positive and negative) when you only need polarity and can drop or ignore factual text. Be aware that a binary model forced to classify a neutral post will still output a confident label.
- Use an ordinal scale such as 1 to 5, and treat the middle value as neutral. Errors between adjacent values are then less serious than errors between the extremes.
Star ratings need care. A 3-star review is often mixed or mildly negative rather than truly neutral, and reviewers use stars inconsistently. Treating 3 stars as neutral is a weak-label shortcut. Check a sample by hand before trusting it.
Agreement between annotators is usually lowest on the neutral class. If two annotators disagree on 30% of neutral items, a model cannot be expected to do better than that on them. Measure agreement per class, not only overall.
Diagnosing the imbalance
Start by counting labels, then check that your split preserves the proportions. class_weight="balanced" in scikit-learn uses the formula n_samples / (n_classes * count_of_class), so you can compute the weights yourself to see what they will be.
from collections import Counter
import numpy as np
from sklearn.utils.class_weight import compute_class_weight
labels = ["pos"] * 800 + ["neg"] * 120 + ["neu"] * 80
counts = Counter(labels)
print(counts)
classes = np.array(sorted(counts))
weights = compute_class_weight("balanced", classes=classes, y=np.array(labels))
for cls, weight in zip(classes, weights):
print(cls, round(weight, 2))The rare neutral class gets a weight of about 4.17 and the common positive class about 0.42. During training, an error on a neutral example costs roughly ten times as much as an error on a positive one.
Remedies and their trade-offs
| Technique | How it works | Main risk |
|---|---|---|
| Class weights | Scales the loss for each class by the inverse of its frequency. | Can over-correct, lowering precision on the minority class. |
| Random oversampling | Duplicates minority examples in the training set. | The model memorizes the duplicates and overfits. |
| Undersampling | Drops majority examples. | Throws away useful data, and works badly on small datasets. |
| Threshold or prior adjustment | Changes the decision rule after training, for example by scaling predicted probabilities per class. | Needs a validation set to tune, and the probabilities must be reasonably calibrated. |
| More data for the rare class | Targeted labeling of minority examples. | Costs annotation time, but is often the most effective fix. |
Class weights are the usual first choice because they need no change to the data. Try them before anything more elaborate.
The code below builds a synthetic imbalanced dataset and compares a model without class weights to one with them. The data is generated from word lists, so the exact numbers change if you edit the lists or the seed. Compare the neutral row between the two reports.
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
random.seed(0)
vocab = {
"pos": ["great", "love", "excellent", "fantastic", "happy"],
"neg": ["awful", "terrible", "broken", "disappointed", "refund"],
"neu": ["arrived", "ordered", "package", "delivered", "tuesday"],
}
filler = ["the", "it", "this", "my", "was", "and", "phone", "order", "today"]
def make_text(label):
words = random.choices(vocab[label], k=2) + random.choices(filler, k=4)
if random.random() < 0.3: # noise: a word from a random class
words.append(random.choice(vocab[random.choice(list(vocab))]))
random.shuffle(words)
return " ".join(words)
sizes = {"pos": 800, "neg": 120, "neu": 80}
texts, labels = [], []
for label, n in sizes.items():
for _ in range(n):
texts.append(make_text(label))
labels.append(label)
X_train, X_test, y_train, y_test = train_test_split(
texts, labels, test_size=0.25, stratify=labels, random_state=0
)
for class_weight in (None, "balanced"):
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(max_iter=1000, class_weight=class_weight),
)
model.fit(X_train, y_train)
print("class_weight =", class_weight)
print(classification_report(y_test, model.predict(X_test), zero_division=0))Two details matter here. stratify=labels keeps the 800/120/80 proportions in both halves of the split. Without it, a small test set could contain only a handful of neutral examples, and its metrics would be unreliable. The test set also keeps its natural imbalance, as the earlier warning requires.
Read the report in this order: neutral recall, neutral precision, then macro F1. Weights typically raise neutral recall and lower neutral precision. Whether that trade is good depends on what a missed neutral post costs compared to a false alarm.
A decision path
The label-definition check comes before more modeling. Low neutral scores often come from a vague neutral definition, and no weighting scheme repairs that.
Neutral in lexicon methods
VADER has no neutral class. It returns a compound score between -1 and 1, and you create the neutral label by choosing a band around zero. The common band is plus or minus 0.05, but that is a default and not a rule. Widening the band sends more borderline texts to neutral. Tune it on a labeled validation set instead of copying the default.
def label_from_compound(compound, band=0.05):
if compound >= band:
return "positive"
if compound <= -band:
return "negative"
return "neutral"
for band in (0.05, 0.2, 0.4):
print(band, label_from_compound(0.15, band))A compound score of 0.15 is positive at the default band and neutral at 0.2 or 0.4. For the mixed case, a lexicon sees positive and negative words that cancel, so the compound lands near zero and the text is called neutral. That may or may not match your definition of neutral.
Common mistakes
- Resampling before splitting. Duplicates of the same example then land in both train and test sets, and your scores are inflated. Split first, then resample only the training portion.
- Judging by accuracy. A model that predicts only the majority class can look strong. Always check per-class recall.
- Over-correcting. Heavy oversampling or weights can push the model to predict the minority class too often. Check precision as well as recall.
- Assuming the deployment distribution matches training. If you train on a 70/20/10 review set but deploy on social posts that are 60% neutral, the model's priors are wrong. Evaluate on a labeled sample from the target source.
- Treating neutral as an afterthought. If the neutral class is the weakest, look at its examples before tuning anything.
Exercise
A dataset has 900 positive, 60 negative and 40 neutral reviews. A model predicts "positive" for every test review, and the test set keeps the same proportions. What are its accuracy, its recall on the negative class, and its macro F1 to two decimals? State one remedy you would try first and one thing you would check about the labels.
Show answer
Accuracy is 900/1000 = 0.90. Negative recall is 0, because no negative review is found. For macro F1, the positive class has precision 0.90, recall 1.0, and F1 = 2 × 0.90 × 1.0 / 1.90 ≈ 0.947. The negative and neutral classes have F1 = 0. Macro F1 = (0.947 + 0 + 0) / 3 ≈ 0.32, far below the 0.90 accuracy. A first remedy is to train with class_weight="balanced" on a stratified split and compare per-class recall. For the labels, check that the neutral definition is consistent, for example whether mixed reviews are labeled neutral, by measuring annotator agreement on that class.
Exercise
You resample the minority class by duplicating it, then split the combined data into train and test sets. Your test F1 is very high. Why is this result unreliable, and what is the correct order of steps?
Show answer
Duplicated minority examples can appear in both the training and test sets, so the model is tested on texts it has already seen. The correct order is to split first with stratification, then oversample only the training set, and evaluate on the untouched test set with its natural class distribution.