Lecture 27 Confidence Versus Credibility

This is the R session for week 9 of the course. In lectures this week we have introduced the topics of confidence intervals and Bayesian priors and posteriors. The aim of this R session is to visualise these concepts: we will consider a hundred confidence intervals, together with a count of how often these intervals “miss” the target, we will consider a confidence interval and a Bayesian interval for the same data, and we will consider how a prior can be transformed into a posterior as observations are added one by one. Today we will use the Bayesian interval in an informal way, in preparation for the fact that in one week (in lecture 28) we will introduce the concept of a credible interval and will then be able to make a proper comparison between confidence intervals and credible intervals.

27.1 Coverage by Simulation

The interval of the day is the zz-interval from example 25.3, using the numerical values from the example (n=16n=16, σ=2\sigma=2 are known), so that the 95%95\% interval is X¯±1.96⋅0.5\bar{X}\pm 1.96\cdot 0.5. By definition 25.1 of the level 0.950.95, the random interval contains the fixed value θ\theta in 95%95\% of all samples. To verify this, we consider θ=10\theta=10 and compute the interval for 100100 samples. Before you execute the code, answer the following questions: (1) How many of the 100100 intervals will not cover the value 1010? (2) Will all intervals have the same width? (3) Will the misses be clustered or evenly distributed among the 100 samples?

theta <- 10
sigma <- 2
n <- 16
z_interval <- function() {
x <- rnorm(n, mean = theta, sd = sigma)
mean(x) + c(-1, 1) * qnorm(0.975) * sigma / sqrt(n)
}
set.seed(2026)
ci <- replicate(100, z_interval())
covers <- ci[1, ] <= theta & theta <= ci[2, ]
sum(covers)
which(!covers)
## [1] 95
## [1] 1 29 34 63 83

As in lecture 12, covers is a vector of TRUE and FALSE, one for each interval, indicating whether the interval covers the truth. The command mean counts the proportion of TRUE values, which are interpreted as ones and zeros by R. For the example, 9595 out of 100100 intervals cover the truth. The misses are for samples 11, 2929, 3434, 6363 and 8383. The exact number 9595 is a coincidence, determined by the seed of the random number generator: the number of intervals which cover the truth is binomially distributed with standard deviation 2.22.2, so 9292 or 9898 would have been just as unremarkable. The command segments can be used to plot each interval as a horizontal line, and the samples where the interval covers the truth are plotted in grey while the misses are plotted in black.

plot(NULL, xlim = range(ci), ylim = c(1, 100),
xlab = expression(theta), ylab = "sample number")
segments(ci[1, ], 1:100, ci[2, ], 1:100,
col = ifelse(covers, "grey60", "black"), lwd = 2)
abline(v = theta, lty = 2)
One hundred horizontal segments, each of equal
length, are shown, stacked on top of each other. The samples
are ordered so that sample 1 is at the bottom and sample 100 is
at the top. A dashed vertical line marks the location of
theta = 10. Ninety-five of the grey segments intersect the line,
while five of the black segments, corresponding to samples 1,
29, 34, 63 and 83, are completely on one side of the line.
Figure 27.1: One hundred 95%95\% confidence intervals for the mean of a N⁢(θ,4)N(\theta,4) sample of size n=16n=16, with true value θ=10\theta=10 (dashed line). The grey intervals cover the truth, the black intervals do not.

Figure 27.1 illustrates the confidence level of the procedure in a graphical way. The intervals in the figure all have the same width, since the value σ\sigma is known: the intervals move, while the dashed line stays fixed. The misses are not clustered but are scattered throughout the figure, since the samples are independent. If we had only observed sample 2929, the interval [10.43,12.39][10.43,12.39] would have been indistinguishable from the others, and there would have been no indication in the data that this was a miss. For this reason, the statement “θ\theta is in the interval [10.43,12.39][10.43,12.39] with probability 0.950.95” is wrong: the value 1010 is either in the interval or it is not, but in this instance it is not. The probability refers to the procedure, not to the individual values. Before the code is executed, predict the long-run proportion of intervals which cover the truth, and determine the distance from 0.950.95 where an error is no longer considered significant.

ci <- replicate(10000, z_interval())
mean(ci[1, ] <= theta & theta <= ci[2, ])
## [1] 0.9473

The long-run coverage is 0.9470.947. The standard error of this estimate is 0.95⋅0.05/10000=0.002\sqrt{0.95\cdot 0.05/10000}=0.002, so the estimate is about one and a half standard errors below the nominal value 0.950.95: this is good agreement, considering the simulation error. The pivot argument in example 25.3 guarantees that this result holds for every value of θ\theta.

27.2 The Same Data, Two Intervals

