Sub topic 12
When Classes Are Unevenly Represented
This chapter assumes you can already build and evaluate a TF-IDF plus logistic regression Pipeline, as in the earlier chapters. You should know precision, recall, F1, and the confusion matrix, and how stratified cross-validation splits data. Here you will see how skewed labels distort that workflow, and how to correct it without leaking test information.
Why imbalance breaks the default workflow
Class imbalance means some labels have far fewer training documents than others. Spam filters, abuse reports, and support tickets that need escalation all look like this. The rare class is usually the one you care about.
Logistic regression minimizes the average log loss over training documents. If 95% of documents belong to one class, a model that favors that class already scores a low average loss. The rare class contributes little to the objective, so the model has little reason to learn its vocabulary well. The result is a classifier with high accuracy, low recall on the rare class, and probabilities that lean toward the majority.
A baseline that ignores the text shows the problem clearly. A classifier that always predicts the majority class gets 95% accuracy on such data. Any model you build must beat that baseline on metrics that look at each class, not only on accuracy.
Building an imbalanced dataset
The 20 Newsgroups categories are roughly balanced. To study imbalance, the code below keeps all documents from two classes and samples only a few from sci.space. It does this for both train and test, so the test set reflects the same skew you would meet in production.
import numpy as np
from sklearn.datasets import fetch_20newsgroups
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
minority = "sci.space"
remove = ("headers", "footers", "quotes")
def load_imbalanced(subset, n_minority, seed=0):
data = fetch_20newsgroups(subset=subset, categories=categories, remove=remove)
y = np.asarray(data.target)
names = list(data.target_names)
minority_id = names.index(minority)
rng = np.random.RandomState(seed)
minority_idx = rng.choice(np.where(y == minority_id)[0], size=n_minority, replace=False)
keep = np.sort(np.concatenate([np.where(y != minority_id)[0], minority_idx]))
texts = [data.data[i] for i in keep]
return texts, y[keep], names, minority_id
X_train, y_train, names, space_id = load_imbalanced("train", n_minority=60)
X_test, y_test, _, _ = load_imbalanced("test", n_minority=30)
print(names)
print("train counts:", np.bincount(y_train))
print("test counts: ", np.bincount(y_test))The minority class is now about 5% of the training set and about 4% of the test set. The remaining code blocks continue in the same Python session and reuse these variables.
Establish a baseline and read the right metrics
First compare three things: a majority-class dummy model, the plain pipeline, and the same pipeline with class weights. The class weights are explained in the next section. Report accuracy next to macro F1 and per-class recall.
from sklearn.dummy import DummyClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, recall_score
from sklearn.pipeline import make_pipeline
def build(class_weight=None, C=1.0):
return make_pipeline(
TfidfVectorizer(sublinear_tf=True, min_df=2, stop_words="english"),
LogisticRegression(C=C, max_iter=1000, class_weight=class_weight),
)
dummy = DummyClassifier(strategy="most_frequent").fit(np.zeros((len(y_train), 1)), y_train)
dummy_pred = dummy.predict(np.zeros((len(y_test), 1)))
models = {"plain": build(), "balanced": build("balanced")}
results = {"dummy": dummy_pred}
for name, clf in models.items():
clf.fit(X_train, y_train)
results[name] = clf.predict(X_test)
for name, pred in results.items():
rec = recall_score(y_test, pred, average=None, zero_division=0)
print(
f"{name:9s} acc={accuracy_score(y_test, pred):.3f} "
f"macroF1={f1_score(y_test, pred, average='macro'):.3f} "
f"recall per class={rec.round(2)}"
)Expect the dummy model to have decent accuracy and a macro F1 near zero for the classes it never predicts. The plain model should look better on accuracy, but its recall for sci.space is typically the weakest number in the row. Exact values depend on your scikit-learn version and the sampled documents.
| Metric | What it does under imbalance | Use it for |
|---|---|---|
| Accuracy | Dominated by the majority class | Only as a sanity check against the dummy baseline |
| Per-class recall | Shows how many rare documents you find | Spotting missed minority cases |
| Per-class precision | Shows how many alerts are correct | Controlling false alarms |
| Macro F1 | Averages per-class F1 with equal weight | Model selection when every class matters |
| Weighted F1 | Averages F1 by class size | Mostly hides the problem, so avoid it for selection |
| Precision-recall curve | Shows the trade-off across thresholds | Binary problems with a rare positive class |
Class weights
The most direct fix for logistic regression is to tell the loss that rare documents count more. With class_weight="balanced", scikit-learn gives each document of class c the weight
wc = n / (K * nc)
where n is the number of training documents, K is the number of classes, and n_c is the number of documents in class c. A class with half the average size gets double weight. The weights sum to n, so the overall loss scale stays comparable and the meaning of C shifts only slightly.
from sklearn.utils.class_weight import compute_class_weight
weights = compute_class_weight("balanced", classes=np.unique(y_train), y=y_train)
for label, w in zip(names, weights):
print(f"{label:20s} weight={w:.2f}")You can also pass a dictionary such as {0: 1.0, 1: 8.0, 2: 1.0} if domain knowledge says a missed minority document costs more than a false alarm. Weights are used inside the loss, so no documents are copied and the vectorizer is unaffected.
Resampling and where it can leak
Resampling changes the training data instead of the loss. Undersampling drops majority documents. Oversampling repeats minority documents. Both approximate the effect of class weights.
For sparse text, oversampling copies identical rows. The model sees the same rare documents many times and can memorize their exact wording. Undersampling discards information that may be useful. For TF-IDF with a linear model, class weights usually give the same benefit with less risk and no extra dependency.
If you do resample, do it inside each training fold only. If you oversample before splitting, copies of the same document land in both the training and validation folds, and cross-validation scores become inflated. The imbalanced-learn library provides a pipeline that applies samplers during fit only, which prevents this.
Move the decision threshold
By default, the model predicts the class whose probability is highest, or 0.5 in the binary case. Nothing says 0.5 is the best operating point for a rare class. Lowering the threshold raises recall and lowers precision. The right threshold depends on the cost of each error.
Choose the threshold on training data without touching the test set. The code below gets out-of-fold probabilities with cross_val_predict, picks the threshold that maximizes F1 there, and applies it once to the test set. It treats sci.space as a binary "rare class versus everything else" problem.
from sklearn.metrics import precision_recall_curve, precision_score, recall_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
y_train_bin = (y_train == space_id).astype(int)
y_test_bin = (y_test == space_id).astype(int)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
binary = build("balanced")
oof = cross_val_predict(binary, X_train, y_train_bin, cv=cv, method="predict_proba")[:, 1]
precision, recall, thresholds = precision_recall_curve(y_train_bin, oof)
f1 = 2 * precision * recall / np.clip(precision + recall, 1e-12, None)
best = thresholds[np.argmax(f1[:-1])]
binary.fit(X_train, y_train_bin)
proba = binary.predict_proba(X_test)[:, 1]
for t in (0.5, best):
pred = (proba >= t).astype(int)
print(
f"threshold={t:.2f} "
f"precision={precision_score(y_test_bin, pred, zero_division=0):.2f} "
f"recall={recall_score(y_test_bin, pred):.2f}"
)precision_recall_curve returns one more precision and recall value than thresholds, which is why the code drops the last F1 entry before taking the maximum. The threshold you choose should reflect the business cost, so treat the F1-optimal value as a starting point rather than a rule.
Tune with imbalance-aware validation
Treat class_weight as a hyperparameter and select with macro F1. A grid search over the whole pipeline keeps the vectorizer and the classifier tuned together. Use stratified folds so every fold contains rare documents. With a classifier and an integer cv, scikit-learn already stratifies, but passing a StratifiedKFold object makes the choice explicit and lets you fix the shuffle seed.
from sklearn.model_selection import GridSearchCV, StratifiedKFold
param_grid = {
"logisticregression__class_weight": [None, "balanced"],
"logisticregression__C": [1.0, 10.0],
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = GridSearchCV(build(), param_grid, cv=cv, scoring="f1_macro", n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_)
print(round(search.best_score_, 3))
print("test macro F1:", round(f1_score(y_test, search.predict(X_test), average="macro"), 3))With only 60 rare training documents, each validation fold holds about 12. Scores will vary a lot between folds, so compare cv_results_["std_test_score"] before trusting small differences.
A decision flow
Common mistakes
- Splitting without stratification, which can leave a validation fold with no rare documents. Recall is then undefined or zero by accident.
- Balancing the test set. The test set should keep the real class distribution, or your precision numbers will not match production.
- Oversampling before cross-validation, which leaks duplicates across folds.
- Picking the threshold on the test set, which turns the test set into a tuning set.
- Reading
predict_probafrom a weighted model as true frequencies. - Judging a rare class from a few documents. With 30 test documents, one extra correct prediction moves recall by about 3 points.
Check your understanding
Exercise
A training set has 900 documents in class A, 90 in class B, and 10 in class C. Compute the "balanced" class weight for each class, and explain why the weights sum to the number of documents.
Show answer
n = 1000 and K = 3, so wc = 1000 / (3 * nc). Class A gets 1000/2700 ≈ 0.37, class B gets 1000/270 ≈ 3.70, and class C gets 1000/30 ≈ 33.33. Weighted counts are 900 0.37 = 333.3, 90 3.70 = 333.3, and 10 * 33.33 = 333.3, so each class contributes equally and the total is 1000. Each class carries n/K weight in total, and K classes times n/K equals n, which keeps the overall loss scale close to the unweighted case.
Exercise
A teammate oversamples the rare class to match the majority class, then runs 5-fold cross-validation and reports a macro F1 of 0.97. On the untouched test set the score is 0.71. Give the most likely cause and the fix.
Show answer
The oversampling happened before the folds were created, so exact copies of the same rare documents appeared in both training and validation folds. The model was scored on documents it had already memorized. The fix is to oversample only inside each training fold, for example with an imbalanced-learn pipeline, or to use class_weight="balanced" instead and keep the original data unchanged.