Algorithm Search⌘K

Algorithmadvanced

BCa bootstrap interval

Also called bias-corrected and accelerated interval, BCa interval.

Efron's bootstrap interval that shifts the percentiles by a bias correction and an acceleration from the jackknife. It is second-order accurate.

Time
Θ(b n + n^2 + b log b) worstΘ(b n + n^2) best
Space
Θ(b + n) extra
Where
b = the number of bootstrap replicates; n = the sample size
Properties
randomizednot exactofflinerandomizediterative
Origin
Bradley Efron, 1987

The BCa (bias-corrected and accelerated) interval is a percentile interval taken at adjusted levels. Instead of the α/2\alpha/2 and 1−α/21 - \alpha/2 quantiles of the bootstrap replicates, it uses the levels α1\alpha_1 and α2\alpha_2 computed from a bias correction z0z_0, measured by the fraction of replicates below the estimate, and an acceleration aa, measured by the skewness of the jackknife values. It keeps the simplicity and the range of the percentile interval, it respects monotone transformations when aa is fixed, and Hall (1988) showed that its one-sided coverage error is of order n−1n^{-1}. That accuracy is asymptotic: the coverages on this page are measured, not proved.

In plain words

The percentile interval cuts off the same share of bootstrap values at each end. That is right only when the bootstrap values are centred on the estimate and spread out the same way on both sides. The BCa interval checks two things. First, are more than half of the bootstrap values below the estimate? If so, the bootstrap distribution sits too low, and both cut points move up. Second, does the spread of the estimate grow with its size, which shows as skewness when you leave out one data point at a time? If so, the cut points move further toward the long tail. The result is still two of the sorted bootstrap values, chosen with more care.

The problem

Input. A sample x1,…,xnx_1, \ldots, x_n, independent and identically distributed from an unknown FF; a statistic ss with θ^=s(x)\hat\theta = s(x), which estimates θ=t(F)\theta = t(F); a level α∈(0,1)\alpha \in (0, 1); and a number of replicates bb.

Output. An interval [L,U][L, U] that should contain θ\theta with probability close to 1−α1 - \alpha.

Definition. Let GG be the bootstrap distribution function of θ^∗\hat\theta^*, Φ\Phi the standard normal distribution function and zp=Φ−1(p)z_p = \Phi^{-1}(p). With

z0=Φ−1(G(θ^−)),a=∑idi36(∑idi2)3/2,di=θ^(⋅)−θ^(i),z_0 = \Phi^{-1}\bigl(G(\hat\theta^-)\bigr), \qquad a = \frac{\sum_i d_i^3}{6 \bigl(\sum_i d_i^2\bigr)^{3/2}}, \qquad d_i = \hat\theta_{(\cdot)} - \hat\theta_{(i)},

where G(θ^−)=P∗(θ^∗<θ^)G(\hat\theta^-) = P^*(\hat\theta^* < \hat\theta), θ^(i)\hat\theta_{(i)} is the estimate without xix_i and θ^(⋅)\hat\theta_{(\cdot)} is their mean, the adjusted levels are

α1=Φ(z0+z0+zα/21−a(z0+zα/2)),α2=Φ(z0+z0+z1−α/21−a(z0+z1−α/2)),\alpha_1 = \Phi\Bigl(z_0 + \frac{z_0 + z_{\alpha/2}}{1 - a (z_0 + z_{\alpha/2})}\Bigr), \qquad \alpha_2 = \Phi\Bigl(z_0 + \frac{z_0 + z_{1-\alpha/2}}{1 - a (z_0 + z_{1-\alpha/2})}\Bigr),

and the BCa interval is [G−1(α1),G−1(α2)][G^{-1}(\alpha_1), G^{-1}(\alpha_2)]. With z0=0z_0 = 0 and a=0a = 0 the levels are α/2\alpha/2 and 1−α/21 - \alpha/2, and it is the percentile interval.

