Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 3.2 — Confidence intervals

This notebook contains the code examples from Section 3.2 Confidence intervals of the No Bullshit Guide to Statistics. Use the “rocket” icon at the top-right to make the code cells interactive (Live Code), or run this notebook an ephemeral JupyterLab cloud instance (Binder).

Notebook setup

Note: you may need to restart the kernel to use updated packages.
<Figure size 640x480 with 0 Axes>
datasets/ directory already exists.

\def\stderr#1{\mathbf{se}_{#1}} \def\stderrhat#1{\hat{\mathbf{se}}_{#1}} \def\Mean{\textbf{mean}} \def\Var{\textbf{var}} \def\Std{\textbf{std}} \def\Freq{\textbf{freq}} \def\RelFreq{\textbf{relfreq}} \def\CI#1{\textbf{CI}_{#1}} \def\CIL#1{\textbf{L}_{#1}} \def\CIU#1{\textbf{U}_{#1}} \def\ci#1{\textbf{ci}_{#1}} \def\cil#1{\textbf{l}_{#1}} \def\ciu#1{\textbf{u}_{#1}} \def\DMeans{\textbf{dmeans}} \def\Prop{\textbf{prop}} \def\DProps{\textbf{dprops}} \def\Err{ {\Large \varepsilon}} \def\calN{\mathcal{N}} \def\Tdist{\mathcal{T}} \def\Expon{\mathrm{Expon}}

(this cell contains the macro definitions like sex‾\stderr{\overline{\mathbf{x}}}, se^\stderrhat{}, mean\Mean, ...)

Definitions

Review of estimators

Recall all the estimators (functions that take samples as inputs) we defined in the previous section.

Interpreting confidence intervals

Illustration of 90% confidence intervals for the population mean. The plot shows confidence intervals ciθ,0.9,1\ci{\theta,0.9,1}, ciθ,0.9,2\ci{\theta,0.9,2}, ciθ,0.9,3\ci{\theta,0.9,3}, …\ldots, ciθ,0.9,50\ci{\theta,0.9,50}, which we computed from 50 different samples of size n=20n=20 taken from the population X∼N(100,10)X \sim \mathcal{N}(100,10). The true population mean is μX=100\mu_X = 100. Intervals that don’t include μX\mu_X are drawn in light red.

Confidence interval constructions

Ingredients:

  • knowledge of the sampling distribution Θ^\widehat{\Theta} of the estimator

  • knowledge of the inverse cumulative distribution function (inverse-CDF) of the sampling distributions FΘ^−1F^{-1}_{\widehat{\Theta}}

Procedure:

  • calculate the α2\tfrac{\alpha}{2}-quantile, FΘ^−1(α2)F^{-1}_{\widehat{\Theta}}(\tfrac{\alpha}{2}), and the (1−α2)(1-\tfrac{\alpha}{2})-quantile, FΘ^−1(1−α2)F^{-1}_{\widehat{\Theta}}(1-\tfrac{\alpha}{2}) of the sampling distribution

  • use a pivotal quantity to convert the quantiles of the sampling distribution and obtain the lower bound and upper bounds of the confidence interval

Recall the two methods for approximating sampling distributions: analytical approximation formulas (based on probability distributions) and the bootstrap estimation procedure (based on computation), which we learned in Section 3.1. We’ll now learn how to compute confidence intervals based on these approximation methods.

<Figure size 600x140 with 1 Axes>

Bootstrap confidence intervals

3.0
[4.4, 3.2, 3.6, 3.2, 2.6]
[1.8, 4.2]
[1.8, 4.2]

Analytical approximations

zℓ=FZ−1(α2)andzu=FZ−1(1−α2).z_\ell = F_{Z}^{-1}(\tfrac{\alpha}{2}) \qquad \text{and} \qquad z_u = F_{Z}^{-1}(1-\tfrac{\alpha}{2}).
1.644853626951472
1.644853626951472

Default parameters

1.644853626951472

Class methods

1.644853626951472
1.644853626951472

Construct 90% confidence interval for the Z distribution

[-1.6448536269514729, 1.644853626951472]

Other standard reference distributions

Just call class method, since by default loc=0 and scale=1.

1.9431802805153042
12.591587243743977

Confidence interval for the population mean

T=X‾−μXse^x‾∼T(n−1).T = \frac{\overline{\mathbf{X}} - \mu_X}{ \stderrhat{\overline{\mathbf{x}}} } \sim \mathcal{T}(n-1).

To build a (1−α)(1-\alpha) confidence interval, we first calculate the α2\frac{\alpha}{2} and (1−α2)(1-\frac{\alpha}{2}) quantiles of Student’s tt-distribution:

tℓ=FT−1(α2)andtu=FT−1(1−α2).t_\ell = F_{T}^{-1}(\tfrac{\alpha}{2}) \qquad \text{and} \qquad t_u = F_{T}^{-1}(1-\tfrac{\alpha}{2}).
<Figure size 600x140 with 1 Axes>

