A maintenance team can inspect only some machines before the next shift, and in a constructed validation set of machines fail during that shift. A rule that never predicts a failure is right 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 , and in a data set with positives among examples the sample prevalence is . 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, of machines fail, so the sample prevalence is . The majority rule, which predicts no failure for every machine, is correct for the machines that do not fail. Its accuracy is and its sensitivity is .
Balanced accuracy
Definition For binary classification with at least one actual positive and one actual negative, the balanced accuracy is
For classes, each with actual examples, it is the unweighted mean of the per-class recalls , where counts the examples of class that are predicted as class . Ordinary accuracy is the same recalls weighted by the class shares , so the two agree whenever the classes are equally frequent. A rule that always predicts one class has balanced accuracy .
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 of the failures and raises false alarms among the other machines, so , , and . Its sensitivity is and its specificity is , so its balanced accuracy is about , while its accuracy is . A lower threshold on the same scores gives , , and , with accuracy and balanced accuracy about . Accuracy ranks the majority rule first, at , and balanced accuracy ranks it last, at .
Macro average and micro average
Definition Suppose a metric such as precision, recall or F1 is computed for each of classes by treating that class as positive and all the others as negative, which gives counts , and . 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 ,
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 true positives, false negatives, false positives and true negatives, and score both classes. For failures the precision is , the recall is and the F1 score is . For the machines that do not fail the precision is , the recall is and the F1 score is . The macro precision is about , the macro recall is about , which is the balanced accuracy, and the macro F1 is about , whereas the F1 score of the macro precision and the macro recall is about . Micro precision, micro recall and micro F1 all equal , the accuracy.
Class weight
Definition Training with class weights gives every example of class a weight in the training objective. For training examples with , a model and the loss on example , the weighted empirical risk is
Dividing by the total weight does not change which minimizes it, and equal weights give the ordinary empirical risk. A common choice is , 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 with
where lies strictly between and . So a model that comes close to this minimizer with overstates the probability of the positive class.
In plain words A weight of 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 failures weight and each of the other machines weight , and fit a model with only an intercept under the log loss. The weighted log loss of a constant prediction is smallest at the weighted share of failures,
so every machine receives the score , while the observed failure rate is . The odds of this score, , are ten times the odds 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 and a neighbor chosen at random among its nearest minority training examples, commonly with , as
with drawn uniformly from , and gives it the minority label. The new point lies on the segment from to . 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 is one of the nearest minority neighbors of the minority training example , and the draw gives . The synthetic example is
a quarter of the way from the first point to the second. If the first feature were a material code, with for steel and for plastic, the value 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 and a false negative costs . The costs can enter the training, by weighting examples with or by resampling in the same proportion. They can instead enter the decision, by applying a threshold to probability estimates and deciding positive when
This threshold rule minimizes the expected cost per case when , 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 reaches the minimizer of the weighted log loss described under class weights, then thresholding its score at 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 constructed cost units and an unnecessary inspection cost . The first threshold rule above, with misses and false alarms, costs . The lower threshold, with misses and false alarms, costs , although its accuracy is lower, against . The majority rule misses all failures and costs . For calibrated probabilities the cost-derived threshold is . In the ideal case described above, a weighted fit with and its score thresholded at makes the same decisions.
Check yourself
- A constructed validation set has machines, of which fail. A rule catches of the failures and raises 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 , , and . Its accuracy is . Its sensitivity is and its specificity is , so its balanced accuracy is about . The majority rule has accuracy and balanced accuracy .
Accuracy prefers the majority rule and balanced accuracy prefers the rule that finds failures. Neither number includes the precision, which is for the rule, or the costs of misses and false alarms.
- A detector has sensitivity and false positive rate on validation data where the prevalence is . It will be used on machines where the prevalence is . Assuming the two rates stay the same, find the precision in both settings for cases.
Show the answer
At prevalence there are positives and negatives, which give true positives and false positives, so the precision is . At prevalence there are positives and negatives, which give true positives and false positives, so the precision is
The sensitivity and specificity are the same in both settings, but negatives now outnumber positives to , 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.
- An analyst applies SMOTE to all machines, adding synthetic failures, then splits the rows at random into training and validation sets and reports a validation recall of 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 instead of , so its precision, accuracy and alert counts do not describe the real stream of machines. The recall of 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.