The algorithm

  1. BCA-INTERVAL(x_1, ..., x_n, s, α, b)
  2. 1θ̂ ← s(x_1, ..., x_n)
  3. 2for j ← 1 to b do
  4. 3x* ← n independent draws from x_1 .. x_n, each with probability 1/n
  5. 4θ*_j ← s(x*)
  6. 5sort the θ*_j; c ← #{j : θ*_j < θ̂}
  7. 6z_0 ← Φ⁻¹(c / b)
  8. 7a ← Σ d_i³ / (6 (Σ d_i²)^{3/2}) with d_i = θ̂_(·) - θ̂_(i), from the n leave-one-out estimates
  9. 8α_1, α_2 ← Φ(z_0 + (z_0 + z)/(1 - a (z_0 + z))) for z = z_{α/2} and z = z_{1-α/2}
  10. 9return [θ*_(⌈b α_1⌉), θ*_(⌈b α_2⌉)]

Line L6 needs 0<c<b0 < c < b; if every replicate lies on one side of θ^\hat\theta, z0z_0 is infinite and the implementation raises an error. Line L8 needs 1−a(z0+z)>01 - a(z_0 + z) > 0; otherwise the formula breaks down and the implementation raises an error. Line L9 uses the quantile rule of the percentile interval, G^b−1(p)=θ(⌈bp⌉)∗\hat G_b^{-1}(p) = \theta^*_{(\lceil b p \rceil)}. The implementation also accepts a fixed value of aa in place of line L7.

Example

Take the right-skewed sample of n=10n = 10 values

0.4, 0.9, 1.3, 1.6, 2.2, 2.8, 3.5, 4.9, 7.6, 13.1,0.4,\ 0.9,\ 1.3,\ 1.6,\ 2.2,\ 2.8,\ 3.5,\ 4.9,\ 7.6,\ 13.1,

with xˉ=3.83\bar x = 3.83, the statistic the mean, α=0.05\alpha = 0.05, b=2000b = 2000 and random.Random(1).

  1. Lines L2 to L5: 1087 of the 2000 replicates are below 3.83, so z0=Φ−1(0.5435)=0.109z_0 = \Phi^{-1}(0.5435) = 0.109. The bootstrap distribution of the mean has its median below xˉ\bar x, because the distribution is skewed to the right.
  2. Line L7: for the mean, di=(xi−xˉ)/(n−1)d_i = (x_i - \bar x)/(n - 1), so aa is the plug-in skewness divided by 6n6\sqrt n. Here the skewness is 1.4881.488 and a=1.488/(610)=0.0784a = 1.488/(6\sqrt{10}) = 0.0784.
  3. Line L8: α1=Φ(0.109+(−1.851)/1.145)=Φ(−1.507)=0.0659\alpha_1 = \Phi(0.109 + (-1.851)/1.145) = \Phi(-1.507) = 0.0659 and α2=Φ(0.109+2.069/0.838)=Φ(2.579)=0.9950\alpha_2 = \Phi(0.109 + 2.069/0.838) = \Phi(2.579) = 0.9950.
  4. Line L9: ⌈2000⋅0.0659⌉=132\lceil 2000 \cdot 0.0659 \rceil = 132 and ⌈2000⋅0.9950⌉=1991\lceil 2000 \cdot 0.9950 \rceil = 1991. The 132nd and the 1991st smallest replicates are 2.18 and 6.97.

So the interval is [2.18,6.97][2.18, 6.97]. Both levels moved up from 0.0250.025 and 0.9750.975, and the interval moved right of the percentile interval [1.80,6.31][1.80, 6.31]. With a=0a = 0 (the bias-corrected interval) the same replicates give [2.00,6.53][2.00, 6.53]. The bootstrap-t interval is [1.82,10.27][1.82, 10.27] and the t interval [1.04,6.62][1.04, 6.62].

Transformation. With aa fixed, the BCa interval for log⁡θ\log\theta is the log of the interval for θ\theta; the tests check this exactly. With the jackknife estimate of aa, it is not: on the log scale, line L7 gives a=0.0875a = 0.0875 instead of 0.07840.0784, and the interval, transformed back, is [2.19,6.99][2.19, 6.99]. The value z0=0.109z_0 = 0.109 is the same on both scales.

Measured coverage. For samples from the exponential law with mean 1, 1000 data sets of each size with b=1000b = 1000 (seeds 101 and 102) gave these coverages for the true mean at the nominal level 0.95:

method n=10n = 10 n=20n = 20
BCa 0.884 0.916
percentile 0.869 0.911
bootstrap-t 0.943 0.950
t interval 0.911 0.924

