AI Wiki中文/EN

Cost-sensitive learning: what does an error cost?

代价敏感学习

Compare exact action risks, derive cost thresholds and a review option, and avoid applying class weights twice.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The most likely label need not be the best action

A toy inspection system assigns a part a defect probability of 1/5. Passing a defective part incurs nine loss points; flagging a sound part incurs one. Correct decisions cost zero. The part is more likely sound, but passing it has expected loss 9/5, whereas flagging it has expected loss 4/5. Under these specified penalties, flagging is the better action.

Nothing in that calculation changes the probability that the part is defective. It changes what to do with that probability. Cost-sensitive learning and decision-making distinguish the prediction target from the consequences of a decision. Elkan’s original paper, §1 states the minimum-expected-cost rule and uses cost rows for decisions and columns for true classes.

The nine-to-one penalties are chosen for this teaching task. They cannot be inferred from a class being rare, and changing them requires a reason outside the observed class counts. A decision penalty may represent time, resource use or another stated objective; its units and reference point must be consistent.

Average over unknown outcomes, then compare actions

Let pᵧ(x) be the conditional probability of true class y and L(a,y) the cost of taking action a when y is true. Actions may include class predictions or a review option. Define conditional risk:

r(a∣x)=∑y=1KL(a,y)py(x),a∗(x)∈arg min⁡a∈Ar(a∣x).r(a\mid x)=\sum_{y=1}^K L(a,y)p_y(x),\qquad a^*(x)\in\operatorname*{arg\,min}_{a\in\mathcal A}r(a\mid x).

For known probabilities and costs, this solves the pointwise expected-loss problem. An exact tie leaves several optimal actions. Our code returns them all and chooses the first action index. Zero-one loss recovers the most probable class because the risk of predicting y is 1−pᵧ. Other matrices need not preserve that choice.

For a binary target, write p=P(Y=1|x), set correct-decision costs to zero, and assume strictly positive false-positive and false-negative costs. Comparing the two risks gives:

r(0)=cFNp,r(1)=cFP(1−p),r(1)<r(0) ⟺ p>cFPcFP+cFN.r(0)=c_{\mathrm{FN}}p,\qquad r(1)=c_{\mathrm{FP}}(1-p),\qquad r(1)<r(0)\ \Longleftrightarrow\ p>\frac{c_{\mathrm{FP}}}{c_{\mathrm{FP}}+c_{\mathrm{FN}}}.

At equality both actions minimize risk. The familiar 1/2 threshold follows only when the two costs are equal under these assumptions. Nonzero correct-decision costs require comparing the full matrix again. Scores that merely rank cases are not interchangeable with conditional probabilities in this formula.

A review action changes the action set

Suppose action 2 has total cost c_R regardless of the class. That assumption already includes the consequences after review; if reviewers make errors or costs depend on the outcome, the row should change. The first inequality below gives the probabilities where review is strictly cheaper than both binary decisions; the second makes that interval nonempty:

cRcFN<p<1−cRcFP,cR<cFPcFNcFP+cFN.\frac{c_R}{c_{\mathrm{FN}}}<p<1-\frac{c_R}{c_{\mathrm{FP}}},\qquad c_R<\frac{c_{\mathrm{FP}}c_{\mathrm{FN}}}{c_{\mathrm{FP}}+c_{\mathrm{FN}}}.

With costs 1, 9 and 3/10, the interval is (1/30,7/10). The boundaries are ties. This is a decision calculation under a specified review row, not evidence that real review achieves those outcomes. A shared review-capacity limit would couple decisions across cases and require another optimization problem.

Training weights can change the probability scale

One option is to learn useful probabilities first, then choose actions using their costs. Another is to change the training loss or sampling scheme. These choices are related but cannot be combined blindly. For example, at a fixed x with true positive probability p, the minimizer q of class-weighted binary log loss is:

