Algorithm Search⌘K

Algorithmcore

Jackknife

Also called Quenouille-Tukey jackknife, leave-one-out jackknife.

Recompute a statistic with each observation left out in turn, and combine the n values to estimate its bias and variance. It fails for nonsmooth statistics like the median.

Time
Θ(n^2) worstΘ(n) best
Space
Θ(n) extra
Where
n = the sample size
Properties
deterministicnot exactofflinenot randomizediterative
Origin
Maurice Quenouille, John Tukey, 1949

The jackknife computes a statistic nn more times, each time with one observation left out, and uses the spread of these nn values to estimate the bias and the standard error of the statistic. It needs no model and no random numbers, and it costs nn evaluations of the statistic. It is exact for the mean and for the plug-in variance, it removes the 1/n1/n term of the bias of smooth statistics, and it turns a V-statistic into the corresponding U-statistic. It fails for statistics that are not smooth, such as the median, where its variance estimate does not converge.

In plain words

You have a statistic, such as an average or a correlation, from nn data points, and you want to know how much it would change with other data. Leave out the first point and compute the statistic again. Put it back, leave out the second point, and compute again. Do this for every point. If the nn results are close together, the statistic is stable. If they spread out, it is not. A fixed formula turns this spread into a standard error and turns the average shift into an estimate of the bias.

The method works well for statistics that change smoothly when one point moves. It works badly for the median, which jumps between only two or three values when one point is left out.

The problem

Input. A sample x1,…,xnx_1, \ldots, x_n, independent and identically distributed, with n≥2n \ge 2, and a statistic ss that is defined for samples of size nn and n−1n - 1 and does not depend on the order of the data. Write θ^=s(x1,…,xn)\hat\theta = s(x_1, \ldots, x_n).

Output. An estimate of the bias Eθ^−θE\hat\theta - \theta, the bias-corrected estimate, and an estimate of the variance of θ^\hat\theta.

Definitions. Let θ^(i)\hat\theta_{(i)} be ss on the sample without xix_i, and θ^(⋅)=1n∑iθ^(i)\hat\theta_{(\cdot)} = \frac{1}{n}\sum_i \hat\theta_{(i)}. Then

bias^jack=(n−1)(θ^(⋅)−θ^),θ^jack=θ^−bias^jack=nθ^−(n−1)θ^(⋅),\widehat{\mathrm{bias}}_{jack} = (n - 1)(\hat\theta_{(\cdot)} - \hat\theta), \qquad \hat\theta_{jack} = \hat\theta - \widehat{\mathrm{bias}}_{jack} = n\hat\theta - (n - 1)\hat\theta_{(\cdot)},
var^jack=n−1n∑i=1n(θ^(i)−θ^(⋅))2.\widehat{\mathrm{var}}_{jack} = \frac{n - 1}{n} \sum_{i=1}^n \bigl(\hat\theta_{(i)} - \hat\theta_{(\cdot)}\bigr)^2.

The factor n−1n - 1 in both formulas makes them exact for the mean. Pseudo-values θ~i=nθ^−(n−1)θ^(i)\tilde\theta_i = n\hat\theta - (n - 1)\hat\theta_{(i)} give the same results: θ^jack\hat\theta_{jack} is their mean, and var^jack\widehat{\mathrm{var}}_{jack} is their sample variance divided by nn, as if they were nn independent observations.

The algorithm

  1. JACKKNIFE(x_1, ..., x_n, s)
  2. 1θ̂ ← s(x_1, ..., x_n)
  3. 2for i ← 1 to n do
  4. 3θ̂_(i) ← s(x_1, ..., x_{i-1}, x_{i+1}, ..., x_n)
  5. 4θ̂_(·) ← (1/n) Σ_i θ̂_(i)
  6. 5bias ← (n - 1) (θ̂_(·) - θ̂)
  7. 6var ← ((n - 1)/n) Σ_i (θ̂_(i) - θ̂_(·))²
  8. 7return θ̂ - bias, bias, var

The implementation uses only addition, subtraction, multiplication and division, so with Fraction data it computes every quantity exactly. This is how the tests check the identities below.

Example

The treatment group of the mouse data of Efron and Tibshirani (Table 2.1) has n=7n = 7 survival times

94, 197, 16, 38, 99, 141, 23.94,\ 197,\ 16,\ 38,\ 99,\ 141,\ 23.