The study used the formula a=skewness/(6n)a = \text{skewness}/(6\sqrt n), which is the jackknife value for the mean. The BCa interval improves on the percentile interval and is better balanced than the t interval, with misses of 8.4%8.4\% below and 3.2%3.2\% above at n=10n = 10. But for the mean of a small skewed sample it is still too short, because the bootstrap distribution of the mean has the plug-in variance and normal-like tails. Second-order accuracy is a statement about large nn. The Monte Carlo standard error of each coverage is about 0.0070.007.

Correctness

The proof is in proofs/correctness.md. What is proved:

  • Lines L5 to L9 compute the stated formulas, and with z0=a=0z_0 = a = 0 the algorithm is the percentile interval.
  • z0z_0 does not change under a strictly increasing transformation of the statistic. With aa fixed, the interval respects such transformations. The jackknife value of aa does change, so the full algorithm respects them only approximately.
  • In Efron's transformation model, where an increasing ϕ\phi makes ϕ(θ^)=ϕ(θ)+(1+aϕ(θ))(Z−z0)\phi(\hat\theta) = \phi(\theta) + (1 + a\phi(\theta))(Z - z_0) with ZZ standard normal, and the bootstrap follows the same model, the ideal BCa interval with the true z0z_0 and aa has coverage 1−α1 - \alpha, exactly when a=0a = 0 and up to an error below Φ(−1/∣a∣+∣z0∣)\Phi(-1/\lvert a \rvert + \lvert z_0 \rvert) otherwise.

What is not proved: the coverage for a general FF. Hall (1988) shows by Edgeworth expansions that the one-sided coverage error is O(n−1)O(n^{-1}) under smoothness conditions; the table above is a measurement.

Proof: The BCa interval computes Efron's adjusted percentiles and is exact in his transformation modelfull

We use the pseudocode and the notation of the page. GG is the bootstrap distribution function of θ^∗\hat\theta^*, G^b\hat G_b the empirical distribution function of the bb replicates, Φ\Phi the standard normal distribution function and zp=Φ−1(p)z_p = \Phi^{-1}(p). For any distribution function KK, K−1(p)=inf⁡{t:K(t)≥p}K^{-1}(p) = \inf\{t : K(t) \ge p\}.

This file proves what the algorithm computes, two invariance facts, and exact coverage in an idealized model. It does not prove a coverage level for a general FF; that coverage is measured on the page.

Claim 1 (the algorithm computes the formulas). Line L6 sets z0=Φ−1(G^b(θ^−))z_0 = \Phi^{-1}(\hat G_b(\hat\theta^-)), where G^b(θ^−)=c/b\hat G_b(\hat\theta^-) = c/b is the fraction of replicates below θ^\hat\theta. Line L9 returns [G^b−1(α1),G^b−1(α2)][\hat G_b^{-1}(\alpha_1), \hat G_b^{-1}(\alpha_2)]. If z0=0z_0 = 0 and a=0a = 0, then α1=α/2\alpha_1 = \alpha/2 and α2=1−α/2\alpha_2 = 1 - \alpha/2, and the result is the percentile interval computed from the same replicates.

Proof. The first statement is the definition of cc. For the second, α1,α2∈(0,1)\alpha_1, \alpha_2 \in (0, 1) because they are values of Φ\Phi, and the quantile rule of the percentile interval (its Claim 1) shows that θ(⌈bp⌉)∗=G^b−1(p)\theta^*_{(\lceil b p \rceil)} = \hat G_b^{-1}(p) for 0<p<10 < p < 1. For the third, put z0=a=0z_0 = a = 0 in line L8: α1=Φ(zα/2)=α/2\alpha_1 = \Phi(z_{\alpha/2}) = \alpha/2 and α2=Φ(z1−α/2)=1−α/2\alpha_2 = \Phi(z_{1-\alpha/2}) = 1 - \alpha/2. □\square

Claim 2 (z0 is invariant). Let gg be strictly increasing on a set that contains every value of ss. If the algorithm runs on the statistic g∘sg \circ s with the same random numbers, line L6 gives the same z0z_0.

Proof. Lines L2 to L4 draw the indices without looking at the statistic, so the replicates of the second run are g(θj∗)g(\theta^*_j), and its estimate is g(θ^)g(\hat\theta). Since gg is strictly increasing, g(θj∗)<g(θ^)g(\theta^*_j) < g(\hat\theta) exactly when θj∗<θ^\theta^*_j < \hat\theta, so cc is the same. □\square

