AI Wiki中文/EN

Imbalanced learning: a rare class needs more than a high accuracy

类别不平衡学习

Audit a rare-class score table, compare PR with ROC, calculate prevalence-dependent precision and keep training resampling inside validation boundaries.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Ninety-five percent correct, and every rare item missed

A fictional image catalogue contains 100 connector photographs: five show a rare connector and 95 show a common one. Calling every image “common” gives 95% accuracy. It also misses all five rare connectors. Both statements are true; the percentage simply hides which class was served.

Imbalanced learning concerns unequal class representation and what that does to learning and evaluation. “Minority” describes frequency, not importance or mistake cost. A rare class with thousands of varied examples can be easier to learn than a balanced class represented by a handful of ambiguous examples. Absolute counts, coverage, label quality and class overlap matter alongside the ratio.

This chapter keeps one score table fixed. It asks what a threshold finds, how results change when the class mix changes, and what training resampling can legitimately change. It does not assume that rare connectors deserve any particular error cost; that decision belongs in the cost-sensitive learning topic.

Follow the denominators

Treat the rare connector as the positive class. A false positive is a common connector called rare; a false negative is a rare connector called common. Higher scores favor the positive class, but the scores need not be probabilities. Our invented table is:

ScorePositive imagesNegative images
9031
7014
40115
10075

At threshold 70, predict positive for scores at least 70. This finds four positives and includes five negatives: TP=4, FP=5, FN=1, TN=90. The relevant denominators answer different questions:

Precision+=TPTP+FP,Recall+=TPTP+FN,Precision−=TNTN+FN,Recall−=TNTN+FP,FPR=FPFP+TN,Accuracy=TP+TNTP+FP+FN+TN.\mathrm{Precision}_+=\frac{TP}{TP+FP},\quad\mathrm{Recall}_+=\frac{TP}{TP+FN},\quad\mathrm{Precision}_-=\frac{TN}{TN+FN},\quad\mathrm{Recall}_-=\frac{TN}{TN+FP},\quad\mathrm{FPR}=\frac{FP}{FP+TN},\quad\mathrm{Accuracy}=\frac{TP+TN}{TP+FP+FN+TN}.

Positive recall is 4/5: four of the five rare items were found. Positive precision is 4/9: fewer than half of the nine positive predictions are correct. Negative precision is 90/91, and negative recall is 90/95=18/19. The false-positive rate is only 1/19, yet false positives outnumber true positives. There are many more negatives available to generate them.

The threshold’s accuracy is 94%, one point below the all-negative baseline. That does not make accuracy incorrectly calculated. It means ordinary accuracy gives every observation one vote, so the many common items dominate its aggregate. Balanced accuracy, the mean of the two class recalls when both are defined, is 83/95 here and 1/2 for the all-negative rule. It answers an equal-class question rather than the observed-mixture question. Neither number determines the consequences of an error.

Why changing class prevalence changes precision

Keep the classifier and its class-conditional behavior fixed. Let t be its true-positive rate, f its false-positive rate and π the positive prevalence in a target population. The mass of true-positive predictions is πt; the mass of false-positive predictions is (1−π)f. Therefore

Precision(π)=πtπt+(1−π)f,P(Y^=1)=πt+(1−π)f.\mathrm{Precision}(\pi)=\frac{\pi t}{\pi t+(1-\pi)f},\qquad P(\widehat Y=1)=\pi t+(1-\pi)f.

The first expression is defined only when some positive predictions occur. With t=4/5 and f=1/19, prevalence 1/20 gives precision 4/9. A balanced population gives 76/81, about 93.8%; prevalence 1/100 gives 76/571, about 13.3%. The same conditional error rates can yield very different reliability among positive predictions.

This is a calculation under a stated prior-change model. It is not permission to assume that rates measured on five positives are known population constants. In practice they are estimates, and class-conditional images may change too. Changing a classifier through resampling or weighting can also change t and f; the calculation does not hold them fixed by magic.

PR and ROC describe the same thresholds from different angles

A ROC point is (FPR, positive recall); a precision–recall point is (positive recall, positive precision). At threshold 70, the former is (1/19,4/5), the latter (4/5,4/9). ROC remains useful: it compares conditional ranking behavior. PR directly displays the proportion of positive predictions that are correct at the evaluated class mix. Under pure prevalence change with unchanged score distributions within each class, the ROC curve is unchanged while precision values generally change.

Davis and Goadrich connect the two spaces for fixed positive and negative totals and explain why their geometric presentation and interpolation differ. Their correspondence requires care at zero recall, where PR points can lose false-positive information. A good-looking ROC curve does not make the precision denominator disappear. Original ICML 2006 paper, §§2–4.

