Sub topic 12
When Classes Are Unevenly Represented
Assume you know the basics of train/test splits, TF-IDF, logistic regression, and classification metrics. This chapter focuses on a common problem: one label appears much more often than another.
Why class imbalance matters
A dataset is class-imbalanced when some labels have many more examples than others. Suppose 95% of support messages are routine and 5% report a security issue. A classifier that always predicts “routine” gets 95% accuracy but never finds a security issue.
Accuracy is therefore weak evidence when the classes have different sizes. Inspect each class separately:
- Precision is the fraction of predicted positives that are correct.
- Recall is the fraction of actual positives that the model finds.
- F1 score is the harmonic mean of precision and recall.
- Balanced accuracy is the average recall across classes.
- A confusion matrix counts correct and incorrect predictions for every class.
| Metric | Main question |
|---|---|
| Precision | When the model predicts this class, how often is it right? |
| Recall | Of the examples in this class, how many did it find? |
| F1 score | How well does it balance precision and recall? |
| Balanced accuracy | How well does it perform across classes equally? |
A baseline and a balanced model
By default, logistic regression gives every training example equal importance. Since the majority class supplies more examples, its patterns can dominate the loss function.
The class_weight="balanced" option changes this. It assigns a larger weight to examples from rare classes and a smaller weight to examples from common classes. For class j, scikit-learn uses a weight proportional to:
\frac{n}{k \times n_j}Here, n is the total number of training examples, k is the number of classes, and n_j is the number of examples in class j.
The following example creates an intentionally uneven text dataset and compares ordinary logistic regression with a class-weighted version.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
balanced_accuracy_score,
classification_report,
confusion_matrix,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
majority = [
"routine account question",
"普通 routine billing question".replace("普通 ", ""),
] * 100
minority = [
"urgent security breach report",
"suspicious login security alert",
"account hacked security incident",
] * 10
texts = majority + minority
labels = ["routine"] * len(majority) + ["security"] * len(minority)
x_train, x_test, y_train, y_test = train_test_split(
texts,
labels,
test_size=0.3,
stratify=labels,
random_state=42,
)
for name, class_weight in [
("unweighted", None),
("balanced", "balanced"),
]:
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(
class_weight=class_weight,
max_iter=1000,
),
)
model.fit(x_train, y_train)
predictions = model.predict(x_test)
print(f"\n{name}")
print(classification_report(y_test, predictions, zero_division=0))
print("Balanced accuracy:", round(
balanced_accuracy_score(y_test, predictions), 3
))
print(confusion_matrix(
y_test,
predictions,
labels=["routine", "security"],
))The example uses stratify=labels so that both splits preserve approximately the same class proportions. Without stratification, a small minority class might be represented poorly in the test set.
What class weights change
Class weighting does not create new text or alter TF-IDF values. It changes how strongly each training error affects the logistic regression objective. The decision boundary may move toward the majority class, making the model more willing to predict the minority class.
That often increases minority recall. It can also reduce minority precision because the model produces more positive predictions. This is a trade-off, not a guaranteed improvement.
Practical decisions
Use these checks before trusting a result:
- Count examples in every label.
- Split with stratification.
- Report per-class precision, recall, and F1.
- Include a confusion matrix.
- Compare ordinary and class-weighted models.
- Use balanced accuracy or macro F1 when each class matters equally.
- Tune the prediction threshold when the application has a specific precision or recall target.
- Consider
class_weight={...}when domain costs are known instead of using"balanced"automatically.
Oversampling the minority class is another option, but duplicated text can encourage overfitting. First try class weights, strong validation, and useful metrics.
Exercise
A classifier has 98% accuracy, but its recall for the minority class is 0%. Is it suitable for finding rare security incidents? What should you inspect next?
Show answer
No. Accuracy hides the missed incidents. Inspect the minority-class recall, precision, F1 score, confusion matrix, and balanced accuracy. Then compare a class-weighted model and threshold choices.