Learn/Evaluation/Lesson 6
Chapter 3 · Choose metrics, objectives, and policy

Metric selection by task and decision

Select metrics from the prediction target, decision, error costs, prevalence, slices, horizon, and deployment constraints—not from habit.

65–90 min7 key conceptsReviewed 26 Aug 2026
01 · Production proposition

Teams report excellent accuracy, RMSE, mAP, or perplexity while the fraud queue, forecast, defect review, and assistant outcomes get worse.

This chapter moves from start from the harm to write the counterexample. We will make the idea concrete in a small code example before placing it back inside a production system with the decision latency, review capacity, horizon, and cost envelope for the task.

Decision

Choose the smallest metric set that measures model discrimination, probability/uncertainty quality, decision utility, and system constraints.

Evidence

A versioned metric contract with direction, unit, aggregation, slices, uncertainty, threshold, guardrails, and stop conditions.

Failure consequence

A team chooses ROC-AUC for rare-event review, MAPE with near-zero targets, pixel accuracy for tiny defects, and perplexity as the only assistant launch metric. An unsafe release must degrade to a named baseline or the last known-good version.

02 · Guided chapter

Build the idea one layer at a time.

There is no universally honest metric. A metric is honest only about the particular target, action, error tradeoff, and aggregation rule it was chosen to represent.

Accuracy can celebrate a classifier that ignores every rare positive. ROC-AUC can hide an unusable review queue, MAPE can explode near zero demand, and pixel accuracy can ignore a tiny defect mask. Each number has a question it answers and cases where that question is irrelevant.

A metric contract names a primary decision-facing measure, complementary diagnostics, slice and horizon aggregation, uncertainty, and system guardrails. Threshold-free quality and the chosen operating policy should remain separately visible.

Keep in view
  • metric contracts
  • proper scoring rules
  • prevalence sensitivity
  • ranking metrics
  • forecast scale
  • slice reliability
  • decision utility
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Start from the harm

    Describe what a false positive, false negative, large residual, or misplaced rank causes for a person or operation.

  2. 02

    Choose the smallest portfolio

    Pair one primary task metric with calibration or interval quality, critical slices, and latency or capacity guardrails.

  3. 03

    Write the counterexample

    Construct a plausible model that improves the chosen metric while worsening the decision; add a diagnostic that exposes it.

pythonrare_event_metrics.py
labels = [0] * 18 + [1, 1]
all_negative = [0] * 20
triage_model = [0] * 17 + [1, 1, 0]

def report(predictions):
    tp = sum(p == 1 and y == 1 for p, y in zip(predictions, labels))
    fp = sum(p == 1 and y == 0 for p, y in zip(predictions, labels))
    fn = sum(p == 0 and y == 1 for p, y in zip(predictions, labels))
    accuracy = sum(p == y for p, y in zip(predictions, labels)) / len(labels)
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn)
    return {"accuracy": accuracy, "precision": precision, "recall": recall}

print("all negative", report(all_negative))
print("triage", report(triage_model))

Show why accuracy misses rare-event decision quality.

READ THE EXAMPLE

What to notice

  • The all-negative classifier reaches 90% accuracy while recovering none of the positives.
  • The triage model has the same 90% accuracy yet creates a queue with measurable precision and recall.
YOUR TURN Pause and predict before revealing the answer.

If reviewers can inspect only one case, which additional evaluation quantity should the contract emphasize?

Need a hint?

The operation cares about the very top of the ranked list, not every possible threshold equally.

Check your reasoning

Use precision@1 or expected utility at capacity one, accompanied by uncertainty and the relevant slice guardrails.

Bring forward

Lessons 1, 2, 3, 4, 5 in this course.

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

Choose metrics from the decision’s failure modes, not from the model family’s default report. The cost-weighted harmonic mean of precision and recall below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.

Formal treatment
Fβ=(1+β2) precision recallβ2 precision+recallF_\beta = \frac{(1 + \beta^2)\,\mathrm{precision}\,\mathrm{recall}}{\beta^2\,\mathrm{precision} + \mathrm{recall}}

Cost-weighted harmonic mean of precision and recall

Symbol, shape or unit contract
SymbolMeaning / shape / unit
βrelative weight placed on recall
precisionfraction of positive decisions that are correct
recallfraction of actual positives recovered
F_βone summary at a declared threshold
Open derivation and numerical substitution

Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.

  1. Write the named inputs: β, precision, recall, F_β.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c02(inputs)
assert is_finite(value)
04 · Selection field guide

Choose from the task contract, not a favorite default.

There is no universally best metric.

Start from the decision, harm, target semantics, prevalence, aggregation unit, horizon, and operating constraint. Keep one primary metric, complementary diagnostics, and production guardrails.

