Unit 5, lesson 32

Imbalanced Classes and Cost-Sensitive Learning

Why accuracy misleads when one class is rare, how prevalence, balanced accuracy and macro and micro averages describe performance, and how class weights, SMOTE and cost-sensitive thresholds differ.

  • Video 32
  • Decisions, Metrics and Calibration

A maintenance team can inspect only some machines before the next shift, and in a constructed validation set 2020 of 1,0001{,}000 machines fail during that shift. A rule that never predicts a failure is right 9898 percent of the time and warns about none of them. When one class is rare, the usual summaries can reward ignoring it, and the common remedies change different things, the metric, the training objective or the decision. This lesson keeps those choices apart and shows how to evaluate each one honestly.

Key terms

Class imbalance and prevalence

Definition The prevalence of the positive class in a population is π=P(Y=1)\pi = P(Y = 1), and in a data set with n1n_1 positives among nn examples the sample prevalence is n1/nn_1/n. With more than two classes, the prevalence of each class is defined the same way. A population or data set has class imbalance when the class prevalences differ substantially, for example when one class makes up a few percent of the cases. Prevalence belongs to a stated population, so the training data, the validation data and the cases met after deployment can each have a different prevalence.

In plain words Imbalance is a property of the problem, not a flaw in the data. It causes three practical difficulties. Accuracy is dominated by the common class, the rare class supplies few examples to learn from and to estimate its error rates from, and precision depends on how rare the positives are where the model is used. Evaluation data should keep the prevalence of the population where decisions will be made, because a set balanced by hand changes the accuracy, the precision and the number of alerts the team would receive.

Example In the constructed validation set, 2020 of 1,0001{,}000 machines fail, so the sample prevalence is 0.020.02. The majority rule, which predicts no failure for every machine, is correct for the 980980 machines that do not fail. Its accuracy is 0.980.98 and its sensitivity is 00.

Balanced accuracy

Definition For binary classification with at least one actual positive and one actual negative, the balanced accuracy is

BA=12 sensitivity+12 specificity.\begin{aligned} \text{BA} &= \tfrac12\, \text{sensitivity} \\[0.4em] &\quad + \tfrac12\, \text{specificity}. \end{aligned}

For KK classes, each with nk≥1n_k \ge 1 actual examples, it is the unweighted mean of the per-class recalls TPk/nk\text{TP}_k / n_k, where TPk\text{TP}_k counts the examples of class kk that are predicted as class kk. Ordinary accuracy is the same recalls weighted by the class shares nk/nn_k / n, so the two agree whenever the classes are equally frequent. A rule that always predicts one class has balanced accuracy 1/K1/K.

In plain words Balanced accuracy asks how well the rule does within each class and gives every class the same say. A majority rule cannot hide behind the common class, because its recall of zero on the rare class pulls its balanced accuracy down to one half in the binary case. Balanced accuracy still ignores precision and the costs of errors, and the recall of a rare class rests on few examples, so it can be noisy.

Example Suppose a threshold rule finds 1212 of the 2020 failures and raises 4040 false alarms among the 980980 other machines, so TP=12\text{TP} = 12, FN=8\text{FN} = 8, FP=40\text{FP} = 40 and TN=940\text{TN} = 940. Its sensitivity is 0.60.6 and its specificity is 940/980≈0.9592940/980 \approx 0.9592, so its balanced accuracy is about 0.77960.7796, while its accuracy is 0.9520.952. A lower threshold on the same scores gives TP=16\text{TP} = 16, FN=4\text{FN} = 4, FP=100\text{FP} = 100 and TN=880\text{TN} = 880, with accuracy 0.8960.896 and balanced accuracy about 0.84900.8490. Accuracy ranks the majority rule first, at 0.980.98, and balanced accuracy ranks it last, at 0.50.5.

Macro average and micro average

Definition Suppose a metric such as precision, recall or F1 is computed for each of KK classes by treating that class as positive and all the others as negative, which gives counts TPk\text{TP}_k, FPk\text{FP}_k and FNk\text{FN}_k. The macro average computes the metric for each class and takes the unweighted mean. The micro average adds the counts over the classes first and computes the metric once from the totals. For precision, with preck=TPk/(TPk+FPk)\text{prec}_k = \text{TP}_k / (\text{TP}_k + \text{FP}_k),