Mean. θ^=86.86\hat\theta = 86.86. Leaving out each value in turn gives 85.67,68.50,98.67,95.00,84.83,77.83,97.5085.67, 68.50, 98.67, 95.00, 84.83, 77.83, 97.50, whose mean is again 86.8686.86, so the bias estimate is 0. Line L6 gives 636.83636.83, and the jackknife standard error is 636.83=25.24\sqrt{636.83} = 25.24, which is exactly S/7S/\sqrt 7. The exact bootstrap standard error is 23.36=6/7⋅25.2423.36 = \sqrt{6/7} \cdot 25.24; the bootstrap uses the plug-in variance with divisor nn.

Plug-in variance. θ^=17∑(xi−xˉ)2=3820.98\hat\theta = \frac{1}{7}\sum(x_i - \bar x)^2 = 3820.98. The bias estimate is −636.83=−S2/7-636.83 = -S^2/7, and the corrected value is 4457.81=S24457.81 = S^2, the unbiased sample variance.

Median. θ^=94\hat\theta = 94. The seven leave-one-out medians take only three values: 96.596.5 three times, 6666 three times and 68.568.5 once. The jackknife standard error is 36.2736.27, close to the bootstrap value 37.8337.83 by chance. The bias estimate is −87.4-87.4, and the "corrected" median is 181.4181.4, larger than every value but one. Do not use the jackknife for the median.

Measured failure for the median. For 2000 uniform samples of each size, the ratio of the jackknife variance of the median to its true variance had these summaries (seed 11):

nn mean ratio median ratio ratio below 0.5
10 1.62 0.48 51%
40 1.79 0.47 51%
160 1.96 0.49 51%

The ratio does not concentrate at 1 as nn grows. It converges in law to (χ22/2)2(\chi^2_2/2)^2, which has mean 2 and median (ln⁡2)2=0.48(\ln 2)^2 = 0.48 (Efron and Tibshirani, Chapter 11).

Correctness

The proof is in proofs/correctness.md. It shows these facts, all exact:

  • For the mean, the bias estimate is 0 and var^jack=S2/n\widehat{\mathrm{var}}_{jack} = S^2/n, with S2S^2 the sample variance with divisor n−1n - 1.
  • If Eθ^n=θ+a1/n+a2/n2E\hat\theta_n = \theta + a_1/n + a_2/n^2 for every nn, then Eθ^jack=θ−a2/(n(n−1))E\hat\theta_{jack} = \theta - a_2/(n(n-1)). The 1/n1/n term of the bias is removed completely.
  • For every symmetric kernel hh of degree 2, the jackknife-corrected V-statistic 1n2∑i,jh(xi,xj)\frac{1}{n^2}\sum_{i,j} h(x_i, x_j) equals the U-statistic (n2)−1∑i<jh(xi,xj)\binom{n}{2}^{-1}\sum_{i<j} h(x_i, x_j). With h(x,y)=(x−y)2/2h(x, y) = (x - y)^2/2 this turns the plug-in variance into S2S^2.
  • The pseudo-value form gives the same estimate and variance.
  • For the median with n=2mn = 2m, var^jack=n−14(x(m+1)−x(m))2\widehat{\mathrm{var}}_{jack} = \frac{n - 1}{4}(x_{(m+1)} - x_{(m)})^2, a function of a single spacing.

The tests check each identity with Fraction data, and check the U-statistic against its definition as a sum over all pairs.

Proof: Exact identities of the jackknifefull

We use the pseudocode and the notation of the page: θ^(i)\hat\theta_{(i)} is the statistic without xix_i, θ^(⋅)\hat\theta_{(\cdot)} their mean, θ^jack=nθ^−(n−1)θ^(⋅)\hat\theta_{jack} = n\hat\theta - (n - 1)\hat\theta_{(\cdot)} and var^jack=n−1n∑i(θ^(i)−θ^(⋅))2\widehat{\mathrm{var}}_{jack} = \frac{n-1}{n}\sum_i (\hat\theta_{(i)} - \hat\theta_{(\cdot)})^2. xˉ\bar x is the mean and S2=1n−1∑(xi−xˉ)2S^2 = \frac{1}{n-1}\sum (x_i - \bar x)^2. Lines L1 to L7 compute these formulas directly, so it remains to prove what the formulas give.

Claim 1 (the mean). If ss is the mean, the bias estimate is 0, θ^jack=xˉ\hat\theta_{jack} = \bar x and var^jack=S2/n\widehat{\mathrm{var}}_{jack} = S^2/n.