We now take the data of example 25.8, T=37T=37 successes in n=100n=100 Bernoulli trials, and compute two intervals for the success probability θ\theta. The first is the Wald interval x¯±1.96⁢x¯⁢(1−x¯)/n\bar{x}\pm 1.96\sqrt{\bar{x}(1-\bar{x})/n} of that example. For the second we treat θ\theta as random, as in lecture 26: the flat-prior posterior is Beta⁢(1+T, 1+n−T)\text{Beta}(1+T,\,1+n-T) by example 26.5, and the interval between its 2.5%2.5\% and 97.5%97.5\% quantiles contains θ\theta with posterior probability 0.950.95; this is the equal-tailed credible interval of lecture 28, and the command qbeta can be used to find the quantiles. Before you run the code, predict whether the credible interval will be wider or narrower than the Wald interval, and whether it will sit to the left or to the right of it.

n <- 100
total <- 37
xbar <- total / n
se <- sqrt(xbar * (1 - xbar) / n)
xbar + c(-1, 1) * qnorm(0.975) * se
a <- 1 + total
b <- 1 + n - total
qbeta(c(0.025, 0.975), a, b)
## [1] 0.2753721 0.4646279
## [1] 0.2817646 0.4680688

The two intervals, [0.275,0.465][0.275,0.465] and [0.282,0.468][0.282,0.468], coincide to two decimal digits; the credible interval is slightly shifted towards 1/21/2, due to the fact that the flat prior adds one success and one failure to the data. The Wald interval states that the recipe used to compute it covers the truth in approximately 95%95\% of samples. It does not make a statement about this particular interval. The credible interval states that, given the observations and the flat prior, the probability that θ\theta falls between 0.2820.282 and 0.4680.468 is 0.950.95: the sentence forbidden in the previous section is the correct interpretation in this context, since θ\theta is a random variable in the Bayesian model. The posterior distribution can be used to answer other questions; the command pbeta can be used to evaluate its distribution function.

lower <- xbar - qnorm(0.975) * se
upper <- xbar + qnorm(0.975) * se
pbeta(upper, a, b) - pbeta(lower, a, b)
1 - pbeta(0.5, a, b)
qbeta(c(0.025, 0.975), 12 + total, 3 + n - total)
## [1] 0.9531666
## [1] 0.004667524
## [1] 0.3374894 0.5171204

The Wald interval itself has posterior probability 0.9530.953 under the flat prior, and the posterior probability that θ\theta exceeds 1/21/2 is 0.0050.005. The frequentist interval cannot make a statement about this probability. The final line shows the price of departing from the flat prior: under the informative prior Beta⁢(12,3)\text{Beta}(12,3), with mean 0.80.8 and equivalent sample size 1515, the same data give the credible interval [0.337,0.517][0.337,0.517]. A credible interval always depends on the prior, and numerical agreement with a confidence interval is a property of the flat prior and of the sample size. We will consider this comparison in more detail in lecture 28.

27.3 From Prior to Posterior

The following picture illustrates the update from lecture 26, where we process the observations one by one. In the example, we simulate 100100 Bernoulli observations with θ=0.3\theta=0.3. After kk observations, with ss successes, the prior distribution with Beta⁢(a,b)\text{Beta}(a,b) has evolved into the posterior distribution Beta⁢(a+s,b+k−s)\text{Beta}(a+s,\,b+k-s) with mean (a+s)/(a+b+k)(a+s)/(a+b+k). This result was obtained in example 26.5. The box below contains a script for computing the posterior mean of the flat prior after k=20k=20 observations. The lines in the box are shuffled, so you will need to sort them into a working script before you can try the code.

successes <- cumsum(x)
theta <- 0.3
(a + successes[k]) / (a + b + k) # posterior mean after k observations
x <- rbinom(100, size = 1, prob = theta)
k <- 20
set.seed(2026)
a <- 1
b <- 1

As always, names must be defined before they are used, and the seed must be set before the first random draw: theta first, followed by the seed, then rbinom with size = 1 to generate the Bernoulli draws, then cumsum to generate the running total of successes; a, b and k can be placed anywhere before the last line. The script R/S27-posterior.R extends this to handle three priors simultaneously, stored as the rows of a matrix: the flat prior Beta⁢(1,1)\text{Beta}(1,1), the Jeffreys prior Beta⁢(1/2,1/2)\text{Beta}(1/2,1/2) from example 26.10 and the misplaced prior Beta⁢(12,3)\text{Beta}(12,3) from the previous section. Before you look at the output of the following code, predict the result: which of the three posterior means will be closest to 0.30.3 after five observations? Will you still be able to distinguish between the three posterior means after one hundred observations?