Claim 3 (transformation respecting for a fixed a). Under the conditions of Claim 2, and with the same fixed value of aa in both runs, if the first run returns [L,U][L, U] the second returns [g(L),g(U)][g(L), g(U)].

Proof. By Claim 2, z0z_0 is the same, and aa and α\alpha are the same, so line L8 gives the same α1\alpha_1 and α2\alpha_2, and line L9 uses the same ranks ⌈bα1⌉\lceil b\alpha_1 \rceil and ⌈bα2⌉\lceil b\alpha_2 \rceil. A strictly increasing gg keeps the order of the replicates, so the replicate of each rank in the second run is gg of the replicate of that rank in the first run. □\square

The jackknife value of line L7 is a function of the leave-one-out estimates θ^(i)\hat\theta_{(i)}, and gg changes their spacings: g(θ^(⋅))g(\hat\theta_{(\cdot)}) is not the mean of the g(θ^(i))g(\hat\theta_{(i)}), and the skewness of the differences changes. So the full algorithm respects transformations only approximately. On the page, aa is 0.07840.0784 for the mean and 0.08750.0875 for the log of the mean. The tests check both facts: exact equality with a fixed aa, and a different jackknife aa after the logarithm.

Claim 4 (exact coverage in the transformation model). Suppose there are numbers z0z_0 and aa and a strictly increasing bijection ϕ\phi from the parameter range onto R\mathbb{R} such that, with ψ=ϕ(θ)\psi = \phi(\theta), ψ^=ϕ(θ^)\hat\psi = \phi(\hat\theta) and ZZ standard normal,

ψ^=ψ+(1+aψ)(Z−z0),1+aψ>0,\hat\psi = \psi + (1 + a\psi)(Z - z_0), \qquad 1 + a\psi > 0,

and the bootstrap follows the same model with ψ^\hat\psi in place of ψ\psi: ϕ(θ^∗)=ψ^+(1+aψ^)(Z∗−z0)\phi(\hat\theta^*) = \hat\psi + (1 + a\hat\psi)(Z^* - z_0) with Z∗Z^* standard normal under P∗P^*. Let EE be the event 1+a(Z−z0)>01 + a(Z - z_0) > 0, and suppose 1−a(z0+z)>01 - a(z_0 + z) > 0 for z=zα/2z = z_{\alpha/2} and z=z1−α/2z = z_{1-\alpha/2}. Then on EE the ideal interval [G−1(α1),G−1(α2)][G^{-1}(\alpha_1), G^{-1}(\alpha_2)] is defined, and

∣P(G−1(α1)≤θ≤G−1(α2))−(1−α)∣≤P(Ec).\bigl\lvert P\bigl(G^{-1}(\alpha_1) \le \theta \le G^{-1}(\alpha_2)\bigr) - (1 - \alpha) \bigr\rvert \le P(E^c).

If a=0a = 0, EE is the whole space and the coverage is exactly 1−α1 - \alpha.

Proof. From the model, 1+aψ^=(1+aψ)+a(1+aψ)(Z−z0)=(1+aψ)(1+a(Z−z0))1 + a\hat\psi = (1 + a\psi) + a(1 + a\psi)(Z - z_0) = (1 + a\psi)\bigl(1 + a(Z - z_0)\bigr), which is positive exactly on EE. On EE the bootstrap law is

G(t)=P∗(ϕ(θ^∗)≤ϕ(t))=Φ(ϕ(t)−ψ^1+aψ^+z0),G(t) = P^*\bigl(\phi(\hat\theta^*) \le \phi(t)\bigr) = \Phi\Bigl(\frac{\phi(t) - \hat\psi}{1 + a\hat\psi} + z_0\Bigr),

which is continuous and strictly increasing with range (0,1)(0, 1). In particular G(θ^)=Φ(z0)G(\hat\theta) = \Phi(z_0), so the ideal value of line L6 is the true z0z_0.

Fix z∈{zα/2,z1−α/2}z \in \{z_{\alpha/2}, z_{1-\alpha/2}\}, let w=z0+zw = z_0 + z and p=Φ(z0+w/(1−aw))p = \Phi(z_0 + w/(1 - a w)), which is α1\alpha_1 or α2\alpha_2. Solving G(t)=pG(t) = p gives the endpoint tz=G−1(p)t_z = G^{-1}(p) with