Proof. θ^(i)=(nxˉ−xi)/(n−1)\hat\theta_{(i)} = (n\bar x - x_i)/(n - 1), so θ^(⋅)=(nxˉ−xˉ)/(n−1)=xˉ\hat\theta_{(\cdot)} = (n\bar x - \bar x)/(n - 1) = \bar x and the bias estimate (n−1)(xˉ−xˉ)(n - 1)(\bar x - \bar x) is 0. Further θ^(i)−θ^(⋅)=(xˉ−xi)/(n−1)\hat\theta_{(i)} - \hat\theta_{(\cdot)} = (\bar x - x_i)/(n - 1), so

var^jack=n−1n⋅1(n−1)2∑i(xi−xˉ)2=1n⋅∑i(xi−xˉ)2n−1=S2n.□\widehat{\mathrm{var}}_{jack} = \frac{n - 1}{n} \cdot \frac{1}{(n-1)^2}\sum_i (x_i - \bar x)^2 = \frac{1}{n} \cdot \frac{\sum_i (x_i - \bar x)^2}{n - 1} = \frac{S^2}{n}. \qquad \square

The same computation with g(xi)g(x_i) in place of xix_i covers every statistic 1n∑g(xi)\frac{1}{n}\sum g(x_i).

Claim 2 (bias reduction). Suppose that for every sample size kk, E s(X1,…,Xk)=θ+a1/k+a2/k2E\, s(X_1, \ldots, X_k) = \theta + a_1/k + a_2/k^2 with constants a1,a2a_1, a_2. Then Eθ^jack=θ−a2/(n(n−1))E\hat\theta_{jack} = \theta - a_2/(n(n-1)). In particular, if a2=0a_2 = 0, θ^jack\hat\theta_{jack} is unbiased.

Proof. Each θ^(i)\hat\theta_{(i)} is ss on n−1n - 1 independent observations, so Eθ^(⋅)=θ+a1/(n−1)+a2/(n−1)2E\hat\theta_{(\cdot)} = \theta + a_1/(n-1) + a_2/(n-1)^2. Then

Eθ^jack=n(θ+a1n+a2n2)−(n−1)(θ+a1n−1+a2(n−1)2)=θ+a2n−a2n−1=θ−a2n(n−1).□E\hat\theta_{jack} = n\Bigl(\theta + \frac{a_1}{n} + \frac{a_2}{n^2}\Bigr) - (n - 1)\Bigl(\theta + \frac{a_1}{n - 1} + \frac{a_2}{(n - 1)^2}\Bigr) = \theta + \frac{a_2}{n} - \frac{a_2}{n - 1} = \theta - \frac{a_2}{n(n - 1)}. \qquad \square

Claim 3 (V-statistics become U-statistics). Let hh be symmetric, h(x,y)=h(y,x)h(x, y) = h(y, x), and let ss be the V-statistic V=1n2∑i=1n∑j=1nh(xi,xj)V = \frac{1}{n^2}\sum_{i=1}^n\sum_{j=1}^n h(x_i, x_j). Then

θ^jack=U=(n2)−1∑i<jh(xi,xj).\hat\theta_{jack} = U = \binom{n}{2}^{-1}\sum_{i < j} h(x_i, x_j).

Proof. Write A=∑ih(xi,xi)A = \sum_i h(x_i, x_i) and B=∑i<jh(xi,xj)B = \sum_{i<j} h(x_i, x_j), so V=(A+2B)/n2V = (A + 2B)/n^2. Leaving out xkx_k removes h(xk,xk)h(x_k, x_k) from AA and the n−1n - 1 terms h(xk,xj)h(x_k, x_j), j≠kj \ne k, from BB:

θ^(k)=A−h(xk,xk)+2(B−∑j≠kh(xk,xj))(n−1)2.\hat\theta_{(k)} = \frac{A - h(x_k, x_k) + 2\bigl(B - \sum_{j \ne k} h(x_k, x_j)\bigr)}{(n - 1)^2}.

Summing over kk, each diagonal term is removed once and each pair i<ji < j is removed twice, once for k=ik = i and once for k=jk = j. So

∑kθ^(k)=(n−1)A+2(n−2)B(n−1)2,(n−1)θ^(⋅)=(n−1)A+2(n−2)Bn(n−1).\sum_k \hat\theta_{(k)} = \frac{(n - 1)A + 2(n - 2)B}{(n - 1)^2}, \qquad (n - 1)\hat\theta_{(\cdot)} = \frac{(n - 1)A + 2(n - 2)B}{n(n - 1)}.

Then

