Conformal prediction: intervals with a promise
Turn any model's held-out errors into prediction intervals or sets with stated coverage. Learn what the promise covers, and the kind of coverage it doesn't.
What runs in CodeSplash
- LightGBM Verified in Python and R
- Random forest Verified in Python and R
You will be able to
- Compute a conformal interval from out-of-fold errors
- Choose among absolute residuals, CQR, LAC and APS
- Say what marginal coverage does and doesn't promise
Read first
A wrapper for any model
ReadA point prediction hides how wrong it might be. Conformal predictionConformal predictionTurns any model's held-out errors into intervals or sets with a stated coverage. wraps any model, with one idea: use how badly it did on rows it hasn't seen.
- Compute a score on held-out rows, such as .
- Take a high quantile of those scores.
- Report .
If new rows behave like the held-out ones, about the stated share of intervals contain the truth, whatever the model.
Which rank?
PredictPredict first
You have 99 calibration rows, and you want 90% coverage. Which rank among the sorted scores do you take?
Make your guess between 1 and 99 rank, then reveal.
Reveal
: the 90th smallest. The counts the new row. With too few rows the rank runs off the end, and the honest interval is unbounded.
Honest coverage
ExploreThe same idea drives any stated coverage: does an interval, over many repeats, contain the truth as often as it promises? Lower Sample size n and read how much a single sample's interval wobbles, while the long-run share holds.
AExplorable · The confidence-interval dance
What does it mean for an interval to be 95% confident?
Out of these studies' intervals, how many will miss the true mean?
Confidence level
Population
Interval
The z shortcut uses 1.96 with the sample SD — fine for large n only.
96 of 100 contain μ · 4 miss
Commit your prediction above to see the result
Make your prediction to see the result.
Conformal coverage is an average over rows and over draws of the calibration set. For any one run, it'll fall a little above or below the target.
Four methods
Read| Method | Task | Shape |
|---|---|---|
| Absolute residuals | Numbers | Same width for every row |
| CQR | Numbers | Width varies by row, from two quantile models |
| LAC | Classes | Smallest sets on average |
| APS | Classes | Larger sets for hard rows |
With classes, you get a prediction set: the labels that can't be ruled out. A set of one means confidence, and a set with many labels is the model's way of saying it can't tell.
The ingredient for CQR is two quantile runs on the same plan. LightGBM can provide them: the upper quantile run for ozone has an RMSE of 20.3 on the same rows.
What it doesn't promise
ReadCoverage is marginal, an average over all rows. A 90% interval may cover 97% of easy rows and 70% of hard ones.
And it assumes new rows are exchangeable with the calibration rows. Under drift the promise weakens, so a monitored coverage rate is a useful alarm.
A wider interval than you'd like isn't a failure. It's what the model knows.
Check your understanding
CheckpointCheck yourself
Which change makes conformal intervals narrower with coverage kept the same?
Show the answer
Answer: a
Better predictions give smaller held-out errors, so shrinks. Coverage doesn't change, because it's what the procedure guarantees.
Check yourself
For most rows, a prediction set for 3 classes has all 3 labels. What does that say?
Show the answer
Answer: b
Set size is an honest signal of how much the model can tell. Lower the coverage or improve the model.
Check yourself
A 90% interval has 90% coverage overall. Can you promise 90% for women over 60?
Show the answer
Answer: b
Conditional coverage isn't guaranteed. Measure it on the groups you care about, using held-out rows.
Check yourself
There are 99 calibration rows, and you want 95% coverage. Which rank do you use?
Show the answer
Answer: 95
.
Get intervals
In the appOpen a run and go to Uncertainty. For numbers, Method offers Intervals from out-of-fold residuals or Conformalized quantile regression (two quantile runs), and for classes LAC or APS. Set Coverage (%). The summary gives coverage on the test rows and by cross-fitting, with the interval width or the set size.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_val_predict, train_test_split
from sklearn.pipeline import make_pipeline
df = pd.read_csv("airquality.csv").dropna(subset=["Ozone"])
X, y = df[["Solar.R", "Wind", "Temp", "Month"]], df["Ozone"].to_numpy()
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=1)
model = make_pipeline(SimpleImputer(strategy="median"), RandomForestRegressor(300, random_state=1))
scores = np.abs(ytr - cross_val_predict(model, Xtr, ytr, cv=5))
n = len(scores)
q = np.sort(scores)[min(int(np.ceil((n + 1) * 0.9)), n) - 1]
pred = model.fit(Xtr, ytr).predict(Xte)
print("half width", round(q, 1), "test coverage", round(np.mean(np.abs(yte - pred) <= q), 3))library(ranger)
df <- airquality[!is.na(airquality$Ozone), ]
df$Solar.R[is.na(df$Solar.R)] <- median(df$Solar.R, na.rm = TRUE)
set.seed(1)
test <- sample(nrow(df), round(0.2 * nrow(df)))
tr <- df[-test, ]; te <- df[test, ]
fold <- sample(rep(1:5, length.out = nrow(tr)))
f <- Ozone ~ Solar.R + Wind + Temp + Month
scores <- numeric(nrow(tr))
for (k in 1:5) {
fit <- ranger(f, tr[fold != k, ], num.trees = 300, seed = 1)
scores[fold == k] <- abs(tr$Ozone[fold == k] - predict(fit, tr[fold == k, ])$predictions)
}
q <- sort(scores)[min(ceiling((length(scores) + 1) * 0.9), length(scores))]
pred <- predict(ranger(f, tr, num.trees = 300, seed = 1), te)$predictions
round(c(half_width = q, test_coverage = mean(abs(te$Ozone - pred) <= q)), 3)Recap
Recap- Conformal prediction turns held-out errors into intervals or sets for any model.
- The rank is , and better models give narrower results.
- Coverage is marginal, and it assumes new rows look like the old ones. Check groups and watch for drift.
Concepts in this lesson