macro=1K∑k=1Kpreck,micro=∑kTPk∑k(TPk+FPk).\begin{aligned} \text{macro} &= \frac{1}{K} \sum_{k=1}^{K} \text{prec}_k, \\[0.4em] \text{micro} &= \frac{\sum_k \text{TP}_k}{\sum_k (\text{TP}_k + \text{FP}_k)}. \end{aligned}

In single-label classification, where each example has exactly one actual class and one predicted class, every error is a false positive for the predicted class and a false negative for the actual class. The false positives and the false negatives therefore both add up to the number of errors, and when every class is included, micro precision, micro recall and micro F1 all equal the accuracy. Macro recall equals the balanced accuracy. Macro F1 is the mean of the per-class F1 scores, which in general differs from the F1 score computed from macro precision and macro recall. A class with no predicted examples has undefined precision, and a macro average then needs a stated convention for it.

In plain words Macro averaging gives each class one vote, so a rare class counts as much as a common one. Micro averaging gives each example one vote, so the common classes dominate. Neither is right in general, and a phrase such as average F1 is unfinished until it says which average and which classes it includes. In a binary problem, reporting only the metrics of the positive class is a third choice, different from both.

Example Take the rule above with 1212 true positives, 88 false negatives, 4040 false positives and 940940 true negatives, and score both classes. For failures the precision is 12/52≈0.230812/52 \approx 0.2308, the recall is 0.60.6 and the F1 score is 24/72=1/324/72 = 1/3. For the machines that do not fail the precision is 940/948≈0.9916940/948 \approx 0.9916, the recall is 940/980≈0.9592940/980 \approx 0.9592 and the F1 score is 1880/1928≈0.97511880/1928 \approx 0.9751. The macro precision is about 0.61120.6112, the macro recall is about 0.77960.7796, which is the balanced accuracy, and the macro F1 is about 0.65420.6542, whereas the F1 score of the macro precision and the macro recall is about 0.68520.6852. Micro precision, micro recall and micro F1 all equal 952/1000=0.952952/1000 = 0.952, the accuracy.

Class weight

Definition Training with class weights gives every example of class kk a weight wk>0w_k > 0 in the training objective. For training examples (xi,yi)(\mathbf{x}_i, y_i) with i=1,…,ni = 1, \dots, n, a model f(x;θ)f(\mathbf{x}; \boldsymbol{\theta}) and the loss Li=L(yi,f(xi;θ))L_i = L\bigl(y_i, f(\mathbf{x}_i; \boldsymbol{\theta})\bigr) on example ii, the weighted empirical risk is

R^w(θ)=∑i=1nwyiLi∑i=1nwyi.\hat{R}_w(\boldsymbol{\theta}) = \frac{\sum_{i=1}^{n} w_{y_i} L_i}{\sum_{i=1}^{n} w_{y_i}}.

Dividing by the total weight does not change which θ\boldsymbol{\theta} minimizes it, and equal weights give the ordinary empirical risk. A common choice is wk=n/(Knk)w_k = n/(K n_k), which gives each class the same total weight. The weights change which model is fitted, and they also change what its scores mean. For binary labels and the log loss, the function that minimizes the weighted risk over the population has outputs q(x)q(\mathbf{x}) with

q(x)1−q(x)=w1w0⋅p(x)1−p(x),\frac{q(\mathbf{x})}{1 - q(\mathbf{x})} = \frac{w_1}{w_0} \cdot \frac{p(\mathbf{x})}{1 - p(\mathbf{x})},

where p(x)=P(Y=1∣x)p(\mathbf{x}) = P(Y = 1 \mid \mathbf{x}) lies strictly between 00 and 11. So a model that comes close to this minimizer with w1>w0w_1 > w_0 overstates the probability of the positive class.

In plain words A weight of 1010 on failures makes each failure count like ten copies in the loss, so the fit works harder to give failures high scores. That can help a model that would otherwise neglect the rare class, and it is one way to express that a miss is expensive. The price is that the scores no longer estimate probabilities in the original population, so they need recalibration on representative data before they are read as probabilities or used in an expected-cost rule. A weighted model is one more candidate, to be evaluated on the same untouched validation data as the others.