q∗=arg min⁡0≤q≤1[−w1plog⁡q−w0(1−p)log⁡(1−q)]=w1pw1p+w0(1−p),p=w0q∗w1(1−q∗)+w0q∗.q^*=\operatorname*{arg\,min}_{0\leq q\leq1}\big[-w_1p\log q-w_0(1-p)\log(1-q)\big]=\frac{w_1p}{w_1p+w_0(1-p)},\qquad p=\frac{w_0q^*}{w_1(1-q^*)+w_0q^*}.

The weights are strictly positive; endpoint solutions use the usual limiting convention. For interior p, set the derivative to zero and solve. At p=0 or 1, the corresponding endpoint minimizes the loss. This is the ideal unrestricted population optimum. A finite, misspecified or regularized classifier need not attain it, so the inverse is not an automatic calibration repair.

If w₁=9 and w₀=1, thresholding this ideal q at 1/2 already corresponds to thresholding the original p at 1/10. Applying the nine-to-one cost threshold again to q counts the intended asymmetry twice. In contrast, simply changing a decision threshold on an unchanged fitted model leaves its probabilities unchanged. The fixed official threshold guide distinguishes these statistical and decision stages.

Return every risk, including the action not taken

This complete Python 3.10+ program computes exact risks from integers or Fraction values. Probability entries must be nonnegative and sum exactly to one. There must be at least one true class and action. Every action row needs one nonnegative cost per class. Floats, Booleans and malformed lists are rejected; the main probability and cost inputs must be lists or tuples. Nothing is silently renormalized.

decide performs no model fitting: the probabilities and cost matrix are inputs. weighted_probability evaluates the derived ideal weight transform or its inverse; it also does not fit a classifier. Its inverse option is a Boolean switch. Action indices 0,1,2 in the example mean pass, flag and review. The matrix orientation is part of the interface.

from fractions import Fraction as F


def number(value):
    if type(value) not in (int, F):
        raise ValueError('Use integers or Fractions, not floats or Booleans.')
    return F(value)


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


def decide(probabilities, costs):
    """Cost rows are actions; columns are true classes in probability order."""
    p = tuple(number(v) for v in sequence(probabilities))
    if not p or any(v < 0 for v in p) or sum(p) != 1:
        raise ValueError('Class probabilities must be nonnegative and sum to one.')
    costs = sequence(costs)
    if not costs:
        raise ValueError('At least one action is required.')
    risks = []
    for row in costs:
        values = tuple(number(c) for c in sequence(row))
        if len(values) != len(p) or any(c < 0 for c in values):
            raise ValueError('Each action needs one nonnegative cost per class.')
        risks.append(sum((prob * cost for prob, cost in zip(p, values)), F()))
    minimum = min(risks)
    winners = tuple(i for i, risk in enumerate(risks) if risk == minimum)
    return {'action': winners[0], 'minimizers': winners,
            'risks': tuple(risks), 'minimum': minimum}


def weighted_probability(p, w0, w1, inverse=False):
    p, w0, w1 = map(number, (p, w0, w1))
    if not 0 <= p <= 1 or w0 <= 0 or w1 <= 0 or type(inverse) is not bool:
        raise ValueError('Probability in [0,1], positive weights and Boolean inverse required.')
    if inverse:
        return w0 * p / (w1 * (1 - p) + w0 * p)
    return w1 * p / (w1 * p + w0 * (1 - p))


if __name__ == '__main__':
    binary = ((0, 9), (1, 0))
    with_review = binary + ((F(3, 10), F(3, 10)),)
    for p in (F(1, 50), F(1, 5), F(4, 5)):
        answer = decide((1-p, p), with_review)
        print('p / risks / action:', str(p), tuple(map(str, answer['risks'])), answer['action'])
    print('threshold tie:', decide((F(9, 10), F(1, 10)), binary)['minimizers'])
    p = F(1, 20)
    q = weighted_probability(p, 1, 9)
    restored = weighted_probability(q, 1, 9, inverse=True)
    print('weighted / restored:', str(q), str(restored))
    print('true-p / weighted-q actions:', decide((1-p, p), binary)['action'],
          decide((1-q, q), binary)['action'])