ϕ(tz)=ψ^+(1+aψ^)w1−aw,1+aϕ(tz)=1+aψ^1−aw=(1+aψ)(1+a(Z−z0))1−aw.\phi(t_z) = \hat\psi + (1 + a\hat\psi)\frac{w}{1 - a w}, \qquad 1 + a\phi(t_z) = \frac{1 + a\hat\psi}{1 - a w} = \frac{(1 + a\psi)\bigl(1 + a(Z - z_0)\bigr)}{1 - a w}.

Now compare θ\theta with tzt_z, which is the same as comparing ψ\psi with ϕ(tz)\phi(t_z).

  • If a>0a > 0: ψ≤ϕ(tz)\psi \le \phi(t_z) is the same as 1+aψ≤1+aϕ(tz)1 + a\psi \le 1 + a\phi(t_z). Divide by 1+aψ>01 + a\psi > 0 and multiply by 1−aw>01 - a w > 0: this is 1−aw≤1+a(Z−z0)1 - a w \le 1 + a(Z - z_0), that is −az≤aZ-a z \le a Z, that is Z≥−zZ \ge -z.
  • If a<0a < 0: ψ≤ϕ(tz)\psi \le \phi(t_z) is the same as 1+aψ≥1+aϕ(tz)1 + a\psi \ge 1 + a\phi(t_z), which by the same steps is −az≥aZ-a z \ge a Z, that is again Z≥−zZ \ge -z.
  • If a=0a = 0: ϕ(tz)=ψ^+w=ψ+Z−z0+z0+z\phi(t_z) = \hat\psi + w = \psi + Z - z_0 + z_0 + z, so ψ≤ϕ(tz)\psi \le \phi(t_z) is Z≥−zZ \ge -z.

So on EE, θ≤G−1(α2)\theta \le G^{-1}(\alpha_2) exactly when Z≥−z1−α/2=zα/2Z \ge -z_{1-\alpha/2} = z_{\alpha/2}, and θ≥G−1(α1)\theta \ge G^{-1}(\alpha_1) exactly when Z≤−zα/2=z1−α/2Z \le -z_{\alpha/2} = z_{1-\alpha/2}. The coverage event therefore agrees on EE with the event zα/2≤Z≤z1−α/2z_{\alpha/2} \le Z \le z_{1-\alpha/2}, which has probability 1−α1 - \alpha. Two events that agree on EE differ in probability by at most P(Ec)P(E^c). □\square

For a>0a > 0, P(Ec)=Φ(z0−1/a)P(E^c) = \Phi(z_0 - 1/a), and for a<0a < 0 it is Φ(−z0−1/∣a∣)\Phi(-z_0 - 1/\lvert a \rvert); both are at most Φ(∣z0∣−1/∣a∣)\Phi(\lvert z_0 \rvert - 1/\lvert a \rvert). With the values of the page, z0=0.109z_0 = 0.109 and a=0.0784a = 0.0784, this is Φ(−12.6)\Phi(-12.6), which is below 10−3510^{-35}. The model needs the exception because a normal ZZ is unbounded while 1+aψ^1 + a\hat\psi must stay positive.

The method does not need to know ϕ\phi; it uses only GG, z0z_0 and aa. The two inputs are the two departures from Claim 4 of the percentile interval: z0z_0 allows a median bias on the normalized scale, and aa lets the standard deviation 1+aψ1 + a\psi change with the parameter.

What is not proved. For a real FF, the transformation model holds only approximately, the jackknife value of aa is an estimate, and the bootstrap law is discrete. Efron (1987) and Hall (1988) show under smoothness conditions that the one-sided coverage error is O(n−1)O(n^{-1}). This file does not reproduce those expansions. The coverages on the page come from a simulation with stated seeds, with a Monte Carlo standard error of about 0.0070.007.

Cost. Lines L2 to L4 cost Θ(b⋅(n+Cs(n)))\Theta(b \cdot (n + C_s(n))), where Cs(n)C_s(n) is the cost of ss. Line L5 sorts and counts in Θ(blog⁡b)\Theta(b \log b). Line L7 evaluates ss on nn samples of size n−1n - 1, which costs Θ(n Cs(n−1))\Theta(n\, C_s(n - 1)), that is Θ(n2)\Theta(n^2) for a linear-time statistic. Lines L6, L8 and L9 take constant time. The extra space is Θ(b+n)\Theta(b + n).

