Build split conformal prediction intervals for a regressor

Why it matters Conformal intervals give distribution-free error bars for demand forecasts, price predictions and LLM-judged scores without retraining the model.

Split conformal prediction wraps any regressor and returns intervals that contain the truth with probability at least 1 - alpha, assuming only exchangeable data.

Write conformal_interval(cal_true, cal_pred, test_pred, alpha). Compute calibration scores s_i = |cal_true_i - cal_pred_i| for n calibration points. Let k = ceil((n + 1)(1 - alpha)). If k > n, q is infinite; otherwise q is the k-th smallest score. Return (lower, upper, q): float arrays test_pred - q and test_pred + q, and q as a float.

Signaturedef conformal_interval(cal_true, cal_pred, test_pred, alpha)

Example

cal_true [1, 2, 3, 4, 5], cal_pred [1.5, 1.8, 3.4, 4.1, 3.9], test_pred [10, 20], alpha 0.34 gives lower [9.5, 19.5], upper [10.5, 20.5] and q 0.5.

Understand the idea

Conformal prediction answers: how wide should my error bars be so they are right 90% of the time? It uses a held-out calibration set and only one assumption, that new points look like the calibration points.

Score each calibration point by how wrong the model was, |y - yhat|. If a new point is just like these, its error is equally likely to fall anywhere in the sorted list of n + 1 errors. So the ceil((n + 1)(1 - alpha))-th smallest calibration error covers it with probability at least 1 - alpha.

Worked example: 5 calibration errors 0.5, 0.2, 0.4, 0.1, 1.1, sorted 0.1, 0.2, 0.4, 0.5, 1.1. With alpha = 0.34, k = ceil(6 * 0.66) = ceil(3.96) = 4, so q = 0.5, the 4th smallest error. A test prediction of 10 gets the interval [9.5, 10.5]. With alpha = 0.2, k = ceil(4.8) = 5 and q jumps to 1.1: asking for more coverage costs width.

Rule: q = k-th smallest |y - yhat| with k = ceil((n + 1)(1 - alpha)); interval = yhat plus or minus q.

Conformal intervals are used for demand forecasts and price estimates where error bars must be trustworthy.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleconformal_interval([1, 2, 3, 4, 5], [1.5, 1.8, 3.4, 4.1, 3.9], [10, 20], 0.34)
  • Sample 2: too few pointsbool(np.isinf(conformal_interval([1, 2, 3], [1.1, 2.2, 2.7], [0], 0.1)[2]))
  • Test 3: randomconformal_interval(_yt, _yp, [0.0, 1.0], 0.1)
  • Test 4: alpha 0.5conformal_interval([0, 0, 0, 0], [1, 2, 3, 4], [5], 0.5)