θ^jack=A+2Bn−(n−1)A+2(n−2)Bn(n−1)=(n−1)(A+2B)−(n−1)A−2(n−2)Bn(n−1)=2Bn(n−1)=U.□\hat\theta_{jack} = \frac{A + 2B}{n} - \frac{(n - 1)A + 2(n - 2)B}{n(n - 1)} = \frac{(n - 1)(A + 2B) - (n - 1)A - 2(n - 2)B}{n(n - 1)} = \frac{2B}{n(n - 1)} = U. \qquad \square

Corollary (the plug-in variance). With h(x,y)=(x−y)2/2h(x, y) = (x - y)^2/2, V=12n2∑i,j(xi−xj)2=1n∑i(xi−xˉ)2V = \frac{1}{2n^2}\sum_{i,j}(x_i - x_j)^2 = \frac{1}{n}\sum_i (x_i - \bar x)^2, the plug-in variance, and U=S2U = S^2. So the jackknife turns the plug-in variance into the unbiased sample variance, and its bias estimate is V−S2=−S2/nV - S^2 = -S^2/n.

The identity 12n2∑i,j(xi−xj)2=1n∑i(xi−xˉ)2\frac{1}{2n^2}\sum_{i,j}(x_i - x_j)^2 = \frac{1}{n}\sum_i (x_i - \bar x)^2 follows by expanding (xi−xj)2=xi2−2xixj+xj2(x_i - x_j)^2 = x_i^2 - 2x_ix_j + x_j^2: the double sum is 2n∑xi2−2(nxˉ)2=2n∑(xi−xˉ)22n\sum x_i^2 - 2(n\bar x)^2 = 2n\sum (x_i - \bar x)^2. The identity U=S2U = S^2 follows in the same way, because ∑i<j(xi−xj)2\sum_{i<j}(x_i - x_j)^2 is half of the double sum.

Claim 4 (pseudo-values). With θ~i=nθ^−(n−1)θ^(i)\tilde\theta_i = n\hat\theta - (n - 1)\hat\theta_{(i)}, the mean of the θ~i\tilde\theta_i is θ^jack\hat\theta_{jack}, and 1n⋅1n−1∑i(θ~i−θ~ˉ)2=var^jack\frac{1}{n} \cdot \frac{1}{n - 1}\sum_i (\tilde\theta_i - \bar{\tilde\theta})^2 = \widehat{\mathrm{var}}_{jack}.

Proof. Averaging gives θ~ˉ=nθ^−(n−1)θ^(⋅)=θ^jack\bar{\tilde\theta} = n\hat\theta - (n - 1)\hat\theta_{(\cdot)} = \hat\theta_{jack}. Then θ~i−θ~ˉ=−(n−1)(θ^(i)−θ^(⋅))\tilde\theta_i - \bar{\tilde\theta} = -(n - 1)(\hat\theta_{(i)} - \hat\theta_{(\cdot)}), so

1n(n−1)∑i(θ~i−θ~ˉ)2=(n−1)2n(n−1)∑i(θ^(i)−θ^(⋅))2=var^jack.□\frac{1}{n(n - 1)}\sum_i (\tilde\theta_i - \bar{\tilde\theta})^2 = \frac{(n - 1)^2}{n(n - 1)}\sum_i (\hat\theta_{(i)} - \hat\theta_{(\cdot)})^2 = \widehat{\mathrm{var}}_{jack}. \qquad \square

For the mean, θ~i=nxˉ−(nxˉ−xi)=xi\tilde\theta_i = n\bar x - (n\bar x - x_i) = x_i: the pseudo-values are the data.

Claim 5 (the median with an even sample size). Let n=2mn = 2m, let ss be the median, and let x(1)≤⋯≤x(n)x_{(1)} \le \cdots \le x_{(n)} be the order statistics. Then var^jack=n−14(x(m+1)−x(m))2\widehat{\mathrm{var}}_{jack} = \frac{n - 1}{4}(x_{(m+1)} - x_{(m)})^2.