Complexity

The bb replicates cost Θ(bn)\Theta(b n) for the mean, the sort costs Θ(blog⁡b)\Theta(b \log b), and the counting of line L5 costs Θ(b)\Theta(b). Line L7 computes nn leave-one-out estimates; done naively for a statistic that costs Θ(n)\Theta(n), this is Θ(n2)\Theta(n^2), and for the mean it can be done in Θ(n)\Theta(n) by subtracting each value from the total. Two selections at the levels α1\alpha_1 and α2\alpha_2 can replace the sort. The extra space is Θ(b+n)\Theta(b + n).

Properties

  • Second-order accurate. For smooth statistics, the one-sided coverage error is O(n−1)O(n^{-1}), and the endpoints agree with those of the bootstrap-t interval up to terms of order n−3/2n^{-3/2} (Hall 1988).
  • Transformation respecting for a fixed aa, and approximately so with the jackknife aa, as the example shows.
  • Range preserving. The endpoints are replicate values, as in the percentile interval.
  • No standard error needed. Unlike the bootstrap-t interval, it needs only the statistic itself and its nn leave-one-out values.
  • More replicates. The adjusted levels can be far in the tails, as α2=0.995\alpha_2 = 0.995 in the example, so bb should be at least 1000, and better 2000 or more.

Variants and improvements

  • Bias-corrected (BC) interval. Efron's earlier method sets a=0a = 0. It corrects the median bias but not the change of the standard error with θ\theta, and it is only first-order accurate.
  • Acceleration from influence values. In place of the jackknife, aa can be computed from the empirical influence function values ℓi\ell_i as ∑ℓi3/(6(∑ℓi2)3/2)\sum \ell_i^3 / (6 (\sum \ell_i^2)^{3/2}). For the mean both give skewness/(6n)\text{skewness}/(6\sqrt n).
  • Parametric BCa. With a parametric bootstrap, aa is computed from the score function of the model instead of the jackknife.
  • ABC interval. DiCiccio and Efron's approximate bootstrap confidence interval replaces the resampling by a few numerical derivatives of the statistic. It gives nearly the same endpoints for smooth statistics, without Monte Carlo error.
  • Iterated bootstrap calibration. A second level of bootstrap estimates the actual coverage and adjusts the nominal level. It also gives second-order or better accuracy, at the cost of b2b^2 evaluations.

When to use it

Use it as the default bootstrap interval for a smooth statistic without a reliable standard error formula, such as a correlation, a ratio or a quantile of moderate order, when nn is moderate or large. It needs only the statistic, which you must already compute. For a mean or a regression coefficient in a small skewed sample, the bootstrap-t interval covered better in the study above. For a statistic that is not smooth, such as an extreme order statistic, neither method is valid, and subsampling is the safer tool.

Pitfalls

  • Ties at the estimate. Counting replicates with θj∗≤θ^\theta^*_j \le \hat\theta instead of <θ^< \hat\theta changes z0z_0 when many replicates equal θ^\hat\theta, as for a median. Some software splits the ties in half; state the rule.
  • Extreme levels. If ∣z0∣\lvert z_0 \rvert or ∣a∣\lvert a \rvert is large, α1\alpha_1 or α2\alpha_2 can be very close to 0 or 1, and the endpoint is then an extreme replicate with a large Monte Carlo error. If 1−a(z0+z)≤01 - a(z_0 + z) \le 0, the formula is not defined.
  • Wrong sign of aa. The jackknife differences are di=θ^(⋅)−θ^(i)d_i = \hat\theta_{(\cdot)} - \hat\theta_{(i)}. The reversed sign gives an acceleration with the wrong sign, which moves the interval the wrong way.
  • Small samples. The interval inherits the narrowness of the bootstrap distribution. Second-order accuracy does not mean good coverage at n=10n = 10.
  • Statistics where the bootstrap fails. The correction cannot repair an inconsistent bootstrap, for example for the sample maximum.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

bca_bootstrap_interval.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bca-bootstrap-interval/. The authors are listed in prov/HRG7H4.jsonl.

import math
import random
from fractions import Fraction
from statistics import NormalDist
from typing import Callable, Sequence

Statistic = Callable[[Sequence[float]], float]
STD_NORMAL = NormalDist()