For summary scores, this program uses ROC AUC with half credit for tied positive–negative pairs and average precision (AP) with recall-increment weights:

AUCROC=P(S+>S−)+12P(S+=S−),AP=∑j(Rj−Rj−1)Pj.\mathrm{AUC}_{ROC}=P(S_+>S_-)+\frac12P(S_+=S_-),\qquad\mathrm{AP}=\sum_j(R_j-R_{j-1})P_j.

The pair probabilities are empirical, choosing one positive and one negative independently and uniformly from this table. For AP, thresholds run from accepting nothing to accepting successive whole score groups; Pⱼ and Rⱼ denote precision and recall after a group is accepted. This is noninterpolated AP, not trapezoidal area under a straight-line PR drawing. Official AP convention, scikit-learn 1.7.2.

Here ROC AUC is 458/475, about 0.9642, while AP is 521/900, about 0.5789. These summarize different aspects of ranking; neither is the accuracy of a deployed threshold. Giving every image the same score would yield ROC AUC 1/2 and AP equal to prevalence, 1/20. That exact constant-score baseline is not a claim about the finite-sample expected AP of every random ranking.

Keep ties together and missing denominators visible

The complete Python program operates on (score, positive count, negative count) bins. It merges duplicate scores before sweeping, so the order of observations within a tie cannot manufacture a better curve. audit accepts an inclusive score threshold; None explicitly means predict every item negative. sweep returns that initial rule and one rule per distinct score, plus ROC AUC, AP and prevalence.

Scores and rates are integers or Fraction values; counts are nonnegative integers, and Booleans are rejected. Every input row must contain at least one observation. Lists and tuples are accepted; an empty table is not. A table may contain only one class so that the program can expose what is undefined: absent-class recall and ROC AUC become None, as does AP when there are no positives. Precision is None when the corresponding class is never predicted. Those conventions are explicit; plotting libraries may use a synthetic PR endpoint instead.

prevalence_precision accepts rational rates in [0,1]. It returns None precision when the resulting positive-prediction mass is zero, including boundary cases. It computes a hypothetical population relationship; it neither trains a model nor estimates changing prevalence. All ratios in the program are exact for the supplied counts.

from fractions import Fraction as F


def rational(value):
    if type(value) not in (int, F):
        raise ValueError('scores and rates must be integers or Fractions')
    return F(value)


def sequence(value):
    if type(value) not in (list, tuple):
        raise ValueError('use a list or tuple')
    return value


def bins(table):
    merged = {}
    for row in sequence(table):
        row = sequence(row)
        if len(row) != 3:
            raise ValueError('row: (score, positive count, negative count)')
        score, positive, negative = rational(row[0]), row[1], row[2]
        if any(type(v) is not int or v < 0 for v in (positive, negative)):
            raise ValueError('counts must be nonnegative integers, not Booleans')
        if positive + negative == 0:
            raise ValueError('each row must contain at least one observation')
        p, n = merged.get(score, (0, 0))
        merged[score] = (p + positive, n + negative)
    if not merged:
        raise ValueError('nonempty table required')
    return tuple((s, *merged[s]) for s in sorted(merged, reverse=True))


def ratio(a, b):
    return F(a, b) if b else None


def report(tp, fp, positives, negatives):
    fn, tn = positives-tp, negatives-fp
    recall, specificity = ratio(tp, positives), ratio(tn, negatives)
    return {'confusion': (tp, fp, fn, tn),
            'accuracy': F(tp+tn, positives+negatives),
            'positive': {'precision': ratio(tp, tp+fp), 'recall': recall, 'support': positives},
            'negative': {'precision': ratio(tn, tn+fn), 'recall': specificity, 'support': negatives},
            'fpr': ratio(fp, negatives),
            'balanced_accuracy': (recall+specificity)/2 if positives and negatives else None}


def audit(table, threshold):
    data = bins(table)
    threshold = None if threshold is None else rational(threshold)
    P, N = sum(p for s, p, n in data), sum(n for s, p, n in data)
    accepted = tuple((p, n) for s, p, n in data if threshold is not None and s >= threshold)
    return report(sum(p for p, n in accepted), sum(n for p, n in accepted), P, N)