Proof. Without one observation, 2m−12m - 1 values remain and the median is the mm-th smallest of them. If the left-out observation is one of x(1),…,x(m)x_{(1)}, \ldots, x_{(m)}, the mm-th smallest of the rest is x(m+1)x_{(m+1)}. If it is one of x(m+1),…,x(n)x_{(m+1)}, \ldots, x_{(n)}, it is x(m)x_{(m)}. With ties the same holds for the values, whichever copy is left out. So mm of the θ^(i)\hat\theta_{(i)} equal x(m+1)x_{(m+1)} and mm equal x(m)x_{(m)}, their mean is (x(m)+x(m+1))/2(x_{(m)} + x_{(m+1)})/2, and each deviation is ±D/2\pm D/2 with D=x(m+1)−x(m)D = x_{(m+1)} - x_{(m)}. Hence var^jack=n−1n⋅n⋅D24=n−14D2\widehat{\mathrm{var}}_{jack} = \frac{n - 1}{n} \cdot n \cdot \frac{D^2}{4} = \frac{n - 1}{4}D^2. □\square

So the estimate depends on a single spacing of the sample. For a density ff that is positive at the median, nDn D is asymptotically exponential with mean 1/f(median)1/f(\text{median}), so var^jack\widehat{\mathrm{var}}_{jack} divided by the asymptotic variance 1/(4nf2)1/(4 n f^2) does not converge to 1. This explains the table on the page, which is a measurement.

Claim 6 (the delete-d jackknife for the mean). For every 1≤d<n1 \le d < n, the delete-dd variance n−dd(nd)∑S(xˉS−mˉ)2\frac{n - d}{d\binom{n}{d}}\sum_S (\bar x_S - \bar m)^2, where SS runs over the subsets of size r=n−dr = n - d and mˉ\bar m is the mean of the xˉS\bar x_S, equals S2/nS^2/n.

Proof. By symmetry each xix_i is in the same number of subsets, so mˉ=xˉ\bar m = \bar x. The mean of a random subset of size rr drawn without replacement from x1,…,xnx_1, \ldots, x_n has variance σ02r⋅n−rn−1\frac{\sigma_0^2}{r}\cdot\frac{n - r}{n - 1}, where σ02=n−1nS2\sigma_0^2 = \frac{n - 1}{n}S^2 is the population variance of the nn values. This is the variance of the uniform law over the subsets, so

1(nd)∑S(xˉS−xˉ)2=S2n⋅n−rr=S2n⋅dn−d,\frac{1}{\binom{n}{d}}\sum_S (\bar x_S - \bar x)^2 = \frac{S^2}{n} \cdot \frac{n - r}{r} = \frac{S^2}{n} \cdot \frac{d}{n - d},

and multiplying by n−dd\frac{n - d}{d} gives S2/nS^2/n. □\square

With d=1d = 1 the delete-dd formula is the formula of line L6, because the subsets are the nn leave-one-out samples. The tests check Claims 1 to 6 with exact Fraction arithmetic, and Claim 3 against the definition of the U-statistic as a sum over all pairs, for four kernels.

Cost. Line L3 runs nn times on n−1n - 1 values, which costs Θ(n2)\Theta(n^2) for a statistic of linear cost. Lines L4 to L6 cost Θ(n)\Theta(n). The nn values need Θ(n)\Theta(n) space.

Complexity

Lines L2 and L3 evaluate ss on nn samples of size n−1n - 1. For a statistic that costs Θ(n)\Theta(n), such as a mean or a variance, this is Θ(n2)\Theta(n^2) time, and lines L4 to L6 add Θ(n)\Theta(n). For the mean and other statistics built from sums, each θ^(i)\hat\theta_{(i)} follows from the full sums by one subtraction, and the whole jackknife costs Θ(n)\Theta(n). The extra space is Θ(n)\Theta(n) for the nn values. The delete-dd jackknife over all (nd)\binom{n}{d} subsets is much more expensive and is usually done on a random selection of subsets.

Properties

  • Deterministic. The same data always give the same result, unlike the bootstrap.
  • Exact for linear statistics. For a statistic of the form 1n∑g(xi)\frac{1}{n}\sum g(x_i), the variance estimate is exactly the unbiased estimate Sg2/nS_g^2/n.
  • Second-order bias reduction. The corrected estimate has bias O(n−2)O(n^{-2}) when the bias has an expansion in powers of 1/n1/n. The variance of the corrected estimate can be larger than that of θ^\hat\theta.
  • Conservative variance. Efron and Stein (1981) showed that, for any symmetric statistic SS of n−1n - 1 observations, E∑i=1n(S(i)−S(⋅))2≥Var S(X1,…,Xn−1)E\sum_{i=1}^n (S_{(i)} - S_{(\cdot)})^2 \ge \mathrm{Var}\, S(X_1, \ldots, X_{n-1}). So the jackknife variance tends to be too large rather than too small.
  • A linear approximation of the bootstrap. The jackknife variance is, up to the factor nn−1\frac{n}{n-1}, the bootstrap variance of the best linear approximation of the statistic in the resampling weights. It agrees with the bootstrap for smooth statistics and differs for nonsmooth ones.
  • Inconsistent for the median and other quantiles. The delete-1 estimate depends on one or two spacings of the order statistics, as the example shows.