Actual output:

p / risks / action: 1/50 ('9/50', '49/50', '3/10') 0
p / risks / action: 1/5 ('9/5', '4/5', '3/10') 2
p / risks / action: 4/5 ('36/5', '1/5', '3/10') 1
threshold tie: (0, 1)
weighted / restored: 9/28 1/20
true-p / weighted-q actions: 0 1

For p=1/50, passing costs 9/50 and wins. For p=1/5, review costs 3/10 and wins over both alternatives. For p=4/5, flagging costs 1/5 and wins. At p=1/10 without review, both binary decisions cost 9/10.

The final lines expose the weighting trap. A true p=1/20 should lead to passing under the binary matrix: risks are 9/20 and 19/20. Its ideal weighted score is q=9/28. Treating that q as the original probability wrongly selects flagging. Inverting the ideal transform restores 1/20. On real fitted scores, calibration and model error would need separate checks.

For A actions and K classes, decide uses O(AK) rational arithmetic operations and O(A+K) extra numeric storage. One cost row is validated at a time; the input matrix itself is not included in this extra-storage count. The returned tuple of risks and ties takes O(A) space. Weight transforms use a constant number of rational operations. Numerator and denominator sizes determine the actual bit cost. The code does not mutate inputs.

The calculation is only as useful as its probabilities and costs

A rare label is a frequency fact, not a cost specification. Imbalanced learning studies a related data problem. Choosing a high penalty solely because a label is rare can encode a different objective from the one intended. Accuracy, balanced accuracy, F1 and expected cost optimize different quantities; state the desired one before tuning.

A useful decision rule also needs probabilities for the intended population. A ranking metric can remain unchanged under a monotone score transformation even though using those transformed scores as probabilities changes cost decisions. Distribution shift, poor calibration or uncertain penalties can move the preferred action. Inspect sensitivity over plausible probability and cost ranges rather than trusting a single exact-looking answer.

Multiplying all costs by a positive constant preserves the minimizers. Adding a common amount to a column also preserves them: every action gains the same probability-weighted term for that true class. Adding to only one action row generally changes decisions. The numerical risks change under these transformations, so retain the original matrix when reporting actual costs. A row that is more expensive in every class can never win; with only weak inequalities, zero-probability classes and ties require care.

If a threshold is selected empirically, tune it on validation data or inside a suitable cross-validation procedure, not on data already used to fit the model and not on the final test set. The official guide’s validation notes explain this separation. Report the matrix, class order, chosen threshold or action rule, and held-out realized cost per case. The finite exact calculations here are neither a performance estimate nor a guarantee of successful deployment.

Change a cost, then check the decision again

1. False positives cost 1 and false negatives cost 9. What happens at p=0.1 and at p=0.2, with no review action?

Answer: The threshold is 0.1. At 0.1 the two risks are both 0.9, so both actions are optimal and the code chooses index 0. At 0.2 the risks are 1.8 and 0.8, so index 1 wins even though class 0 is more probable.

2. Add a review row with constant cost 0.3. At which probabilities does it strictly beat both binary actions?

Answer: For 1/30<p<7/101/30<p<7/10. At the lower boundary it ties passing; at the upper boundary it ties flagging. A capacity limit or imperfect review could require a different model of the decision.

3. Multiply every cost by 100, then add 2 to every entry in the true-class-1 column. Do the chosen actions change?

Answer: No. Each risk becomes 100 times its old value plus 2p, a term common to all actions. The minimizers and ties are unchanged, but the reported risk numbers differ. Adding 2 to only one action row would not have this invariance.

4. A classifier is trained with positive-class weight 9. Is its output necessarily the original probability, and can the inverse formula be trusted without further checks?

