How to Handle Class Imbalance in Weighted Logistic Regression
One sunny afternoon, I was driving down the road to visit a client when I received a call from my bank. After verifying they were really the bank, they proceeded to ask me if I was in Detroit, Michigan in the previous week. Puzzled, I told them that I had not left town.
Someone had swiped my card several states over. It was the first time it happened to me.
It got me thinking, in all these years, thousands of transactions, and only one of them was a fraud. In fact, less than 4% of the global transactions are fraudulent
Likewise, only a small sliver of alerts handled by the security operation center (SOC) team are false positives. Most logins are valid. Rarely, an anomaly with multiple failed attempts emerges. One could go their entire life without being hacked.
These rare events have something in common. They are the ones we want to predict and avoid.
This lopsided split is called class imbalance, and it has a reputation. There are different methods to deal with it. The usual advice is that logistic regression can’t handle it, and the data should be rebalanced first. That is true; but not necessary the only way.
When using logic regression in scikit-learn, that is one argument: class_weight="balanced".
Recently, I began exploring what that argument actually does.
The short version: weighting rarely makes the model better at telling cases apart, and it quietly breaks probabilities. Most of what people want from it can be done more honestly by choosing a better decision threshold.
If log-odds ratios is something new for you, I wrote an article about regression analysis where I explain the concept a little better.
The analysis below comes from a simulated dataset: 40,000 cases, three predictors, and an event rate of about 5.5%.
What Imbalance Does to Logistic Regression
Before we dive in, let me get one thing off my chest: a rare outcome does not prevent logistic regression from learning. In the simulation, the unweighted model recovers slopes of 1.15, 0.70, and -0.56, which are remarkably close to the true values of 1.1, 0.7, and -0.5.
What the rarity actually changes is where the predictions land. These numbers suggest that, despite the outcome being uncommon, the model successfully identified how each variable influenced its likelihood.
The intercept for the unweighted model is -3.70 on the log-odds scale, which translates to about a 2.4% chance for an “average” case. Most predicted probabilities sit in the single digits. That is not a flaw. If only 1 in 18 cases is an event, small probabilities are the honest answer.
The 0.5 cutoff almost never fires. With the default rule of “flag it if p ≥ 0.5,” the model flags just 94 of the 20,000 test cases and catches 53 of the 1,187 real events. That is a recall of just 4.5%.
The sample model scores 94.1% accuracy, which is very high. But it is also exactly what you would get by predicting no event for everyone. Accuracy rewards the model for its agreement with the majority class, which means nothing when one class makes up 94% of the data.
I’m going to venture out and say something that might be controversial: the model is fine; the decision rule and the metric are the problem.
How Weighted Logistic Regression Works
Ordinary logistic regression picks the coefficient that makes the observed outcomes most likely. It does so by maximizing the log-likelihood, a sum with one term per case. Weighted logistic regression multiplies each case’s term by a weight that depends on the class:
\(\ell(\beta) = \sum_{i=1}^{n} w_{y_i} \left[ y_i \log p_i + (1 - y_i) \log(1 - p_i) \right]\)
Increasing the weight assigned to positive events (w₁) makes misclassifying those events more costly, encouraging the model to place greater emphasis on identifying the rare classes.
Conversely, scikit-learn class_weight picks the weight automatically:
\(w_k = \frac{n}{2 \, n_k}\)
Here n is the number of training cases and \(n_k\) is the number in class k. In the simulation, the 1,085 events each get a weight of about 9.2 and the 18,915 non-events each get about 0.53. After weighting, both classes contribute the same total to the fit, as if the data were split 50/50.
The slope barely moves. Almost everything changes at the intercept, which jumped by 2.84.
The Research
As part of my investigative side, I wanted to delve into the problem and find what other experts are saying about this issue.
Two papers came to my attention and I found especially useful in this situation. They lead with different headlines, but when you read closer, they agree on more than is apparent.
Resampling and Weighting Break Calibration
Goorbergh et al. (2022) tested random undersampling, oversampling, and SMOTE on standard and ridge logistic regression. Using Monte Carlo Simulations as well as a real model for diagnosing ovarian cancer, their findings line up with the simulation in this post.
None of the corrections improved discrimination, as measured by AUC, yet every one of them led the model to strongly overestimate the probability of the event. The model ended up with badly calibrated risks.
The correction did raise sensitivity, but the authors found that simply moving the cutoff on the undercorrected model delivered similar results without the calibration problem.
The conclusion was very similar to mine. The imbalance is not a problem in itself.
One distinct difference is that they tested resampling rather than class weights. Random oversampling and class weighting behaved the same way in expectation, which closely mirrors what we learned.
Learned from Weights
The second paper, Zhang et al. (2021) approaches the problem from a different angle. Instead of giving the whole minority class one fixed weight, the authors give each event its own weight and learn from those weights.
I think the idea of doing it that way is clever, but I have mixed feelings about it. Stay with me while I break this down.
Their own results, summarized in the chart above, make two points worth noting.
First, fixed balanced weights turn out to be something of a coin flip when it comes to ranking. Compared to an unweighted model (class_weight="balanced") lowered the mean AUC on 6 to 10 real datasets. It makes sense once you remember that real models are rarely perfectly specified. When they are weighted, it shifts which cases the line fits best, and the ranking can move in either direction.
Second, the learned weights did better on every dataset. The AUC gains ranged from +0.007 to +0.063. In the simulations, the gains were smaller and showed up mainly when the event rate was 1% or the relationship was nonlinear.
My feelings are mixed about this method. The idea is clever and improves ranking in real data. The one thing that makes me a little hesitant is that the event weights aren’t really learned in any principled sense. The authors run gradient ascent on the weights while running gradient descent on the coefficients. As a result, the weights keep growing until early stopping halts them. That makes the method less likelihood-based than a boosting-style reweighting of the hardest positive cases.
It is a reasonable ranking tool to benchmark, but not the principled fix for class imbalance as it is presented.
Where the Papers Agree
Taken together, the two papers point in the same direction. A plain weighted scheme mostly shifts scores up and down rather than making the model better.
If we were to change the training weights, we should treat the outputs as scores rather than probabilities and set the threshold on held-out data, which brings us to the most practical part of the discussion.
Pick the Threshold, not the Weights
The clearest evidence comes from comparing the decisions the two models make. At the default 0.5 cutoff, the balanced model flags 5,593 test cases and catches 874 events.
If we were to unweight the model and lower its cutoff to the training event rate of 5.4%, it flags 5,614 cases and catches 873 events. A significant change for very little reward.
For all practical purposes, those are the same decisions; with balanced weights, applying p≥5 to the weighted model is roughly equivalent to applying p≥ base rate to the unweighted one. In other words, the weights did not teach the model anything; they simply moved the cutoff, and they distorted the probabilities along the way.
It makes more sense to set the threshold directly and to base it on what kind of mistake costs. If missing an event costs c_FN and raising false alarms costs c_FP, the expected cost is lowest when we flag every case that exceeds this value:
\(t^* = \frac{c_{FP}}{c_{FP} + c_{FN}}\)
For instance, if a missed readmission costs 20 times as much as an unnecessary follow-up call, then t* = 1/21, or about 4.8%. This rule only works when the probabilities are calibrated.
In the simulation, the cost curve bottoms out between 4% and 5%. At that cutoff, the model catches between 76% and 81% of events while flagging about a third of all cases. The 0.5 default only catches 4.5% of events, and the total cost is more than twice as high.
This framing fits security work especially well. The cost of a false alarm is very real, measured in analyst time and in the alert fatigue that builds up over weeks of noise. When a SOC team can review 500 alerts a day, that capacity becomes the true constraint. The natural approach is to rank these cases by predicted risk. Take the top 500 and calibrate probabilities to tell the team how many real incidents to expect in that batch.
Conclusion
At the end of the day, class imbalance is a fact about the data rather than a defect in logistic regression. The unweighted model already ranks cases as well as it can and already produces honest probabilities.
Using the class_weight="balanced" patches the problem. Sort of. It pushes the prediction towards 50%. It works as a threshold shift, but it costs calibration.
More sophisticated weight schemes, such as learning a separate weight for each event, can improve the ranking, but even the outputs are a score that needs a validated threshold.
This is a work in progress.
References:
van den Goorbergh, R., van Smeden, M., Timmerman, D. & Van Calster, B. (2022). The harm of class imbalance corrections for risk prediction models: illustration and simulation using logistic regression. Journal of the American Medical Informatics Association, 29(9), 1525–1534. Preprint: arXiv:2202.09101.
Zhang, L., Geisler, T., Ray, H. & Xie, Y. (2021). Improving logistic regression on the imbalanced data by a novel penalized log-likelihood function. Journal of Applied Statistics, 49(13), 3257–3277. doi:10.1080/02664763.2021.1939662.
King, G. & Zeng, L. (2001). Logistic regression in rare events data. Political Analysis, 9(2), 137–163. Simulation for this post: 40,000 cases from a known logistic model (event rate about 5.5%) with a 50/50 train/test split, fit with scikit-learn.
No comments yet. Be the first.