Variants and improvements

  • Delete-dd jackknife. Leave out dd observations at a time and use n−dd(nd)∑S(θ^S−θˉ)2\frac{n - d}{d\binom{n}{d}}\sum_S (\hat\theta_S - \bar\theta)^2 over the subsets SS. For the mean it gives S2/nS^2/n for every dd. Shao and Wu (1989) proved that it is consistent for the sample quantiles when d/n→∞d/\sqrt n \to \infty and n−d→∞n - d \to \infty. With d=n−md = n - m it is closely related to subsampling with subsamples of size mm.
  • Grouped jackknife. Split the data into gg groups and leave out one group at a time. This is Quenouille's original form and reduces the cost to gg evaluations.
  • Infinitesimal jackknife. Replace the leave-one-out differences by derivatives of the statistic in the direction of each point, which are the empirical influence function values. This gives the delta-method variance 1n2∑ℓi2\frac{1}{n^2}\sum \ell_i^2.
  • Acceleration of BCa. The skewness of the leave-one-out values gives the acceleration aa of the BCa interval.
  • Jackknife+ prediction intervals. In predictive inference, leave-one-out residuals give prediction intervals with guaranteed coverage; see conformal prediction.
  • Leave-one-out cross-validation. The same loop that leaves out each point, applied to prediction error rather than to bias and variance, is cross-validation.

When to use it

Use the jackknife for a quick, deterministic standard error or bias correction of a smooth statistic: a mean, a ratio of means, a correlation, a regression coefficient or a smooth function of moments. It is useful when the statistic is expensive and nn is small, so that nn evaluations are cheaper than the b≥200b \ge 200 of the bootstrap. Use the bootstrap or the delete-dd jackknife for quantiles and other nonsmooth statistics, and the bootstrap when you need a confidence interval rather than a standard error.

Pitfalls

  • The median and other quantiles. The variance estimate is inconsistent, and the bias correction can be absurd, as the example shows.
  • Using the usual variance formula. The leave-one-out values are much closer together than independent replicates, because any two of them share n−2n - 2 observations. Their ordinary sample variance, with the factor 1/(n−1)1/(n - 1) in place of (n−1)/n(n - 1)/n, is too small by the factor (n−1)2/n(n - 1)^2/n.
  • Variance of the corrected estimate. The jackknife variance estimates the variance of θ^\hat\theta; it is often used for θ^jack\hat\theta_{jack} too, which is only approximately right.
  • Dependent data. Leaving out single observations of a time series ignores the dependence. Leave out blocks, as the block bootstrap resamples blocks.
  • Bias correction can increase the error. Removing a small bias can add more variance than it removes in mean squared error; report both θ^\hat\theta and θ^jack\hat\theta_{jack}.

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.

jackknife_resampling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jackknife-resampling/. The authors are listed in prov/DBF7V5.jsonl.

import itertools
import math
from typing import Callable, NamedTuple, Sequence

Statistic = Callable[[Sequence], object]


class JackknifeResult(NamedTuple):
    estimate: object  # theta_hat, the statistic on the full sample
    leave_one_out: list  # theta_(i), i = 1..n
    bias: object  # (n - 1) (theta_(.) - theta_hat)
    corrected: object  # theta_hat - bias
    variance: object  # ((n - 1)/n) sum (theta_(i) - theta_(.))^2


def jackknife(x: Sequence, statistic: Statistic) -> JackknifeResult:
    """The leave-one-out jackknife of Quenouille and Tukey.

    The arithmetic uses + - * / only, so Fraction data give exact results.
    """
    n = len(x)
    if n < 2:
        raise ValueError("the jackknife needs at least two observations")
    theta_hat = statistic(list(x))  # @line L1
    loo = []
    for i in range(n):  # @line L2
        loo.append(statistic(list(x[:i]) + list(x[i + 1 :])))  # @line L3
    theta_dot = sum(loo[1:], loo[0]) / n  # @line L4
    bias = (n - 1) * (theta_dot - theta_hat)  # @line L5
    variance = (n - 1) * sum(((t - theta_dot) ** 2 for t in loo[1:]), (loo[0] - theta_dot) ** 2) / n  # @line L6
    return JackknifeResult(theta_hat, loo, bias, theta_hat - bias, variance)  # @line L7


