Quantiles, coverage, conformal prediction and calibration
A prediction is one number. A decision usually needs to know how far off that number may be. This note covers two ways of saying so, and how to check them on data the model has not seen: an interval for a numerical outcome, and a probability for a binary one. Throughout, the numerical example is a simulation, so that the right answers are known: \(x\) is uniform on \([0, 10]\), and \[
Y = 3 + x + 2\sin x + (0.5 + 0.35\,x)\,\varepsilon, \qquad \varepsilon \sim N(0, 1),
\] so the noise grows with \(x\). There are 1,000 points to fit on and 2,000 fresh points to check on.
Show the setup code
# quantreg is on the course's package list; plotly draws the interactive figures and is needed only here.library(tidyverse); library(quantreg); library(xgboost); library(NHANES); library(plotly)# Course palette (theme/st310.scss): viridis for the primary scale, magma for the second.v_dark <-"#440154"; v_blue <-"#31688e"; v_teal <-"#21918c"; m_pink <-"#b73779"; m_orange <-"#fc8961"# NHANES adults, split as in the lecture (data note: data/nhanes.md); then the simulation.nh <- NHANESraw |>filter(Age >=20) |>select(Diabetes, Gender, Age, Race1, Poverty, Weight, Height, BMI, Pulse, BPSysAve, TotChol, DirectChol, PhysActive) |>drop_na() |>mutate(diabetes =as.numeric(Diabetes =="Yes"), male =as.numeric(Gender =="male"),active =as.numeric(PhysActive =="Yes"))set.seed(310)nh_id <-sample(nrow(nh))nh_train <- nh[nh_id[1:4000], ]nh_tune <- nh[nh_id[4001:7000], ]f_sim <-function(x) 3+ x +2*sin(x)s_sim <-function(x) 0.5+0.35* xsim <-function(n) tibble(x =runif(n, 0, 10)) |>mutate(y =f_sim(x) +s_sim(x) *rnorm(n))het_train <-sim(1000)het_fresh <-sim(2000)x_grid <-tibble(x =seq(0, 10, length.out =201))
Two kinds of interval
At a new input \(x_0\) the outcome is \(Y_0 = f^\star(x_0) + \varepsilon_0\). A confidence interval is for \(f^\star(x_0)\), the average outcome at \(x_0\): it describes how far the fitted model may be from the regression function, and it narrows as the training sample grows. A prediction interval is for \(Y_0\) itself, so it must also cover \(\varepsilon_0\). The bias–variance decomposition at a point says why it cannot narrow to nothing: \[
\mathbb E\big[(Y_0 - \hat f(x_0))^2\big] = \sigma^2 + \text{bias}^2 + \text{variance},
\] and more data shrink the variance, never \(\sigma^2\). For a linear model with normal noise of constant variance, R gives both: predict(fit, newdata, interval = "confidence") and interval = "prediction". This note is about the second kind, without assuming normal noise of constant variance.
Quantiles and the pinball loss
Squared error makes the conditional mean the best prediction, and absolute error the conditional median. The pinball loss makes it a conditional quantile. For an outcome \(y\) and a prediction \(\hat y\), \[
\rho_\tau(y - \hat y) = (y - \hat y)\,\big(\tau - \mathbf 1\{y < \hat y\}\big),
\] which charges \(\tau\) for each unit of underprediction and \(1 - \tau\) for each unit of overprediction; with \(\tau = \frac12\) it is half the absolute error. As a function of the error \(y - \hat y\) it is two lines that meet at zero: slope \(\tau\) to the right, where the prediction is too low, and slope \(-(1 - \tau)\) to the left, where it is too high. With \(\tau = 0.9\) a shortfall costs nine times an overshoot of the same size, so the best prediction is high.
Move the slider to change \(\tau\).
Show the code
pin <-function(e, tau) e * (tau - (e <0)) # the pinball loss of an error e = y - y-hatloss_grid <-expand_grid(tau =seq(0.05, 0.95, by =0.05), e =seq(-3, 3, by =0.05)) |>mutate(loss =pin(e, tau))if (knitr::is_html_output()) {plot_ly(loss_grid, x =~e, y =~loss, frame =~tau, type ="scatter", mode ="lines",line =list(color = v_dark, width =3), showlegend =FALSE,hovertemplate ="error %{x:.2f}<br>loss %{y:.2f}<extra></extra>") |>layout(xaxis =list(title ="error, y − ŷ"), yaxis =list(title ="pinball loss", range =c(0, 3))) |>animation_opts(frame =300, redraw =FALSE) |>animation_slider(currentvalue =list(prefix ="τ = "))} else {# The static version, for print: three values of tau.ggplot(filter(loss_grid, round(tau, 2) %in%c(0.1, 0.5, 0.9)), aes(e, loss, colour =factor(tau))) +geom_line(linewidth =1) +scale_colour_manual(values =c(`0.1`= m_pink, `0.5`= v_dark, `0.9`= v_teal), name =expression(tau)) +labs(x =expression("error, "* y -hat(y)), y ="pinball loss") +theme_minimal(base_size =12)}
If \(Y\) given \(X = x\) has a continuous distribution with a finite mean, the conditional \(\tau\)-quantile \(q_\tau(x)\) minimizes the expected loss \(\mathbb E[\rho_\tau(Y - \hat y) \mid X = x]\) over \(\hat y\), uniquely unless the distribution function is flat at \(\tau\) (the quantile optimality theorem, stated in the lecture).
Fitting a model with the pinball loss is quantile regression: minimize \(\frac1n\sum_i \rho_\tau(y_i - f(x_i))\) over a class of functions \(f\), a line or a sum of trees, just as least squares minimizes the average squared error.
An interval from two quantiles
A 90% interval from two quantile fits is \(\hat C(x) = [\hat q_{0.05}(x), \hat q_{0.95}(x)]\). The true quantiles would cover \(Y\) with probability \(0.9\) at every \(x\); estimated quantiles aim at that, and miss by however much the fits are wrong. The figure compares four ways to make a 90% interval on the simulated data; the dashed lines are the true 5% and 95% quantiles.
Click a name in the legend to show or hide it.
Linear model, constant noise: least squares, with R’s prediction interval, which assumes normal noise of constant variance. It widens slightly toward the ends of the range, with the uncertainty in the fitted line.
Mean and variance: least squares for the mean, then a second regression, of the absolute residuals on \(x\), for the spread; the interval is the mean \(\pm\, 1.645 \times\) the spread (the absolute value of a normal error has mean \(\sqrt{2/\pi}\) times its standard deviation, so the second fit is scaled by \(\sqrt{\pi/2}\)).
Linear quantiles: two quantile regressions on a line, with quantreg::rq().
Boosted quantiles: two boosted-tree fits with the pinball loss, xgboost’s objective = "reg:quantileerror".
Show the code
z90 <-qnorm(0.95)fit_lm <-lm(y ~ x, data = het_train)fit_abs <-lm(abs(resid(fit_lm)) ~ x, data = het_train)fit_qr <-rq(y ~ x, tau =c(0.05, 0.95), data = het_train)boost_q <-function(tau) xgboost(x =as.matrix(het_train["x"]), y = het_train$y,objective ="reg:quantileerror", quantile_alpha = tau,max_depth =2, learning_rate =0.05, nrounds =300, min_child_weight =30, nthread =1)fit_b05 <-boost_q(0.05)fit_b95 <-boost_q(0.95)intervals <-function(d) { pi_lm <-predict(fit_lm, d, interval ="prediction", level =0.9) m <-predict(fit_lm, d); s <-predict(fit_abs, d) *sqrt(pi /2) qr <-predict(fit_qr, d) X <-as.matrix(d["x"])list(`linear model, constant noise`=cbind(pi_lm[, "lwr"], pi_lm[, "upr"]),`mean and variance`=cbind(m - z90 * s, m + z90 * s),`linear quantiles`= qr,`boosted quantiles`=cbind(predict(fit_b05, X), predict(fit_b95, X)))}bands <-imap_dfr(intervals(x_grid), function(b, nm) tibble(x = x_grid$x, lo = b[, 1], hi = b[, 2], method = nm))if (knitr::is_html_output()) {p <-plot_ly() |>add_markers(data = het_train, x =~x, y =~y, marker =list(color ="rgba(0,0,0,0.25)", size =4),name ="training points", hoverinfo ="skip")band_cols <-c(`linear model, constant noise`= m_orange, `mean and variance`= v_blue, `linear quantiles`= m_pink, `boosted quantiles`= v_teal)for (nm innames(band_cols)) { b <-filter(bands, method == nm) p <- p |>add_ribbons(data = b, x =~x, ymin =~lo, ymax =~hi, name = nm,fillcolor =paste0(band_cols[[nm]], "55"), line =list(color = band_cols[[nm]]),visible =if (nm %in%c("linear model, constant noise", "boosted quantiles")) TRUEelse"legendonly",hovertemplate =paste0(nm, ": %{y:.1f}<extra></extra>"))}p |>add_lines(data = x_grid, x =~x, y =~f_sim(x) - z90 *s_sim(x), line =list(color ="black", dash ="dash"),name ="true quantiles", legendgroup ="true", hoverinfo ="skip") |>add_lines(data = x_grid, x =~x, y =~f_sim(x) + z90 *s_sim(x), line =list(color ="black", dash ="dash"),showlegend =FALSE, legendgroup ="true", hoverinfo ="skip") |>layout(xaxis =list(title ="x"), yaxis =list(title ="y"), legend =list(x =0.02, y =0.98))} else {# The static version, for print: one panel per method.ggplot(mutate(bands, method =fct_inorder(method)), aes(x)) +geom_point(data = het_train, aes(y = y), alpha =0.15, size =0.5) +geom_ribbon(aes(ymin = lo, ymax = hi), fill = v_teal, alpha =0.35) +geom_line(data = x_grid, aes(y =f_sim(x) - z90 *s_sim(x)), linetype ="dashed") +geom_line(data = x_grid, aes(y =f_sim(x) + z90 *s_sim(x)), linetype ="dashed") +facet_wrap(~ method, nrow =2) +labs(x ="x", y ="y") +theme_minimal(base_size =12)}
Checking an interval
Check a claimed 90% on data that played no part in the fit: the share of fresh outcomes inside their intervals (the coverage), the mean width, and both again within ranges of \(x\). The linear model’s interval is close to 90% overall and far from it within ranges, too wide where the noise is small and too narrow where it is large; covering is not enough on its own either, since widening an interval never lowers its coverage.
Show the code for the table
# Coverage of the fresh points, overall and within five ranges of x, and the mean width; one row per interval.coverage_table <-function(ints) {imap_dfr(ints, function(b, nm) tibble(method = nm, range =cut(het_fresh$x, c(0, 2, 4, 6, 8, 10), include.lowest =TRUE),inside = het_fresh$y >= b[, 1] & het_fresh$y <= b[, 2], width = b[, 2] - b[, 1])) |>group_by(method =fct_inorder(method)) |>summarise(all =mean(inside),`x in [0, 2]`=mean(inside[range =="[0,2]"]), `(2, 4]`=mean(inside[range =="(2,4]"]),`(4, 6]`=mean(inside[range =="(4,6]"]), `(6, 8]`=mean(inside[range =="(6,8]"]),`(8, 10]`=mean(inside[range =="(8,10]"]), `mean width`=mean(width)) |>mutate(across(all:`(8, 10]`, \(v) sprintf("%.0f%%", 100* v)), `mean width`=sprintf("%.1f", `mean width`)) |> knitr::kable(align ="lrrrrrrr")}coverage_table(intervals(het_fresh))
method
all
x in [0, 2]
(2, 4]
(4, 6]
(6, 8]
(8, 10]
mean width
linear model, constant noise
88%
100%
98%
86%
82%
78%
9.1
mean and variance
89%
93%
93%
83%
87%
90%
8.7
linear quantiles
88%
92%
93%
82%
85%
90%
8.6
boosted quantiles
87%
84%
87%
94%
79%
89%
7.3
The true quantiles have mean width 7.5 on these points. Coverage by range is a diagnostic, not a certificate: a range can be right on average while a smaller group within it is not. Could a method promise 90% at every \(x\)? Marginal coverage averages over \(X\), \(P(Y \in \hat C(X)) \ge 0.9\); conditional coverage asks for \(P(Y \in \hat C(X) \mid X = x) \ge 0.9\) at every \(x\). Barber, Candès, Ramdas and Tibshirani (2021) show that if a procedure guarantees the second in finite samples for every distribution, then wherever the inputs are continuous its intervals are infinitely long on average (their Proposition 2.2).1 Guarantees for groups, such as each range of \(x\), and results that rest on assumptions about the distribution, or hold as \(n\) grows, remain possible. No method does best on every distribution, and none can promise coverage at every \(x\) without saying something about the distribution.
Conformalized quantile regression
An interval from two quantile fits covers as well as the fits are right, and the fits do not say how right they are. Checked on the points that fitted them, they look better than they are, just as training error underestimates the risk. Conformalized quantile regression (CQR; Romano, Patterson and Candès 2019, section 4) measures how far the fits miss on rows they did not see, and moves both ends of the interval by that amount. For a \(1 - \alpha\) interval, here \(\alpha = 0.1\):
Split the training rows in two. On the first part, fit a lower and an upper quantile, \(\hat q_{\mathrm{lo}}\) and \(\hat q_{\mathrm{hi}}\) (here the 5% and 95% quantiles), by any method. Keep the other \(m\) rows, the calibration set, for the next step.
On each calibration row, compute the score\[
E_i = \max\big\{\hat q_{\mathrm{lo}}(x_i) - y_i,\ y_i - \hat q_{\mathrm{hi}}(x_i)\big\}
\] (their equation 6). If \(y_i\) is above the interval, \(E_i\) is how far above the upper end; if below, how far below the lower end; if inside, \(E_i \le 0\), minus the distance to the nearer end.
Let \(Q\) be the \(k\)-th smallest of the \(m\) scores, with \(k = \lceil (1 - \alpha)(m + 1) \rceil\); in their equation 8, the \((1 - \alpha)(1 + 1/m)\)-th empirical quantile. (If \(k > m\), take \(Q = \infty\).)
Report \[
\hat C(x) = \big[\hat q_{\mathrm{lo}}(x) - Q,\ \hat q_{\mathrm{hi}}(x) + Q\big]
\] (their equation 7). If the fits were too narrow, \(Q > 0\) and the interval widens; if too wide, \(Q < 0\) and it narrows.
Proof sketch. A new row \((X, Y)\) is inside \(\hat C(X)\) exactly when its own score, \(E = \max\{\hat q_{\mathrm{lo}}(X) - Y,\ Y - \hat q_{\mathrm{hi}}(X)\}\), is at most \(Q\). Suppose all the rows, including the new one, are independent draws from one distribution.2 The fits used neither the calibration rows nor the new row, so given the rows they were fitted on, the \(m + 1\) scores of these rows are independent draws from one distribution too. With no ties, the new score’s rank among them is then equally likely to be any of \(1, \dots, m + 1\), and the new score is at most the \(k\)-th smallest of the other \(m\) exactly when its rank is at most \(k\). So \[
P\big(Y \in \hat C(X)\big) = \frac{k}{m + 1}, \qquad 1 - \alpha \;\le\; \frac{k}{m + 1} \;<\; 1 - \alpha + \frac{1}{m + 1},
\] and with ties the probability is at least \(k/(m + 1)\). This is their Theorem 1: coverage at least \(1 - \alpha\), and at most \(1 - \alpha + 1/(m + 1)\) when the scores are almost surely distinct, as they are when continuous. Nothing is assumed about the quantile fits. A poor fit gives a wide or badly shaped interval, not a wrong overall level. The argument needs fits that did not use the calibration rows in any way, and that includes tuning: if the rows that set \(Q\) also chose the fits’ settings, the setting chosen is one whose scores there happen to be small, and coverage falls below \(1 - \alpha\). In the lecture’s simulation, choosing among 50 settings on 500 calibration rows cost about a percentage point at most; with fewer rows or more candidates it costs more. Use separate rows to fit, tune and calibrate, or tune by cross-validation within the fitting rows.
Scope of the guarantee. First, the probability is over the calibration rows and the new row together. For one fixed calibration set, the coverage of future rows is the chance that a new score is at most that set’s \(Q\). If the rows are independent draws from one distribution and the scores have a continuous distribution, this chance is the \(k\)-th smallest of \(m\) independent uniform draws, which has the \(\mathrm{Beta}(k, m + 1 - k)\) distribution: mean \(k/(m + 1)\), standard deviation about \(\sqrt{\alpha(1 - \alpha)/m}\), 1.3 percentage points when \(m = 500\). Second, the guarantee is marginal. The same \(Q\) is added at every \(x\), so CQR corrects the overall level and not the shape: where the fits are too narrow in one range and too wide in another, the conformalized interval is too.
Conditional coverage as \(n\) grows. If the quantile fits are consistent, approaching the true conditional quantiles as the fitting and calibration sets grow, then the CQR interval approaches \([q_{\alpha/2}(x), q_{1 - \alpha/2}(x)]\) and its coverage given \(X = x\) tends to \(1 - \alpha\), except on a set of \(x\) whose probability tends to zero (Sesia and Candès 2020, Theorem 1 and its corollary, for independent rows and scores with a density bounded away from zero near zero). This does not contradict the impossibility result: consistency is an assumption about the distribution and the method. How fast the fits converge depends on how smooth the quantiles are and on the number of inputs. The same limits apply to checking coverage near \(x\), which needs rows near \(x\): 2,000 fresh rows in 5 bins for each input give 400 rows a bin with one input, 16 with three, under one with five, and with 16 rows the standard error of a bin’s coverage near 90% is 7.5 percentage points.
Split conformal prediction is a special case. If both quantile fits are the same fit of the mean, \(\hat q_{\mathrm{lo}} = \hat q_{\mathrm{hi}} = \hat f\), the score is \(\max\{\hat f(x_i) - y_i,\ y_i - \hat f(x_i)\} = \lvert y_i - \hat f(x_i) \rvert\) and the interval is \(\hat f(x) \pm Q\), the same width at every \(x\) (Lei et al. 2018, section 2.2).
On the simulated data: boosted 5% and 95% fits, with the settings above, on the first 500 training points, and scores on the other 500, so \(m = 500\) and \(k = 451\). The figure shows the scores; the dashed line is \(Q\), and the points above it are the outcomes the interval still misses.
Here \(Q = 0.25\). The two fits cover 92% of their own 500 training points but only 87% of the calibration rows, so CQR widens each end by \(Q\). The scores spread out above zero for \(x\) beyond 6, where the fits are too narrow, and one \(Q\) cannot fix that. On the fresh points, against split conformal prediction around a least squares line fitted and calibrated on the same halves:
Overall, CQR covers 90% of the fresh points and split conformal 87%. Theorem 1 is about the average over calibration sets: for one set of 500, the coverage varies with a standard deviation of about 1.3 percentage points (above), and measuring it on 2,000 fresh points adds a standard error of about 0.7. Split conformal has one width everywhere, so it covers too much where the noise is small and too little where it is large; CQR keeps the shape of its quantile fits, including their error beyond \(x = 6\).
Ways to make an interval
Method
How
Assumes
Can claim
Linear model, normal noise
\(\hat f(x)\) plus or minus a multiple of the estimated noise sd
linear mean, constant variance, normal noise
90% at every \(x\), if the model is right
Mean and variance
a model for the mean, another for the spread
both models right, normal noise
about 90% at every \(x\), if right
Quantile regression
two fits with the pinball loss
the quantile model right
90% at every \(x\) as \(n\) grows, if right
Split conformal prediction
fit \(\hat f\) on part of the data; on the rest, find the residual size \(d\) that 90% of residuals stay within (with a small correction); report \(\hat f(x) \pm d\)
independent rows from one distribution
at least 90% marginally, in finite samples, with any model; the same width at every \(x\)
Conformalized quantile regression
fit two quantiles on part of the data; on the rest, find how far to widen (or narrow) them so that 90% of outcomes fall inside
independent rows from one distribution
at least 90% marginally, in finite samples; widths that follow the quantile fits; 90% at every \(x\) as \(n\) grows, if the fits are consistent
The first three rows rest on a model being right; the two conformal methods (Lei et al. 2018, section 2.2; Romano, Patterson and Candès 2019, Theorem 1) need only independent rows from one distribution, and in return their guarantee is marginal.
Calibration
The same idea for a binary outcome: a stated probability should match a frequency. Of 500 adults given probability \(0.2\) of having diabetes by a model, about 100 should have it. Probabilities are acted on as probabilities: a risk told to a patient, a premium set from an expected cost, a threshold set from the costs of errors. If adults given \(0.2\) in fact have the condition 40% of the time, a threshold of \(0.25\) leaves them unreferred although referring them costs less on average. A score \(\hat p\) is calibrated if \(P\big(Y = 1 \mid \hat p(X)\big) = \hat p(X)\): it conditions on the score’s value, not on \(x\). A reliability diagram checks this on fresh data: sort the units by their score into bins of equal size, and plot each bin’s share of 1s against its average score.
Here the outcome is diabetes, as reported by adults in the NHANES survey (data note; 14% of the training adults). Two scores use nine measurements (age, sex, BMI, pulse, systolic blood pressure, total and HDL cholesterol, the income-to-poverty ratio and physical activity); they are fitted on 4,000 adults and checked on 3,000 others: logistic regression, and boosted trees with xgboost’s defaults (depth 6, learning rate 0.3, 100 iterations). The boosted score is too confident on fresh adults. Checked on the adults who fitted it (grey), it looks too cautious at the top instead, which is why the check needs fresh data.
Show the code
cal_inputs <-c("Age", "male", "BMI", "Pulse", "BPSysAve", "TotChol", "DirectChol", "Poverty", "active")fit_lr <-glm(diabetes ~ Age + male + BMI + Pulse + BPSysAve + TotChol + DirectChol + Poverty + active,family = binomial, data = nh_train)fit_xg <-xgboost(x =as.matrix(nh_train[cal_inputs]), y =factor(nh_train$diabetes), nthread =1)p_lr <-predict(fit_lr, nh_tune, type ="response")p_xg <-predict(fit_xg, as.matrix(nh_tune[cal_inputs]))y_tune <- nh_tune$diabetes# The gap between a group's average score and its share with diabetes, in binomial standard errors.gap_se <-function(g) { i <- nh_tune$Race1 == g; abs(mean(p_lr[i]) -mean(y_tune[i])) /sqrt(mean(y_tune[i]) * (1-mean(y_tune[i])) /sum(i)) }reliability <-function(p, y, bins =10) tibble(p, y) |>mutate(bin =ntile(p, bins)) |>group_by(bin) |>summarise(n =n(), mean_p =mean(p), freq =mean(y), .groups ="drop")rel <-bind_rows(reliability(p_lr, y_tune) |>mutate(score ="logistic regression, tuning adults"),reliability(p_xg, y_tune) |>mutate(score ="boosted trees, tuning adults"),reliability(predict(fit_xg, as.matrix(nh_train[cal_inputs])), nh_train$diabetes) |>mutate(score ="boosted trees, training adults"))if (knitr::is_html_output()) {plot_ly(rel, x =~mean_p, y =~freq, color =~score, colors =c("grey60", v_dark, v_teal), type ="scatter", mode ="lines+markers",text =~n, hovertemplate ="average score %{x:.2f}<br>share with diabetes %{y:.2f}<br>%{text} adults<extra></extra>") |>add_lines(x =c(0, 1), y =c(0, 1), color =I("grey60"), line =list(dash ="dash"), inherit =FALSE,name ="calibrated", hoverinfo ="skip") |>layout(xaxis =list(title ="average score in the bin", range =c(0, 1)),yaxis =list(title ="share with diabetes", range =c(0, 1)),legend =list(x =0.55, y =0.12), height =520, width =640)} else {# The static version, for print.ggplot(rel, aes(mean_p, freq, colour = score)) +geom_abline(linetype ="dashed", colour ="grey60") +geom_line() +geom_point(size =2) +scale_colour_manual(values =c(`boosted trees, training adults`="grey60", `boosted trees, tuning adults`= v_dark,`logistic regression, tuning adults`= v_teal), name =NULL) +coord_equal(xlim =c(0, 1), ylim =c(0, 1)) +labs(x ="average score in the bin", y ="share with diabetes") +theme_minimal(base_size =12) +theme(legend.position ="right")}
Calibration and sharpness. The base rate, \(\hat p(x) = 0.14\) for every adult, is calibrated, and it does not separate those with diabetes from the rest at all. A useful score is calibrated and also sharp, with values near 0 and 1 where it can; Gneiting, Balabdaoui and Raftery (2007) make this principle precise for forecasts of a continuous outcome: as sharp as possible, subject to calibration.
Calibration and the threshold. If \(\hat p\) is calibrated, the optimal threshold theorem applies with \(\hat p(X)\) as the input: when a false positive costs \(c_{FP}\) and a false negative \(c_{FN}\), predicting 1 when \(\hat p(x) > c_{FP}/(c_{FP} + c_{FN})\) is optimal among rules based on that score. It need not be optimal among rules that use all of \(x\). Without calibration, that threshold need not be the optimal cut on \(\hat p\): a miscalibrated score can still give the right decisions (with \(p\) the true class probability, \(\hat p = 0.25 + 0.5p\) does at the threshold \(0.5\)), but in general it does not.
Recalibration. A score can be repaired on rows not used to fit it. One method: a logistic regression of the label on \(\mathrm{logit}\,\hat p = \log\frac{\hat p}{1 - \hat p}\), giving \(\tilde p = 1/(1 + e^{-(a + b\,\mathrm{logit}\,\hat p)})\). For \(b > 0\) the map from \(\hat p\) to \(\tilde p\) is increasing, so the new score ranks the adults as the old one did (its AUC is unchanged), with new probabilities. Fitted on the first 1,500 tuning adults and checked on the other 1,500:
Show the code
logit_p <-function(p) qlogis(pmin(pmax(p, 1e-4), 1-1e-4))half_a <-1:1500; half_b <-1501:3000recal <-glm(y ~ s, family = binomial, data =tibble(y = y_tune[half_a], s =logit_p(p_xg[half_a])))p_recal <-predict(recal, tibble(s =logit_p(p_xg[half_b])), type ="response")logloss <-function(p, y) -mean(y *log(p) + (1- y) *log(1- p))tibble(``=c("boosted trees", "recalibrated"),`log loss on the other 1,500 adults`=c(logloss(p_xg[half_b], y_tune[half_b]), logloss(p_recal, y_tune[half_b]))) |> knitr::kable(digits =3)
log loss on the other 1,500 adults
boosted trees
0.375
recalibrated
0.329
The fitted slope is \(b = 0.39\): two adults whose boosted log-odds differ by 1 differ by 0.39 after recalibration, in the same order. Van Calster et al. (2019) describe the same checks and repairs for risk models in medicine, where a miscalibrated risk can change a treatment decision.
Calibration within groups. A score can be right on average and still too high for one group and too low for another, with the errors cancelling. Used with one threshold for everyone, such a score refers the first group for tests more often, and the second less often, than their risk warrants: it discriminates, even when group membership is not one of its inputs. Calibration within groups is one fairness criterion among several, and they conflict. Kleinberg, Mullainathan and Raghavan (2017) show that when the groups’ base rates differ, a score that is calibrated within groups cannot also be balanced, meaning that its average is the same in each group among those with the outcome, and the same in each group among those without, unless it predicts perfectly. For a rule that thresholds a score, Chouldechova (2017) shows that with different base rates, equal positive predictive values across groups rule out equal false positive and false negative rates (for a rule whose positive predictive value is strictly between 0 and 1). Multicalibration (Hébert-Johnson, Kim, Reingold and Rothblum 2018, definition 2.6) asks for calibration within every group in a collection named in advance: within each group, among the units with score near \(v\), the share of 1s should be within a tolerance of \(v\), for every \(v\). Their algorithm (section 3.2) repeatedly finds a group and a range of scores where the average score and the share of 1s differ by more than the tolerance, and shifts the scores there by the difference. The groups must be large enough to check, and a group not in the collection gets no guarantee. On these data the logistic score above, which leaves race and ethnicity out, is right on average on the tuning adults (an average score of 14.1% against 13.7% with diabetes), but for White adults it averages 14.8% against 10.6% with diabetes, a gap of about 5 standard errors; for the survey’s other groups the gaps are within about two standard errors. Matching averages, overall or in a group, would not show calibration: errors at different scores can cancel, which is why multicalibration asks for calibration at every range of scores within each group. In the lecture, shifts learned on the tuning adults shrink the gaps for White and Black adults on the test adults and widen the gap for Mexican American adults: with a few hundred adults in a cell, the shifts partly fit noise. Applying them also needs each person’s group when the score is used.
Further reading
Barber, R. F., Candès, E. J., Ramdas, A. and Tibshirani, R. J. (2021). The limits of distribution-free conditional predictive inference. Information and Inference: A Journal of the IMA 10(2), 455–482. doi:10.1093/imaiai/iaaa017. Section 1 defines marginal and conditional coverage; Proposition 2.2 is the impossibility.
Chouldechova, A. (2017). Fair prediction with disparate impact: a study of bias in recidivism prediction instruments. Big Data 5(2), 153–163. doi:10.1089/big.2016.0047. Equal positive predictive values and equal error rates cannot hold together when base rates differ.
Gneiting, T., Balabdaoui, F. and Raftery, A. E. (2007). Probabilistic forecasts, calibration and sharpness. Journal of the Royal Statistical Society: Series B 69(2), 243–268. doi:10.1111/j.1467-9868.2007.00587.x. The principle of a sharp forecast subject to calibration, for forecasts that are whole distributions.
Hébert-Johnson, Ú., Kim, M. P., Reingold, O. and Rothblum, G. N. (2018). Multicalibration: calibration for the (computationally-identifiable) masses. Proceedings of the 35th International Conference on Machine Learning, PMLR 80, 1939–1948. proceedings.mlr.press/v80/hebert-johnson18a.html. Definition 2.6 and the algorithm of section 3.2 (numbered as in the arXiv version, 1711.08513).
James, G., Witten, D., Hastie, T. and Tibshirani, R. (2021). An Introduction to Statistical Learning with Applications in R, 2nd edition. Springer. Section 3.2.2, its last question, on predictions: confidence against prediction intervals for a linear model. statlearning.com
Kleinberg, J., Mullainathan, S. and Raghavan, M. (2017). Inherent trade-offs in the fair determination of risk scores. 8th Innovations in Theoretical Computer Science Conference (ITCS 2017), LIPIcs 67, 43:1–43:23. doi:10.4230/LIPIcs.ITCS.2017.43. Calibration within groups and balance conditions on the scores, compatible only with perfect prediction or equal base rates.
Lei, J., G’Sell, M., Rinaldo, A., Tibshirani, R. J. and Wasserman, L. (2018). Distribution-free predictive inference for regression. Journal of the American Statistical Association 113(523), 1094–1111. doi:10.1080/01621459.2017.1307116. Section 2.2, split conformal prediction.
National Center for Health Statistics, National Health and Nutrition Examination Survey, 2009–2012, as shipped in the R package NHANES: Pruim, R., NHANES: Data from the US National Health and Nutrition Examination Study, version 2.1.4, CRAN. The calibration examples; data note.
Romano, Y., Patterson, E. and Candès, E. J. (2019). Conformalized quantile regression. Advances in Neural Information Processing Systems 32, 3543–3553. NeurIPS proceedings. Section 4, equations 6 to 8 and Theorem 1: the method above.
Sesia, M. and Candès, E. J. (2020). A comparison of some conformal quantile regression methods. Stat 9(1), e261. doi:10.1002/sta4.261. Theorem 1 and its corollary (numbered as in arXiv:1909.05433): asymptotic conditional coverage of CQR when the quantile fits are consistent.
Van Calster, B., McLernon, D. J., van Smeden, M., Wynants, L. and Steyerberg, E. W. (2019). Calibration: the Achilles heel of predictive analytics. BMC Medicine 17, article 230. doi:10.1186/s12916-019-1466-7. Levels of calibration, how to check them, and an example of two heart-disease risk models in which the one with the slightly higher AUC overestimated risk and, at a 20% threshold, flagged about twice as many men.
Footnotes
Their statement is about every \(x\) that is not an atom of the inputs’ distribution, a value with positive probability; continuous inputs have none.↩︎
Romano, Patterson and Candès, and Lei et al., state their results for exchangeable rows, a weaker condition: the joint distribution of the rows is unchanged when they are reordered. Independent draws from one distribution are exchangeable; draws without replacement from a finite population are exchangeable but not independent. The argument here uses only exchangeability. The Beta distribution in the next paragraph uses independence.↩︎