def empirical_quantile(sorted_values: Sequence[float], p: float) -> float:
    """inf{t : G(t) >= p}: the ceil(b p)-th smallest value, or the smallest for p = 0."""
    k = max(1, math.ceil(Fraction(p) * len(sorted_values)))
    return sorted_values[k - 1]


def jackknife_acceleration(x: Sequence[float], statistic: Statistic) -> float:
    """a = sum d_i^3 / (6 (sum d_i^2)^(3/2)) with d_i = theta_(.) - theta_(i)."""
    n = len(x)
    loo = [statistic(list(x[:i]) + list(x[i + 1 :])) for i in range(n)]
    dot = math.fsum(loo) / n
    d = [dot - t for t in loo]
    s2 = math.fsum(v * v for v in d)
    if s2 == 0:
        return 0.0
    return math.fsum(v**3 for v in d) / (6.0 * s2**1.5)


def bca_levels(z0: float, a: float, alpha: float) -> tuple:
    """The adjusted levels alpha_1 and alpha_2 of Efron (1987)."""
    out = []
    for z in (STD_NORMAL.inv_cdf(alpha / 2), STD_NORMAL.inv_cdf(1 - alpha / 2)):
        w = z0 + z
        denom = 1 - a * w
        if denom <= 0:
            raise ValueError("the acceleration is too large for this level")
        out.append(STD_NORMAL.cdf(z0 + w / denom))
    return out[0], out[1]


def bca_interval(
    x: Sequence[float],
    statistic: Statistic,
    alpha: float,
    b: int,
    rng: random.Random,
    acceleration: float | None = None,
) -> tuple:
    """The 1 - alpha BCa interval [G^{-1}(alpha_1), G^{-1}(alpha_2)].

    acceleration=None estimates a by the jackknife; a number fixes it.
    Returns (lo, hi, z0, a).
    """
    if not 0 < alpha < 1:
        raise ValueError("alpha must be in (0, 1)")
    n = len(x)
    if n < 2 or b < 1:
        raise ValueError("need n >= 2 and b >= 1")
    theta_hat = statistic(x)  # @line L1
    reps = []
    for _ in range(b):  # @line L2
        xs = [x[rng.randrange(n)] for _ in range(n)]  # @line L3
        reps.append(statistic(xs))  # @line L4
    reps.sort()
    below = sum(1 for t in reps if t < theta_hat)  # @line L5
    if below == 0 or below == b:
        raise ValueError("all replicates lie on one side of the estimate; z0 is infinite")
    z0 = STD_NORMAL.inv_cdf(below / b)  # @line L6
    a = jackknife_acceleration(x, statistic) if acceleration is None else acceleration  # @line L7
    a1, a2 = bca_levels(z0, a, alpha)  # @line L8
    return empirical_quantile(reps, a1), empirical_quantile(reps, a2), z0, a  # @line L9
test_bca_bootstrap_interval.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bca-bootstrap-interval/. The authors are listed in prov/HRG7H4.jsonl.

import math
import random
import statistics
from statistics import NormalDist

import pytest

from bca_bootstrap_interval import bca_interval, bca_levels, empirical_quantile, jackknife_acceleration

SKEWED = [0.4, 0.9, 1.3, 1.6, 2.2, 2.8, 3.5, 4.9, 7.6, 13.1]


def fmean(xs):
    return math.fsum(xs) / len(xs)


def test_acceleration_of_the_mean_is_skewness_over_6_root_n():
    rng = random.Random(1)
    for n in (3, 5, 10, 40):
        x = [rng.expovariate(1.0) for _ in range(n)]
        m = fmean(x)
        m2 = math.fsum((v - m) ** 2 for v in x) / n
        m3 = math.fsum((v - m) ** 3 for v in x) / n
        skew = m3 / m2**1.5
        assert math.isclose(jackknife_acceleration(x, fmean), skew / (6 * math.sqrt(n)), rel_tol=1e-9)


def test_acceleration_by_definition():
    """Leave-one-out values computed by hand for a tiny sample."""
    x = [1.0, 2.0, 6.0]
    loo = [4.0, 3.5, 1.5]  # means without 1, without 2, without 6
    dot = sum(loo) / 3
    d = [dot - t for t in loo]
    a = sum(v**3 for v in d) / (6 * sum(v * v for v in d) ** 1.5)
    assert math.isclose(jackknife_acceleration(x, fmean), a, rel_tol=1e-12)