def sweep(table):
    data = bins(table)
    P, N = sum(p for s, p, n in data), sum(n for s, p, n in data)
    curve = [(None, report(0, 0, P, N))]
    tp = fp = 0
    ap = F(0) if P else None
    for score, positive, negative in data:
        tp, fp = tp+positive, fp+negative
        current = report(tp, fp, P, N)
        curve.append((score, current))
        if P:
            ap += F(positive, P)*current['positive']['precision']
    below = twice_wins = 0
    for score, positive, negative in reversed(data):
        twice_wins += positive*(2*below+negative)
        below += negative
    auc = F(twice_wins, 2*P*N) if P and N else None
    return {'curve': tuple(curve), 'roc_auc': auc, 'average_precision': ap,
            'prevalence': F(P, P+N)}


def prevalence_precision(tpr, fpr, prevalence):
    tpr, fpr, prevalence = map(rational, (tpr, fpr, prevalence))
    if any(v < 0 or v > 1 for v in (tpr, fpr, prevalence)):
        raise ValueError('rates must lie in [0, 1]')
    true_mass = prevalence*tpr
    predicted_mass = true_mass+(1-prevalence)*fpr
    return {'precision': true_mass/predicted_mass if predicted_mass else None,
            'predicted_positive_mass': predicted_mass}


if __name__ == '__main__':
    table = ((90, 3, 1), (70, 1, 4), (40, 1, 15), (10, 0, 75))
    none = audit(table, None)
    selected = audit(table, 70)
    print('all negative: accuracy / positive recall:', none['accuracy'], none['positive']['recall'])
    print('threshold 70: TP FP FN TN:', selected['confusion'])
    print('positive precision / recall:', selected['positive']['precision'], selected['positive']['recall'])
    print('negative precision / recall:', selected['negative']['precision'], selected['negative']['recall'])
    result = sweep(table)
    print('ROC AUC / AP:', result['roc_auc'], result['average_precision'])
    for prior in (F(1,20), F(1,2), F(1,100)):
        changed = prevalence_precision(selected['positive']['recall'], selected['fpr'], prior)
        print('prevalence / precision:', prior, changed['precision'])

Actual output:

all negative: accuracy / positive recall: 19/20 0
threshold 70: TP FP FN TN: (4, 5, 1, 90)
positive precision / recall: 4/9 4/5
negative precision / recall: 90/91 18/19
ROC AUC / AP: 458/475 521/900
prevalence / precision: 1/20 4/9
prevalence / precision: 1/2 76/81
prevalence / precision: 1/100 76/571

For B input bins and M distinct scores, validation and merging take O(B) expected dictionary operations, sorting takes O(M log(M+1)) comparisons, and the sweep and pair-count accumulation take O(M) arithmetic operations. Stored and returned records take O(M) space. audit also sorts through the shared validator. These are operation counts: rational score sizes, integer counts and their bit costs are separate. The compressed program does not materialize all 100 images or every positive–negative pair.

What balancing changes during training

Duplicating a training observation dᵢ times gives it dᵢ contributions to an unpenalized empirical loss sum. With consistent normalization, it is equivalent to integer sample weighting for that objective. It does not create independent evidence. For binary zero-one loss, class-balancing weights lead to

w+=n2n+,w−=n2n−,1n∑iwyi1[y^i≠yi]=12(FNn++FPn−),n+>0, n−>0.w_+=\frac{n}{2n_+},\qquad w_-=\frac{n}{2n_-},\qquad\frac1n\sum_i w_{y_i}\mathbf1[\widehat y_i\ne y_i]=\frac12\left(\frac{FN}{n_+}+\frac{FP}{n_-}\right),\qquad n_+>0,\ n_->0.

On the given counts, the all-negative rule has equal-class error 1/2; threshold 70 has error 12/95. Ordinary error orders the two rules the other way. This arithmetic explains how changing a training objective can favor minority recall. It does not select a threshold for deployment from a final test table. Integer duplication and weighted training also need not follow identical optimization trajectories or penalty normalization in a library.

Random undersampling can discard useful majority-class variation. Random oversampling repeats minority information and may increase overfitting; SMOTE-style interpolation of numerical features adds a geometric assumption rather than fresh independent labels. Class weights change the loss emphasis without changing the original row count. None guarantees better minority precision and recall, and changes to the effective training mix can affect probability calibration. Official oversampling guide.

Split by the true independent unit before fitting any sampler, learned transform or model. In cross-validation, each sampler belongs inside the corresponding training fold. Keep validation and final evaluation data representative of the intended evaluation population, or explicitly report the sampling design and target weighting. A balanced diagnostic set can help estimate class-conditional rates, but its raw precision is not automatically deployment precision. The official imbalanced-learn guide explains both leakage from resampling before splitting and the evaluation-population mismatch. Common pitfalls, §9.1.

