Build conformal prediction sets for a classifier with adaptive scores

Why it matters Conformal sets give guaranteed coverage for medical triage, content moderation and LLM routing, where saying 'it is one of these two labels' is safer than a single wrong guess.

Conformal classification returns a set of labels that contains the true label with probability at least 1 - alpha. Adaptive prediction sets (APS) grow larger for uncertain inputs and stay small for confident ones.

Write aps_prediction_sets(cal_probs, cal_labels, test_probs, alpha). Probabilities are (n, K) and (m, K) arrays of softmax outputs. For any probability row, rank classes by probability descending (ties: smaller class index first). The calibration score of a row is the cumulative probability of its ranked classes up to and including the true label. Let k = ceil((n + 1)(1 - alpha)); qhat = the k-th smallest score, or infinity if k > n. For each test row, walk the ranked classes adding their probabilities and include a class if the cumulative total BEFORE adding it is < qhat; the top class is always included. Return a list of sorted label lists.

Signaturedef aps_prediction_sets(cal_probs, cal_labels, test_probs, alpha)

Example

cal_probs [[0.7, 0.2, 0.1], [0.5, 0.3, 0.2], [0.1, 0.8, 0.1], [0.3, 0.3, 0.4]], cal_labels [0, 1, 1, 2], test_probs [[0.6, 0.3, 0.1], [0.34, 0.33, 0.33]], alpha 0.4 gives [[0, 1], [0, 1, 2]] (qhat is 0.8).

Understand the idea

A classifier that says 'cat, 51%' is not sure. Instead of forcing one label, a conformal predictor returns a set like {cat, dog}, with a promise: across many inputs, the true label is in the set at least 90% of the time.

APS builds each set by adding labels from most to least likely until enough probability mass is collected. 'Enough' is learned on a calibration set: for each calibration example, measure how much ranked mass you had to collect to reach its true label. Take the ceil((n + 1)(1 - alpha))-th smallest of these as qhat.

Worked example: a calibration row [0.5, 0.3, 0.2] with true label 1 needs 0.5 + 0.3 = 0.8. A confident test row [0.6, 0.3, 0.1] with qhat = 0.8 keeps class 0 (mass before it 0) and class 1 (mass before 0.6 < 0.8) but not class 2 (mass before 0.9). A flat row [0.34, 0.33, 0.33] keeps all classes whose mass before is under 0.8, giving a bigger set.

Rule: score = cumulative ranked mass up to the true label; include a test class while mass before it < qhat.

Shapes and data flow

cal_probs (n, K) -> scores (n,) -> qhat; test_probs (m, K) -> m label sets
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleaps_prediction_sets([[0.7, 0.2, 0.1], [0.5, 0.3, 0.2], [0.1, 0.8, 0.1], [0.3, 0.3, 0.4]], [0, 1, 1, 2], [[0...
  • Sample 2: too few calibration pointsaps_prediction_sets([[0.9, 0.1], [0.8, 0.2]], [0, 1], [[0.99, 0.01]], 0.1)