Example Give each of the 2020 failures weight 1010 and each of the 980980 other machines weight 11, and fit a model with only an intercept under the log loss. The weighted log loss of a constant prediction qq is smallest at the weighted share of failures,

q=20×1020×10+980=2001180≈0.169,\begin{aligned} q &= \frac{20 \times 10}{20 \times 10 + 980} \\[0.4em] &= \frac{200}{1180} \approx 0.169 , \end{aligned}

so every machine receives the score 0.1690.169, while the observed failure rate is 0.020.02. The odds of this score, 10/4910/49, are ten times the odds 1/491/49 of the observed rate, as the formula above says.

SMOTE

Definition Resampling changes which training rows a learner sees. Random oversampling repeats minority examples, random undersampling discards majority examples, and synthetic oversampling adds new minority examples. SMOTE, the synthetic minority oversampling technique, builds each synthetic example from a minority training example xi\mathbf{x}_i and a neighbor xj\mathbf{x}_j chosen at random among its kk nearest minority training examples, commonly with k=5k = 5, as

xnew=xi+λ (xj−xi),\mathbf{x}_{\text{new}} = \mathbf{x}_i + \lambda\,(\mathbf{x}_j - \mathbf{x}_i),

with λ\lambda drawn uniformly from [0,1][0, 1], and gives it the minority label. The new point lies on the segment from xi\mathbf{x}_i to xj\mathbf{x}_j. The method assumes numeric features for which distances and straight-line interpolation make sense, so features are usually scaled first, with the scaling fit on the training data. Like every resampling step, it is applied only to training data, inside each training fold of cross-validation, and never to validation or test data, which keeps it from causing data leakage.

In plain words SMOTE fills in the space between nearby minority examples, so the learner sees a larger minority region than repeated copies would give. The synthetic points are not new observations. All the evidence still comes from the real minority examples, and treating synthetic points as independent cases overstates how much is known. Undersampling, by contrast, discards real majority examples and the information they carry. Interpolating category codes produces values with no meaning, and when the classes overlap, a point between two minority examples can land among majority examples. Resampling also changes the training prevalence, so, like class weights, it moves the scores away from calibrated probabilities for the original population.

Example Suppose (6,3)(6, 3) is one of the nearest minority neighbors of the minority training example (2,1)(2, 1), and the draw gives λ=0.25\lambda = 0.25. The synthetic example is

xnew=(2,1)+0.25 (4,2)=(3,1.5),\begin{aligned} \mathbf{x}_{\text{new}} &= (2, 1) + 0.25\,(4, 2) \\[0.4em] &= (3, 1.5), \end{aligned}

a quarter of the way from the first point to the second. If the first feature were a material code, with 22 for steel and 66 for plastic, the value 33 would name no material at all, and the interpolation would be meaningless.

Cost-sensitive learning

Definition Cost-sensitive learning builds a classifier to minimize expected misclassification cost rather than the error rate. Suppose correct decisions cost nothing, a false positive costs cFP>0c_{\text{FP}} > 0 and a false negative costs cFN>0c_{\text{FN}} > 0. The costs can enter the training, by weighting examples with w1/w0=cFN/cFPw_1 / w_0 = c_{\text{FN}} / c_{\text{FP}} or by resampling in the same proportion. They can instead enter the decision, by applying a threshold to probability estimates p^(x)\hat{p}(\mathbf{x}) and deciding positive when

p^(x)≥cFPcFP+cFN.\hat{p}(\mathbf{x}) \ge \frac{c_{\text{FP}}}{c_{\text{FP}} + c_{\text{FN}}}.

This threshold rule minimizes the expected cost per case when p^(x)=P(Y=1∣x)\hat{p}(\mathbf{x}) = P(Y = 1 \mid \mathbf{x}), the costs are fixed and known, and each case is decided on its own with no limit on how many can be selected. If a model weighted with w1/w0=cFN/cFPw_1 / w_0 = c_{\text{FN}} / c_{\text{FP}} reaches the minimizer of the weighted log loss described under class weights, then thresholding its score at 1/21/2 gives the same decisions as the cost-derived threshold applied to the true probabilities.