Example 1: confidence interval for the mean apple weight

array([205., 182., 192., 189., 217., 192., 210., 240., 225., 191., 193., 209., 167., 183., 210., 198., 239., 188., 179., 182., 200., 197., 245., 192., 201., 218., 198., 211., 208., 217.])

The sample mean is:

202.6

Analytical confidence interval for the mean

30
3.3959407817427336
[196.82986523723363, 208.37013476276636]

We would normally report this interval as [197,208][197, 208] without too many decimals.

Bootstrap confidence interval for the mean

[197.23333333333332, 208.26666666666668]

Reusable procedure

Verify coverage probability

Coverage proportion of analytical approx. CIs: 0.89
Coverage proportion of bootstrap CIs: 0.86

Confidence interval for the population variance

<Figure size 600x140 with 1 Axes>

Example 2: confidence interval for the variance of apple weights

30
345.9724137931035
[235.75927791988897, 566.5796548600426]

Bootstrap confidence interval for the variance

[196.387816091954, 480.82183908046]

Reusable procedure

Verify coverage probability

Coverage proportion of analytical approx. CIs: 0.89
Coverage proportion of bootstrap CIs: 0.81

Alternative calculation methods

Using scipy.stats.bootstrap for confidence intervals

One-sample bootstrap confidence interval

[197.23333333333332, 208.26666666666668]

Note the result is the same as ...

Using the function scipy.stats.bootstrap requires lots of keyword arguments, because it is a very powerful tool you can use for all kinds of bootstrap calculations. Let’s go over the arguments one by one:

  • Instead of giving the input asample directly as the first argument, we pass in a list of length one [asample] which tells the function that we want a single-sample calculation

  • statistic: specify the estimator we want to compute confidence interval for

  • confidence_level: the confidence level (1−α)(1-\alpha)

  • n_resamples: the number of bootstrap samples we want to generate

  • vectorized=False: turns off vectorized inputs, which is a performance optimization that we don’t need for this calculation

  • method="percentile": select the percentile bootstrap method, as opposed to one of the other bootstrap methods that are available

The bootstrap function returns a result object. We can access the attributes of this object to obtain the limits of the confidence interval. Note the result is identical to the bootstrap estimate we obtained from the function gen_boot_dist followed by np.percentile calculations.

Using statsmodels for confidence intervals

The Python libraries statsmodels, scipy.stats, and pingouin provide predefined functions for computing confidence intervals. We’ll now show some of these “alternative computations” based on predefined functions so you’ll learn a little bit about the tools for statistical analysis that are available to you.

We’ll also use these alternative computations to confirm that the calculations we did from first principles are correct.

Note however these are “optional” reading materials, and you can skip any code cells that start with an # ALT comment without loss of generality.

(196.82986523723363, 208.37013476276636)

As you can see, the numbers we obtain from the statsmodels is exactly the same as the confidence interval we computed manually.

Using pingouin for confidence intervals

array([197.27, 208.3 ])

Note the results are the same as ...

Explanations

One-sided confidence intervals

Point and interval estimates

terminology...

Frequentist interpretation

Guarantees for confidence intervals given in terms of EX\mathbb{E}_\mathbf{X}, the expectation over a random sample X\mathbf{X}. These guarantees can be interpreted as long-term average error rates if the statistical procedure were performed many times (frequentist paradigm). Note in the frequentist paradigm gives no guarantee about any specific confidence interval—only gives guarantee about the performance of the procedure we used for computing the CIs.

Assumptions

condensed mention of: (full discussion of assumptions in Sec 3.4) Parametric model assumption (conceptual) cf. nonparametric methods

  • (NORM): the population is normally distributed (normality test)

  • (LARGEn): the sample size is “large enough” for approximate normality

  • (EQVAR): the variance in two groups is the same

Discussion

Misconceptions about confidence intervals

See main text.

Comparing analytical formulas and bootstrap estimates

See main text.

Advanced bootstrap methods

Mention more advanced bootstrap methods like BCa exist (--> see problem PZZ)

[197.6, 208.46666666666664]
[231.29845557680545, 541.41793330525]

This interval is very close to the analytical approximation we obtained in terms of the chi-square reference distribution [235.8,566.6][235.8, 566.6].

Evaluation of confidence interval methods

Rows:

  • uniform

  • norm

  • slightly skewed

  • very skewed

  • bimodal

Column groups:

  • coverage probability

  • average width

Cols:

  • analytical approx

  • percentile bootstrap

  • BCa

<Figure size 700x400 with 4 Axes>

Coverage probabilities for population mean

simdata/ directory present and ready.
loaded cached results from  simdata/simulate_ci_props_mean__ns_20_40__alpha_0.1__seed_42.csv
Loading...

Coverage probabilities for population variance

loaded cached results from  simdata/simulate_ci_props_var__ns_20_40__alpha_0.1__seed_43.csv
Loading...