def test_levels_reduce_to_percentile():
    a1, a2 = bca_levels(0.0, 0.0, 0.1)
    assert math.isclose(a1, 0.05, rel_tol=1e-12) and math.isclose(a2, 0.95, rel_tol=1e-12)
    a1, a2 = bca_levels(0.2, 0.05, 0.1)
    z = NormalDist().inv_cdf(0.05)
    assert math.isclose(a1, NormalDist().cdf(0.2 + (0.2 + z) / (1 - 0.05 * (0.2 + z))), rel_tol=1e-12)
    assert a1 > 0.05 and a2 > 0.95  # a positive bias correction moves both levels up


def test_transformation_respecting_for_fixed_acceleration():
    lo, hi, z0, a = bca_interval(SKEWED, fmean, 0.1, 999, random.Random(4), acceleration=0.05)
    llo, lhi, lz0, _ = bca_interval(SKEWED, lambda xs: math.log(fmean(xs)), 0.1, 999, random.Random(4), acceleration=0.05)
    assert lz0 == z0
    assert llo == math.log(lo) and lhi == math.log(hi)
    # The jackknife estimate of a is not invariant: it changes under the log.
    a_mean = jackknife_acceleration(SKEWED, fmean)
    a_log = jackknife_acceleration(SKEWED, lambda xs: math.log(fmean(xs)))
    assert abs(a_mean - a_log) > 0.005


def test_infinite_bias_correction_is_an_error():
    with pytest.raises(ValueError):
        bca_interval(SKEWED, min, 0.1, 200, random.Random(1))


def test_page_example():
    lo, hi, z0, a = bca_interval(SKEWED, fmean, 0.05, 2000, random.Random(1))
    m = fmean(SKEWED)
    assert lo < m < hi
    assert z0 > 0 and a > 0  # right skew: more replicates below the mean, positive acceleration


def test_coverage_is_measured_not_proved():
    rng = random.Random(9)
    r, b, alpha = 300, 300, 0.05
    hits = 0
    for _ in range(r):
        x = [rng.expovariate(1.0) for _ in range(20)]
        lo, hi, _, _ = bca_interval(x, fmean, alpha, b, rng)
        hits += lo <= 1.0 <= hi
    cov = hits / r
    assert abs(cov - (1 - alpha)) <= 4 * math.sqrt(alpha * (1 - alpha) / r) + 0.04


def test_quantile_and_errors():
    assert empirical_quantile([1.0, 2.0, 3.0], 0.34) == 2.0
    assert empirical_quantile([1.0, 2.0, 3.0], 0.33) == 1.0
    with pytest.raises(ValueError):
        bca_interval([1.0], fmean, 0.1, 10, random.Random(1))
    with pytest.raises(ValueError):
        bca_interval(SKEWED, fmean, 0.0, 10, random.Random(1))

History

Bradley Efron proposed the percentile interval with the bootstrap and, in 1981 and 1982, the bias-corrected interval, which adds z0z_0. In Better bootstrap confidence intervals (JASA, 1987) he added the acceleration aa, derived the interval from a transformation model in which the standard deviation of the normalized estimate changes linearly with the parameter, and gave the jackknife estimate of aa. Peter Hall's 1988 paper, which used Edgeworth expansions, showed that BCa and the bootstrap-t interval are both second-order accurate, while the percentile and BC intervals are first-order accurate. DiCiccio and Efron later developed the ABC approximation and reviewed the methods.

References

  1. Bradley Efron, Better bootstrap confidence intervals, Journal of the American Statistical Association 82(397), 1987, pp. 171 to 185 (the BCa method, the transformation model with bias z0 and acceleration a, and the jackknife estimate of a)
  2. Bradley Efron and Robert J. Tibshirani, An Introduction to the Bootstrap, Chapman and Hall, 1993, Chapter 14 (better bootstrap confidence intervals, the BCa method and its formulas) and Chapter 22 (justification of the method)
  3. Peter Hall, Theoretical comparison of bootstrap confidence intervals, The Annals of Statistics 16(3), 1988, pp. 927 to 953 (the BCa interval is second-order accurate and second-order correct)
  4. A. C. Davison and D. V. Hinkley, Bootstrap Methods and their Application, Cambridge University Press, 1997, Chapter 5 (the adjusted percentile method, BCa, and its estimate of a by empirical influence values)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example