Can logistic regression handle unbalanced classes?
Logistic regression can handle imbalanced classes, though using the default 0.5 probability threshold often causes low recall on the minority class. Adjusting the decision threshold, applying class weighting (class_weight='balanced'), or resampling training folds restores minority detection, though weighting and resampling shift predicted probabilities away from true base rates.
Study Card: Logistic Regression and Unbalanced Classes
Direct Answer
Logistic regression can handle imbalanced classes, provided you adapt the training objective, classification threshold, and evaluation metrics. Under severe class imbalance, maximum likelihood still estimates consistent slope coefficients if the model is well specified, while the learned intercept reflects the skewed prior base rate—causing a default 0.5 probability cutoff to classify nearly all cases as the majority class. Effective remedies include tuning the decision threshold on validation data, applying cost-sensitive class weights (class_weight='balanced'), or oversampling/undersampling only the training split, while evaluating with Precision, Recall, F1, ROC-AUC, and PR-AUC rather than accuracy. Note that class weighting and resampling distort calibrated probabilities upward for the minority class, whereas threshold tuning preserves true probability calibration.
Key Terms
- Class Imbalance: A dataset distribution where one class (the majority) vastly outnumbers another (the minority), such as 99:1 in fraud detection.
- Precision: The fraction of predicted positives that are actually positive, , crucial when false alarms are costly.
- Recall (Sensitivity): The fraction of actual positive observations correctly identified, , crucial when missed positives are costly.
- F1-Score: The harmonic mean of precision and recall, .
- Threshold Tuning: Moving the classification cutoff away from to match asymmetric misclassification costs without distorting model probability calibration.
Example
Consider credit card fraud detection where 99% of transactions are legitimate () and 1% are fraudulent (). A model that trivially predicts 0 for every transaction achieves 99% accuracy—the accuracy paradox—yet detects zero fraud (0% recall). By applying class_weight='balanced' during training (or lowering the prediction threshold from to e.g. ), misclassifying a fraudulent transaction incurs a much larger loss penalty, dramatically increasing fraud recall while trading off some precision.
Code Implementation
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.utils.class_weight import compute_class_weight
# Create an informative imbalanced dataset (90% negative, 10% positive)
X, y = make_classification(
n_samples=1000,
n_features=6,
n_informative=4,
n_redundant=0,
weights=[0.9, 0.1],
random_state=42,
)
# Always stratify when splitting imbalanced classes
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Baseline Logistic Regression (default threshold 0.5, unweighted)
model_base = LogisticRegression(solver='liblinear', random_state=42)
model_base.fit(X_train, y_train)
y_pred_base = model_base.predict(X_test)
print("Baseline Unweighted Logistic Regression:")
print(classification_report(y_test, y_pred_base, zero_division=0))
# Option 1: Class Weighting
classes = np.unique(y_train)
weights = compute_class_weight(class_weight='balanced', classes=classes, y=y_train)
class_weight_dict = dict(zip(classes, weights))
model_weighted = LogisticRegression(class_weight=class_weight_dict, solver='liblinear', random_state=42)
model_weighted.fit(X_train, y_train)
y_pred_weighted = model_weighted.predict(X_test)
print("Model with Class Weighting:")
print(classification_report(y_test, y_pred_weighted, zero_division=0))
# Option 2: Random Oversampling (apply ONLY to training data, never test data)
X_train_df = pd.DataFrame(X_train)
y_train_s = pd.Series(y_train, index=X_train_df.index)
X_maj, X_min = X_train_df[y_train_s == 0], X_train_df[y_train_s == 1]
y_maj, y_min = y_train_s[y_train_s == 0], y_train_s[y_train_s == 1]
X_min_os = X_min.sample(n=len(X_maj), replace=True, random_state=42)
y_min_os = y_min.loc[X_min_os.index]
X_train_os = pd.concat([X_maj, X_min_os])
y_train_os = pd.concat([y_maj, y_min_os])
model_os = LogisticRegression(solver='liblinear', random_state=42)
model_os.fit(X_train_os, y_train_os)
print("\nModel with Random Oversampling:")
print(classification_report(y_test, model_os.predict(X_test), zero_division=0))
# Option 3: Random Undersampling (training data only)
X_maj_us = X_maj.sample(n=len(X_min), random_state=42)
y_maj_us = y_maj.loc[X_maj_us.index]
X_train_us = pd.concat([X_min, X_maj_us])
y_train_us = pd.concat([y_min, y_maj_us])
model_us = LogisticRegression(solver='liblinear', random_state=42)
model_us.fit(X_train_us, y_train_us)
print("\nModel with Random Undersampling:")
print(classification_report(y_test, model_us.predict(X_test), zero_division=0))
# Compare PR-AUC (Average Precision), which focuses directly on the minority class
y_prob_base = model_base.predict_proba(X_test)[:, 1]
print(f"Baseline PR-AUC: {average_precision_score(y_test, y_prob_base):.4f}")
Related Concepts
- Precision-Recall Tradeoff: Lowering the classification threshold increases recall at the expense of precision; PR curves and PR-AUC highlight minority-class behavior much more faithfully than ROC curves under severe imbalance.
- Probability Calibration: Applying
class_weight='balanced'or resampling shifts predicted probabilities upward; if downstream systems require calibrated risk scores, prefer threshold tuning on unweighted logistic regression or recalibrate afterward (e.g., Platt scaling / prior offset adjustment). - SMOTE and Resampling Hygiene: Synthetic Minority Oversampling Technique (SMOTE) interpolates new minority points in feature space; resampling must always occur inside each cross-validation training fold to avoid data leakage.
- Alternative Models & Losses: Gradient boosted trees with focal loss or scale-pos weighting often handle complex non-linear imbalanced tabular problems effectively.