A rare class can still be poorly represented after balancing

Five positives become 95 rows if each is copied nineteen times, but they remain five original observations. Subtypes, acquisition conditions and labeling mistakes do not disappear through duplication. Report counts of independent examples as well as any resampled counts; uncertainty based on duplicated rows as if they were independent would be misleading.

Precision depends on which class is called positive. For multiple classes, inspect per-class support and errors before using a macro or frequency-weighted summary. This program intentionally stays binary. It does not implement multilabel prevalence, resampling, training, confidence intervals or calibration correction.

A threshold should be chosen for an explicit use case and validated within the selection process. Increasing recall can require more positive predictions, but precision need not decrease monotonically at every empirical threshold: another score group may contain mostly positives. No metric or fixed class ratio determines an optimal operating point on its own.

Finally, training imbalance, deployment prevalence and asymmetric error costs are different inputs. A common class can be expensive to misclassify; a rare class can have the same mistake cost as every other class. Preserving those distinctions is more useful than declaring every dataset must be made 50–50.

Change one denominator at a time

  1. The all-negative rule scores 95% accuracy. At threshold 70, accuracy is 94%. Which rule has higher rare-class recall, and what additional information is needed to choose between them?

    Answer: Threshold 70 has recall 4/5; the baseline has zero. The choice requires a specified use case, error consequences or operational constraints and an appropriate evaluation protocol. Frequency and accuracy alone do not encode those requirements.

  2. Hold t=4/5 and f=1/19 fixed, but reduce prevalence to 1/100. What are precision and the ROC point?

    Answer: Precision becomes 76/571, about 13.3%. The ROC point remains (1/19,4/5) under the unchanged class-conditional assumption. This does not establish that the assumptions hold after a real deployment change.

  3. All scores tie. With five positives and 95 negatives, what does this program report for ROC AUC and AP? May you place positives first within the tie to improve AP?

    Answer: ROC AUC is 1/2 and AP is 1/20. The inclusive threshold accepts the entire tied group at once. Ordering tied items by their true labels would introduce label information unavailable to the score rule.

  4. Each minority training image is copied nineteen times, then the expanded rows are split randomly for training and validation. What are the two problems?

    Answer: Copies of one original can cross the split, making the parts dependent and leaking information. The altered evaluation class mix also changes quantities such as precision. Split original independent units first, resample within training only, and document the target evaluation population.

Compare an operating rule, not just a flattering summary

The original Davis–Goadrich paper was read from its university-hosted ICML 2006 PDF. Its metric definitions, fixed-total relationship and interpolation discussion support the distinction between PR and ROC. The example on this page, all counts and code are original; no source dataset or figure is reproduced, and the program does not implement the paper’s achievable-curve construction.

The scikit-learn AP source was read at the 1.7 path, displaying 1.7.2. The imbalanced-learn pitfalls page was read on September 5, 2026, when its mutable stable URL displayed 0.14.2; that is a recorded reference version, not a release-date assertion or a claim that the build is pinned by this URL. No library was executed and no package example was reused.

Tests expand small bins into labeled observations, compare complete per-class reports and tied thresholds, and use ROC trapezoids and a positive-item AP identity as independent summaries. They also check class-count replication, undefined ratios and the prevalence calculation. Those are checks on this exact table machinery; they do not show that balancing a future training set improves its classifier.

Make a prediction, then check

With TPR 4/5 and FPR 1/19 unchanged, how does precision change when positive prevalence falls from 1/20 to 1/100?

Choose one answer

Learning objectives

  • Use one count table to distinguish accuracy, both classes’ precision/recall and balanced accuracy without equating class frequency with error cost.
  • Explain PR/ROC and score ties, and calculate prevalence changes under fixed conditional rates and noninterpolated AP.
  • Explain what training duplication, weights and resampling change while preserving validation separation and the target population.

Prerequisites & connections

Explore related knowledge →