priors <- rbind(flat = c(1, 1), jeffreys = c(0.5, 0.5),
informative = c(12, 3))
post_mean <- function(k) {
s <- if (k == 0) 0 else successes[k]
(priors[, 1] + s) / (priors[, 1] + priors[, 2] + k)
}
head(x, 10)
successes[c(5, 20, 100)]
round(sapply(c(0, 5, 20, 100), post_mean), 3)
## [1] 0 0 0 0 0 0 0 1 0 0
## [1] 0 2 28
## [,1] [,2] [,3] [,4]
## flat 0.5 0.143 0.136 0.284
## jeffreys 0.5 0.083 0.119 0.282
## informative 0.8 0.600 0.400 0.348

The start of the sequence is bad: the first five observations are all failures and after twenty observations there have been only two successes. The probability of at most two successes in twenty observations is 0.0350.035 for θ=0.3\theta=0.3. For this case, the prediction at k=5k=5 is dominated by the flat prior: the posterior mean 0.1430.143 is closest to 0.30.3, since five failures have driven both weak priors below the truth, and the Jeffreys prior is driven lower than the flat prior is. The misplaced prior is still at 0.60.6. The two weak priors follow the data and end at 0.140.14 and 0.120.12, both far below the truth. The misplaced prior, moving from 0.80.8 to 0.40.4, is the closest of the three at k=20k=20: with twenty observations, the data alone is not enough to avoid being misled, but a prior in the correct region helps and a prior in the wrong region does harm. The data does not allow us to infer the correct region. By k=100k=100 the two weak priors are indistinguishable at 0.280.28 and even the misplaced prior, with an equivalent sample size of 1515, is now mostly aligned with the sample proportion. The script plots the three posterior densities at each stage using curve and dbeta. Before you look at figure 27.2, sketch the panel for k=5k=5: which curves are steep, where do they take their peaks and how wide are the curves?

Four panels of Beta densities on the unit
interval, each with three curves and a grey vertical line at 0.3.
For k=0 the flat prior is a horizontal line, the Jeffreys prior is a
shallow U and the informative prior is a hump with a maximum
around 0.85. For n=5, all failures, two curves start steep at
the left edge and the hump has moved to 0.6. For n=20, two
successes, the two narrow humps are around 0.1 and the third is
around 0.4. For n=100, 28 successes, two narrow peaks at 0.28
are on the grey line, with a third peak at 0.34 overlapping the
other two.
Figure 27.2: Posterior densities for the probability of success in a Bernoulli trial after k=0k=0, 55, 2020 and 100100 observations of one simulated sequence with θ=0.3\theta=0.3 (grey vertical line), for the priors Beta⁢(1,1)\text{Beta}(1,1) (solid), Beta⁢(1/2,1/2)\text{Beta}(1/2,1/2) (dashed) and Beta⁢(12,3)\text{Beta}(12,3) (dotted).

Figure 27.2 summarises the update procedure. At k=0k=0 the three curves correspond to the prior distributions from lecture 26. One can see that the Jeffreys prior is not flat. At k=5k=5 the two weak posteriors have the largest values at 0, since no successes have been observed so far, and the informative posterior has not yet significantly changed. At k=20k=20 all three posteriors have the form of humps, and the posteriors are narrower than in the previous step: as data are added, the posterior gets sharper, irrespective of the prior distribution. At k=100k=100 the two weak posteriors coincide and the informative posterior overlaps these two: this is a consequence of the prior being washed out in example 26.5, and the panel for k=20k=20 serves as a reminder that data are needed to achieve this effect.

Repeat the picture in figure 27.1 for the tt-interval from example 25.4, but with n=5n=5, sigma replaced with sd(x) and qnorm(0.975) replaced with qt(0.975, df = 4). The widths of the intervals will change. Estimate how often the intervals miss the target value, and estimate the long-run coverage from 1000010000 samples. Repeat the experiment, but this time leaving qnorm(0.975) instead of the tt quantile, and comment on your result. Finally, choose a prior mean and an equivalent sample size as in exercise 26.1, use your student ID as the seed for the random number generator, and repeat the posterior sequence of the last section, both with and without the prior. For both cases, determine the first kk where the posterior mean is within 0.050.05 of the truth.

Type the commands used in this session into R, and check that you get the same results as the text.

Summary.
  • •
    ​

    The written reference for the commands used in this session is appendix B.

  • •
    ​

    The confidence level of a statistical procedure is a property of the procedure: in 100100 simulated trials of 95%95\% intervals, 9595 intervals contained the truth, the misses were indistinguishable from the successes, and in the long run the coverage was 0.9470.947. A computed confidence interval either contains the parameter or it does not.

  • •
    ​

    For the same Bernoulli data, the Wald interval and the credible interval with flat prior coincide to two decimal digits, but they are different statements: the credible interval is a probability statement about θ\theta, conditioned on the data and on the prior, and thus depends on the prior.

  • •
    ​

    The Beta posterior gets more and more sharp as observations are added, and in the limit it converges to the sample proportion for every prior. For 2020 observations the prior is still noticeable, but for 100100 the prior is largely washed out.