In plain words Changing the training objective changes which model is fitted, and changing the threshold changes what is done with its scores afterward. Either can give a cheaper policy, and the two are easy to apply twice by accident, for instance by weighting failures and then also lowering the threshold for the same cost. Compare the candidates by their cost on validation data with the deployment prevalence, not by accuracy, since a cheaper policy can have lower accuracy. A fixed inspection budget changes the decision problem itself, and so do costs that vary from case to case or an intervention that does not always work.

Example Let a missed failure cost 200200 constructed cost units and an unnecessary inspection cost 55. The first threshold rule above, with 88 misses and 4040 false alarms, costs 8×200+40×5=18008 \times 200 + 40 \times 5 = 1800. The lower threshold, with 44 misses and 100100 false alarms, costs 4×200+100×5=13004 \times 200 + 100 \times 5 = 1300, although its accuracy is lower, 0.8960.896 against 0.9520.952. The majority rule misses all 2020 failures and costs 40004000. For calibrated probabilities the cost-derived threshold is 5/205=1/41≈0.02445/205 = 1/41 \approx 0.0244. In the ideal case described above, a weighted fit with w1/w0=200/5=40w_1 / w_0 = 200/5 = 40 and its score thresholded at 1/21/2 makes the same decisions.

Check yourself

  1. A constructed validation set has 500500 machines, 1010 of which fail. A rule catches 77 of the failures and raises 4343 false alarms. Find the accuracy and the balanced accuracy of the rule and of the majority rule that never predicts a failure.
Show the answer

The rule has TP=7\text{TP} = 7, FN=3\text{FN} = 3, FP=43\text{FP} = 43 and TN=490−43=447\text{TN} = 490 - 43 = 447. Its accuracy is (7+447)/500=0.908(7 + 447)/500 = 0.908. Its sensitivity is 0.70.7 and its specificity is 447/490≈0.9122447/490 \approx 0.9122, so its balanced accuracy is about 0.80610.8061. The majority rule has accuracy 490/500=0.98490/500 = 0.98 and balanced accuracy (0+1)/2=0.5(0 + 1)/2 = 0.5.

Accuracy prefers the majority rule and balanced accuracy prefers the rule that finds failures. Neither number includes the precision, which is 7/50=0.147/50 = 0.14 for the rule, or the costs of misses and false alarms.

  1. A detector has sensitivity 0.80.8 and false positive rate 0.10.1 on validation data where the prevalence is 0.20.2. It will be used on machines where the prevalence is 0.010.01. Assuming the two rates stay the same, find the precision in both settings for 10,00010{,}000 cases.
Show the answer

At prevalence 0.20.2 there are 20002000 positives and 80008000 negatives, which give 0.8×2000=16000.8 \times 2000 = 1600 true positives and 0.1×8000=8000.1 \times 8000 = 800 false positives, so the precision is 1600/2400=2/31600/2400 = 2/3. At prevalence 0.010.01 there are 100100 positives and 99009900 negatives, which give 8080 true positives and 990990 false positives, so the precision is

8080+990=8107≈0.0748.\frac{80}{80 + 990} = \frac{8}{107} \approx 0.0748 .

The sensitivity and specificity are the same in both settings, but negatives now outnumber positives 9999 to 11, so false alarms swamp the true ones. The calculation assumes the two rates carry over, and a change in the machines or in their features could change those rates too.

  1. An analyst applies SMOTE to all 1,0001{,}000 machines, adding 480480 synthetic failures, then splits the 1,4801{,}480 rows at random into training and validation sets and reports a validation recall of 0.950.95 for failures. What is wrong, and how should the workflow be repaired?
Show the answer

Resampling before the split lets information cross it. Synthetic failures in the validation set are interpolations of real failures that may sit in the training set, and synthetic training points may have been built from failures that ended up in validation, so validation rewards the model for recognizing near copies of what it has already seen. The validation set also contains synthetic machines that were never observed, and its failure prevalence is about 500/1480≈0.34500/1480 \approx 0.34 instead of 0.020.02, so its precision, accuracy and alert counts do not describe the real stream of machines. The recall of 0.950.95 is therefore no evidence of real performance.

The repair is to split the real machines first, keeping repeated records of one machine on the same side and respecting time order if the records are ordered in time. Then fit the scaling and SMOTE on the training portion only, inside each training fold when cross-validation is used. The validation and test sets keep their original machines and prevalence, the threshold is chosen or the scores recalibrated on validation data, and the test set is used once at the end.

How this lesson connects