References

  1. The Relationship Between Precision-Recall and ROC Curves
    Jesse Davis; Mark Goadrich · 2006
  2. average_precision_score — scikit-learn 1.7.2 documentation
    scikit-learn contributors
  3. imbalanced-learn — Common pitfalls and recommended practices
    imbalanced-learn developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Nine tests passed. Forty-four tables match an independent item-expanded complete sweep reference, with another 176 complete threshold-report comparisons. ROC uses trapezoid integration and AP a mean over positive items, rather than production pair accumulation or grouped recall increments.
  • Exact main results: TP/FP/FN/TN=4/5/1/90, ROC AUC=458/475 and AP=521/900; changed prevalences give precision 76/81 and 76/571. Checked merged ties, None for absent classes or predictions, weighting/duplication identities, unchanged ROC, input preservation, monotone score transforms, compressed 10^80 counts and invalid input.
  • Complete bilingual prose, identical Python/eight-line stdout, four display formulas, six anchors and four answered exercises. Strict MDX/KaTeX/React HTML and MathML correspondence pass. Only article_text controls article paths in tests. Targeted Humanizer scanning and paragraph-level AI rereading completed; remains written. No model training, sampler execution, real image experiment, whole-site build, human review or browser acceptance.
  • All nine author tests passed. The additional reference uses compressed signed-label/prediction moments for confusion matrices, weighted Wilcoxon midranks for AUC and Abel summation for AP. Sixteen tables, 88 complete threshold reports and eight separately constructed integer prevalence tables agree exactly; no item expansion, ROC trapezoids or production pair/recall accumulation is reused.
  • Reviewed class-frequency versus error-cost distinction, tied-score group handling, absent-class/zero-prediction denominators, both class reports and balanced-error weighting. The original table gives confusion 4/5/1/90, AUC 458/475 and AP 521/900. Fixed conditional score laws, rather than arbitrary dataset shift, are required for ROC invariance under prevalence change.
  • Reviewed resampling inside training folds, duplicated observations versus independent information, noninterpolated AP versus PR area, the constant-score AP baseline and its distinction from finite random-ranking expectations. Input/bit-cost contracts and compressed-count complexity match the complete code; no model-training or calibration guarantee is implied.
  • Both complete articles, exercises and metadata were read. Strict MDX/KaTeX and actual React HTML pass with four displays, six required anchors and four answers per language; all four mathematical annotations match. Author tests verify identical runnable code/stdout. All five final file hashes and exact metadata source IDs/URLs are bound below.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • The Relationship Between Precision-Recall and ROC Curves · Actually opened and read the 8-page original ICML 2006 PDF. Header/footer and introduction identify authors and venue/year. §§2–3, extracted lines 105–174, define confusion metrics and fixed-total correspondence, including the nonzero-recall qualification. §4, lines 407–487, explains nonlinear PR interpolation and ROC trapezoid/ranking equivalence; lines 381–406 distinguish tuning from final testing when selecting curve points. No source figure, clinical example, achievable-hull algorithm or empirical result was reproduced. The author-page mirror failed; the listed university FTP HTTPS copy succeeded.
  • average_precision_score — scikit-learn 1.7.2 documentation · Actually read official API lines 618–642: AP weights precision by recall increments, uses no interpolation and differs from trapezoidal PR area; scores can be unthresholded measures rather than calibrated probabilities. Lines 704–706 identify the implementation convention. No library metrics executed; this program has its own explicit None behavior for absent positive support.
  • imbalanced-learn — Common pitfalls and recommended practices · Actually read stable/common_pitfalls.html §9.1, lines 20–31, for leakage and target-mixture mismatch, and lines 121–153 for placing resampling inside a training-fold pipeline. Read stable/over_sampling.html lines 25–26 and 86–92, plus 153–158: random replacement sampling, numerical SMOTE/ADASYN interpolation and its geometric limitations. Both pages displayed 0.14.2 on 2026-09-05. No source census data, results or model-training code used; no claim that a pipeline cures an otherwise invalid split.
  • The Relationship Between Precision-Recall and ROC Curves · Independently opened the original eight-page university-hosted ICML 2006 PDF. Read authors/venue/year, sections 2–3 on confusion rates, fixed class totals and the nonzero-recall qualification, and section 4 on nonlinear PR interpolation. Also read the tuning/final-test distinction. Text extraction; no Java implementation, figures or benchmark results reproduced.
  • average_precision_score — scikit-learn 1.7.2 documentation · Independently read the fixed 1.7 API rendered as 1.7.2: lines 618–642 and 704–706 specify recall-increment-weighted noninterpolated AP, unthresholded scores and the difference from trapezoidal PR area. The article explicitly defines its own None convention. No library execution.
  • imbalanced-learn — Common pitfalls and recommended practices · Independently read the mutable stable common-pitfalls page, rendered 0.14.2, section 9.1 lines 20–31 and 121–128 on leakage, evaluation prevalence and training-fold pipelines. Also read https://imbalanced-learn.org/stable/over_sampling.html lines 25–26, 86–92 and 153–158 on replacement sampling, interpolation and geometric limitations. No sampler execution or claim of a pinned stable build.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.