Answer: No. At the ideal unrestricted weighted-log-loss optimum the output is q*, not p, and the formula exactly inverts that particular transformation. Finite data, model restrictions and regularization can invalidate that ideal relation. Check the fitted probability meaning and calibration before applying a cost rule; avoid applying the same asymmetry twice.

Keep the objective separate from a software default

Elkan’s manuscript for IJCAI’01 makes the probability-estimation and decision stages explicit. Its first section is useful for checking matrix orientation and consistent cost baselines before changing class frequencies. The point is to specify what each action costs under each possible outcome, then use the appropriate probabilities for those outcomes.

The fixed scikit-learn 1.7.2 threshold guide connects that distinction to a software workflow: the fitted probability model can stay the same while the selected labels change. Its validation notes explain why choosing a threshold on reused training data is a separate source of optimism. Continue with logistic regression, model evaluation and train/validation/test splits to connect estimation, decisions and evidence.

Make a prediction, then check

False negatives cost 9, false positives 1 and correct decisions 0. With p=0.2 and no review option, which action minimizes expected cost?

Choose one answer

Learning objectives

  • Compute conditional risks with action rows and true-class columns, explaining why the most probable class need not give the best action.
  • Derive binary thresholds, review intervals and ties; distinguish error costs from class frequencies.
  • Explain the ideal probability-scale change under weighted log loss and its limits, avoiding double application of asymmetric costs.

Prerequisites & connections

Explore related knowledge →

References

  1. The Foundations of Cost-Sensitive Learning
    Charles Elkan · 2001
  2. Tuning the decision threshold for class prediction (1.7.2)
    scikit-learn contributors

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.

  • Five author tests pass: 24 three-class/four-action cases use independent equal-probability ticket averages for risks/ties/winners; 21 binary threshold points, review endpoint ties, zero-probability classes, dominance, class-column permutations and unit changes checked.
  • Thirty-three weighted-population stationary points/inverses checked with exact fractions, plus endpoints and a100-digit denominator. Inputs unchanged, invalid probabilities/matrices/weights rejected; full stdout and both locales align on4 displays/6 anchors/4 answers, with strict MDX/KaTeX and actual React HTML passing.
  • 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 Foundations of Cost-Sensitive Learning · Root actually opened author-hosted six-page PDF and read first-page header plus §1/§1.1/§1.2, extracted lines0–190: minimum conditional expected cost, action/prediction rows versus true-class columns, scaling/baseline discussion and start of binary threshold comparison. Mathematical OCR is garbled, so equations were independently derived and checked in exact arithmetic. No whole-paper review, monetary case reproduction or blanket recommendation about reweighting specific learners.
  • Tuning the decision threshold for class prediction (1.7.2) · Root followed official1.7 model_selection link31 to classification_threshold.html, displaying1.7.2, and read lines71–79,96–108,125–132: statistical versus decision stage, probability/score thresholds, fitted probabilities unchanged under threshold changes, scoring choices and train/threshold-validation separation. No health/financial scenario reused and no estimator executed.
  • The Foundations of Cost-Sensitive Learning · Actually opened author-hosted six-page manuscript. Header identifies Charles Elkan and forthcoming IJCAI01. Read §1 and §1.1, extracted lines 23–111: conditional expected cost, prediction/action rows and true-class columns, dominance and positive scaling; §1.2 lines 112–168: consistent baselines; §1.3 lines 169–214: binary action comparison and ties. Equation OCR is garbled; mathematical claims were independently rederived and tested rather than claiming reliable transcription of every symbol. No financial example, broad empirical recommendation or whole-paper review reused.
  • Tuning the decision threshold for class prediction (1.7.2) · Actually read the exact metadata URL, rendered scikit-learn 1.7.2. Lines 71–79 distinguish probability estimation and decisions; 96–108 describe unchanged probability outputs under threshold changes, decision metrics and class labels; 125–132 describe internal cross-validation, prefit validation separation and manually fixed thresholds. No library run or dataset-performance reproduction claimed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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