def pseudo_values(x: Sequence, statistic: Statistic) -> list:
    """Tukey's pseudo-values n theta_hat - (n - 1) theta_(i)."""
    r = jackknife(x, statistic)
    n = len(x)
    return [n * r.estimate - (n - 1) * t for t in r.leave_one_out]


def delete_d_variance(x: Sequence, statistic: Statistic, d: int):
    """The delete-d jackknife variance (n - d)/(d C(n, d)) sum_S (theta_S - mean)^2 over all
    subsets S that leave out d observations. It lists all C(n, d) subsets: small n only."""
    n = len(x)
    if not 1 <= d < n:
        raise ValueError("need 1 <= d < n")
    values = [statistic([x[i] for i in keep]) for keep in itertools.combinations(range(n), n - d)]
    count = len(values)
    mean = sum(values[1:], values[0]) / count
    ss = sum(((v - mean) ** 2 for v in values[1:]), (values[0] - mean) ** 2)
    return (n - d) * ss / (d * count)


def mean(xs: Sequence):
    return sum(xs[1:], xs[0]) / len(xs)


def plugin_variance(xs: Sequence):
    """The plug-in variance with divisor n, a V-statistic of degree 2."""
    m = mean(xs)
    return sum(((v - m) ** 2 for v in xs[1:]), (xs[0] - m) ** 2) / len(xs)