Task-to-metric decision map
TaskPrimary starting pointPair withProduction guardrailsNever use alone
Binary probabilityLog loss or Brier score; calibration errorPR-AUC for rare positives; ROC-AUC as discrimination contextPrecision, recall, utility, and queue volume at the operating thresholdAccuracy or AUC alone
Hard classificationBalanced accuracy, MCC, or justified FβPer-class confusion matrix; macro and micro viewsCost by slice, abstention, latency, and fallback outcomesOne aggregate accuracy
Multiclass / multilabelMacro and per-label precision/recall/F1Micro metrics and top-k only when product semantics fitCoverage, calibration, rare-label behavior, and policy capacityMicro average alone
RegressionMAE for linear error cost; RMSE for large-error sensitivityR² only against a meaningful baseline; quantile error when asymmetricResidual slices, bias, uncertainty, and action costA metric chosen without units
ForecastingMASE or scale-aware error by horizon; biasPinball loss and interval coverage/widthInventory or staffing cost, horizon slices, and driftMAPE near zero or one pooled horizon
Ranking / searchNDCG@k for graded order; MRR for first-hit tasksRecall@k for candidate generation; MAP when relevant-set semantics fitCoverage, diversity, freshness, position slices, latency, and online utilityOffline clicks treated as unbiased relevance
Anomaly detectionPrecision or analyst yield at alert budgetEvent recall, false alerts per time unit, detection delayIncident cost, alert fatigue, novelty slices, and investigation latencyROC-AUC on extreme imbalance
DetectionmAP across IoU thresholds, classes, sizes, and slicesRecall at an operating confidence thresholdCalibration, duplicate rate, review load, and device latencyOne mAP number
SegmentationPer-class IoU or Dice plus boundary qualityPixel-level precision/recall and calibration where usefulSmall-object slices, topology failures, latency, and correction effortPixel accuracy on background-heavy masks
ClusteringStability and downstream/operator utilityARI or NMI only when trustworthy labels exist; silhouette as a diagnosticCoverage, actionability, drift, and manual validationInternal geometry declared product success
Language generationTask success, groundedness, factuality, and safetyToken loss/perplexity as an intrinsic diagnostic; calibrated judge or human preference with auditCitation validity, refusal behavior, latency, cost, and adversarial slicesPerplexity or one opaque judge score
05 · Deterministic lab

Change one assumption and make the tradeoff visible.

Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.

Exact computation

Cost-aware threshold

Move the cutoff over a fixed set of scored transactions.

Primary16 cost
Secondary4 caught
Diagnosis2 false alerts

Assumption: Fixed 12-event dataset; false positive costs 2 units and false negative costs 12.

Open nonvisual data table
ItemComputed stateInterpretation
0.92fraudreview
0.84fraudreview
0.76legitreview
0.68fraudreview
0.59legitreview
0.51fraudreview
0.43legitpass
0.37legitpass
0.31fraudpass
0.22legitpass
0.14legitpass
0.08legitpass
06 · Production implications

Trace the complete operating path.

Carry the chapter’s central idea into the system: Choose metrics from the decision’s failure modes, not from the model family’s default report. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Start from the harm” into a written invariant and a failing test.

  2. 02

    Promote rare_event_metrics.py from illustration to a versioned implementation with representative fixtures.

  3. 03

    Use “Write the counterexample” as the release checkpoint: Construct a plausible model that improves the chosen metric while worsening the decision; add a diagnostic that exposes it.

  4. 04

    Serve or materialize behind explicit the decision latency, review capacity, horizon, and cost envelope for the task.

  5. 05

    Join telemetry to mature outcomes and retain a rollback path.

Observability

Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.

Cost

Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.

Failure modes

A team chooses ROC-AUC for rare-event review, MAPE with near-zero targets, pixel accuracy for tiny defects, and perplexity as the only assistant launch metric. Add a detector, owner, mitigation, and stop condition for this class of failure.

Alternatives

Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.

07 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01Which metric is universally best for classification?
02Why can MAPE fail for demand forecasting?
03What should accompany an aggregate ranking metric?
08 · Apply in production

Metric-contract portfolio

Write complete selection contracts for rare fraud, ETA regression, search ranking, and visual defect detection.

  • Primary metric and decision rationale for four tasks
  • Secondary diagnostics, thresholds, and guardrails
  • Aggregation, horizon, slice, and uncertainty definitions
  • Counterexample where each selected metric misleads
  • Release and rollback decision template
Production self-review0/100

Staged hints

Failure diagnosis

  • If offline numbers look impossible, audit prediction-time availability before model code.
  • If quality is sound but the contract fails, measure the exact serialized and served path.
  • If one slice regresses, preserve that slice as a permanent release gate.

Record an honest attempt to unlock the reference solution.

09 · Sources & next depth

Read primary material with a purpose.

10 · Production resolution

Return to the opening failure.

Every model card names why each metric matches the action, which aggregation and horizon it uses, required slice/uncertainty views, and the threshold or policy that turns scores into outcomes.

For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a metric contract, leakage-safe validation, calibration analysis, and experiment plan.

Course production assignmentLate-delivery evaluation contract