def median(xs: Sequence):
    s = sorted(xs)
    k = len(s)
    if k % 2:
        return s[k // 2]
    return (s[k // 2 - 1] + s[k // 2]) / 2


def jackknife_se(x: Sequence[float], statistic: Statistic) -> float:
    return math.sqrt(jackknife(x, statistic).variance)
test_jackknife_resampling.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jackknife-resampling/. The authors are listed in prov/DBF7V5.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from jackknife_resampling import delete_d_variance, jackknife, mean, median, plugin_variance, pseudo_values

MOUSE_TREATMENT = [94, 197, 16, 38, 99, 141, 23]


def sample_variance(xs):
    """S^2 with divisor n - 1, by its definition."""
    m = Fraction(sum(xs), len(xs))
    return sum((Fraction(v) - m) ** 2 for v in xs) / (len(xs) - 1)


def random_fractions(rng, n):
    return [Fraction(rng.randint(-50, 50), rng.randint(1, 6)) for _ in range(n)]


def test_variance_of_the_mean_is_s2_over_n():
    rng = random.Random(1)
    for n in range(2, 12):
        x = random_fractions(rng, n)
        r = jackknife(x, mean)
        assert r.variance == sample_variance(x) / n
        assert r.bias == 0 and r.corrected == mean(x)


def test_jackknife_of_plugin_variance_is_s2():
    rng = random.Random(2)
    for n in range(2, 12):
        x = random_fractions(rng, n)
        r = jackknife(x, plugin_variance)
        assert r.corrected == sample_variance(x)
        assert r.bias == -sample_variance(x) / n  # E(plug-in) - sigma^2 = -sigma^2/n


def u_statistic_by_definition(x, kernel):
    """The average of the kernel over all 2-subsets of the sample."""
    pairs = list(itertools.combinations(range(len(x)), 2))
    return sum((kernel(x[i], x[j]) for i, j in pairs), Fraction(0)) / len(pairs)


def v_statistic(kernel):
    def v(xs):
        n = len(xs)
        return sum((kernel(a, b) for a in xs for b in xs), Fraction(0)) / (n * n)

    return v


KERNELS = [
    lambda a, b: (a - b) ** 2 / 2,  # U = S^2
    lambda a, b: abs(a - b),  # Gini mean difference
    lambda a, b: Fraction(int(a + b > 0)),  # Wilcoxon one-sample kernel
    lambda a, b: a * b,  # U estimates mu^2
]


def test_jackknifed_v_statistic_is_the_u_statistic():
    rng = random.Random(3)
    for n in range(2, 9):
        x = random_fractions(rng, n)
        for h in KERNELS:
            assert jackknife(x, v_statistic(h)).corrected == u_statistic_by_definition(x, h)
    x = random_fractions(rng, 6)
    assert u_statistic_by_definition(x, KERNELS[0]) == sample_variance(x)


def test_pseudo_values():
    rng = random.Random(4)
    for n in range(2, 10):
        x = random_fractions(rng, n)
        r = jackknife(x, plugin_variance)
        pv = pseudo_values(x, plugin_variance)
        assert sum(pv) / n == r.corrected
        assert sample_variance(pv) / n == r.variance
        assert pseudo_values(x, mean) == x  # the pseudo-values of the mean are the data


def test_median_formula_and_inconsistency():
    rng = random.Random(5)
    for m in range(1, 7):
        n = 2 * m
        x = sorted(random_fractions(rng, n))
        gap = x[m] - x[m - 1]
        assert jackknife(x, median).variance == Fraction(n - 1, 4) * gap**2
    # For odd n the leave-one-out medians take only three values.
    loo = jackknife(MOUSE_TREATMENT, median).leave_one_out
    assert sorted(set(loo)) == [66, Fraction(137, 2), Fraction(193, 2)]


def test_delete_d_reduces_to_delete_one_and_is_exact_for_the_mean():
    rng = random.Random(6)
    for n in range(3, 9):
        x = random_fractions(rng, n)
        assert delete_d_variance(x, plugin_variance, 1) == jackknife(x, plugin_variance).variance
        for d in range(1, n):
            assert delete_d_variance(x, mean, d) == sample_variance(x) / n


def test_median_variance_estimates_by_simulation():
    """Measured, not proved: the delete-1 jackknife variance of the median does not settle
    as n grows, while the delete-d version with d near sqrt(n) stays closer to the truth."""
    rng = random.Random(7)
    n, reps = 16, 60
    ratios_one, ratios_d = [], []
    for _ in range(reps):
        x = [rng.random() for _ in range(n)]
        ratios_one.append(jackknife(x, median).variance)
        ratios_d.append(delete_d_variance(x, median, 4))
    true_var = 1 / (4 * (n + 2))  # variance of the uniform median, about 1/(4n)
    spread_one = math.sqrt(sum((v / true_var - 1) ** 2 for v in ratios_one) / reps)
    spread_d = math.sqrt(sum((v / true_var - 1) ** 2 for v in ratios_d) / reps)
    assert spread_d < spread_one


def test_float_example_and_errors():
    r = jackknife([float(v) for v in MOUSE_TREATMENT], mean)
    s2 = sample_variance(MOUSE_TREATMENT)
    assert math.isclose(math.sqrt(r.variance), math.sqrt(s2 / 7), rel_tol=1e-12)
    with pytest.raises(ValueError):
        jackknife([1.0], mean)
    with pytest.raises(ValueError):
        delete_d_variance([1, 2, 3], mean, 3)

History

Maurice Quenouille introduced the idea in 1949, to reduce the bias of estimates of serial correlation by combining estimates on parts of the sample, and in 1956 gave the leave-one-out form nθ^−(n−1)θ^(⋅)n\hat\theta - (n - 1)\hat\theta_{(\cdot)}. John Tukey, in a 1958 abstract, saw that the pseudo-values behave approximately like independent observations, which gives a variance estimate and approximate t intervals, and named the method after the pocket knife that serves many purposes. Rupert Miller studied its theory in the 1960s and 1970s. Bradley Efron's 1979 bootstrap paper presented the bootstrap as "another look at the jackknife", and Efron and Stein (1981) proved that the jackknife variance is biased upward. Shao and Wu (1989) developed the delete-dd jackknife.

References

  1. M. H. Quenouille, Approximate tests of correlation in time-series, Journal of the Royal Statistical Society, Series B 11(1), 1949, pp. 68 to 84 (the bias reduction by estimates on parts of the sample)
  2. M. H. Quenouille, Notes on bias in estimation, Biometrika 43(3-4), 1956, pp. 353 to 360 (the leave-one-out bias correction n θ̂ - (n - 1) θ̂_(·))
  3. J. W. Tukey, Bias and confidence in not-quite large samples, 1958, p. 614 (the pseudo-values and the jackknife variance estimate)
  4. Bradley Efron and Robert J. Tibshirani, An Introduction to the Bootstrap, Chapman and Hall, 1993, Chapter 11 (the jackknife, its bias and variance estimates, the failure for the median and the delete-d jackknife)
  5. B. Efron and C. Stein, The jackknife estimate of variance, The Annals of Statistics 9(3), 1981, pp. 586 to 596 (the jackknife variance estimate is biased upward)
  6. Jun Shao and C. F. J. Wu, A general theory for jackknife variance estimation, The Annals of Statistics 17(3), 1989, pp. 1176 to 1197 (the delete-d jackknife and its consistency for the sample quantiles)

Where this leads

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