11.3. Confidence Intervals#
A manager at a UK online gift retailer, which sells mostly to wholesalers, asks three questions. How much does a customer typically spend on an order? What share of orders are large, worth more than £500, the level at which the retailer considers offering free delivery? And how sure can the manager be of either answer? Reading every order is slow, so the manager works from a random sample of 400 orders. (The orders are real, from the UCI Online Retail II data, D. Chen, 2019, CC BY 4.0. The sample, in online_retail_orders.csv, was drawn at random from the 33,398 orders by identified UK customers that are worth under £5,000; the file keeps order value in pounds, the number of items, and whether the order is above £500.) Any number computed from that sample is an estimate, and a different sample would have given a different one.
In The Bootstrap you learned to measure that variation by resampling the sample many times. This section turns the resulting bootstrap distribution into a confidence interval: a range of plausible values for the unknown population quantity. You will build intervals for a median, a mean, and a proportion, see how the confidence level and the sample size change their width, and end with the situations in which the method should not be trusted.
11.3.1. Bootstrap Percentile Intervals#
A manager needs both an estimate and a way to describe its uncertainty: how far the estimate might be from the parameter. A confidence interval (CI) is an interval estimate: it estimates a population parameter with two endpoints instead of one number. The confidence level describes how the procedure behaves over many samples: if you drew fresh random samples again and again and built an interval from each, an approximate 95% procedure would capture the fixed population parameter in about 95% of them.
The bootstrap percentile method builds the interval from the bootstrap distribution itself. Sort the resampled statistics and keep the middle ones. For a central 95% interval, leave 2.5% in each tail and use the 2.5th and 97.5th percentiles as the endpoints. In general, a central C% interval leaves (100 - C)/2 percent in each tail. As in Percentiles, percentiles are computed with method='nearest'.
Here is the sample. Each row is one order: its value in pounds, the number of items, and whether it is a large order (large_order is 1 if the value is above £500 and 0 otherwise).
orders = pd.read_csv(path_data + 'online_retail_orders.csv')
orders.head()
| order_value | items | large_order | |
|---|---|---|---|
| 0 | 279.77 | 126 | 0 |
| 1 | 175.15 | 149 | 0 |
| 2 | 188.85 | 109 | 0 |
| 3 | 1894.01 | 706 | 1 |
| 4 | 115.45 | 79 | 0 |
Order values are right-skewed: most orders are modest, and a few are large.
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.hist(orders['order_value'], bins=np.arange(0, 4600, 200), color='steelblue', edgecolor='white')
ax.set_xlabel('Order value (pounds)', fontsize=12)
ax.set_ylabel('Number of orders', fontsize=12)
ax.set_title('Most orders are modest; a few are large', fontsize=13)
plt.show()
order_values = orders['order_value'].to_numpy()
large_flags = orders['large_order'].to_numpy()
print('Orders in the sample:', len(order_values))
Orders in the sample: 400
The table below shows how many values go in each tail for two common confidence levels. The function central_interval (defined in the hidden setup cell) does this arithmetic.
for confidence in [95, 80]:
tail = (100 - confidence) / 2
print(f'{confidence}% interval: {tail}% in each tail, so use percentiles {tail} and {100 - tail}')
95% interval: 2.5% in each tail, so use percentiles 2.5 and 97.5
80% interval: 10.0% in each tail, so use percentiles 10.0 and 90.0
A percentile interval is built from the two tails separately, so it need not be symmetric around the sample estimate. For that reason, report both endpoints and avoid a single “plus or minus” margin of error (a half-width added to and subtracted from the estimate) unless the interval really is balanced.
11.3.1.1. Practice#
### Exercise: Choose the tails
# boot_means holds 20 bootstrap means of weekly sales (in $1,000s).
# 1. A central 90% interval leaves what percentage in each tail?
# 2. Print the lower and upper percentile levels.
# 3. Use them with np.percentile(..., method='nearest') to print the 90% interval.
# Print exactly:
# Percentile levels: 5.0 95.0
# 90% interval: 47.9 to 52.4
import numpy as np
confidence = 90
boot_means = np.array([48.2, 51.0, 49.5, 50.3, 47.9, 52.4, 50.8, 49.1, 51.7, 50.0,
48.8, 53.1, 49.9, 50.6, 47.4, 51.3, 50.2, 49.6, 52.0, 48.5])
### Your code starts here.
### Your code ends here.
Percentile levels: 5.0 95.0
90% interval: 47.9 to 52.4
11.3.2. Estimating a Median#
The median is a natural summary of order value, because a few very large orders pull the mean upward but leave the median alone. The median of the 400 sampled orders is £300.52. This is a point estimate: one number that stands in for the median of all orders.
To describe its uncertainty, generate 5,000 resamples of the 400 orders, each drawn with replacement and each the same size as the original sample, and record the median of each. Each repetition gives a statistic, not a new order. The function bootstrap_stats in the setup cell does this with a seeded random generator.
median_stats = bootstrap_stats(order_values, np.median, 5000, seed=1131)
med_lo, med_hi = central_interval(median_stats, 95)
print('Sample median: ', round(np.median(order_values), 2))
print('95% interval: ', round(med_lo, 2), 'to', round(med_hi, 2))
print('Below the median:', round(np.median(order_values) - med_lo, 2))
print('Above the median:', round(med_hi - np.median(order_values), 2))
Sample median: 300.52
95% interval: 278.87 to 310.85
Below the median: 21.64
Above the median: 10.34
The 95% interval for the population median is about £278.87 to £310.85. It reaches £21.64 below the sample median and £10.34 above it, so it is not symmetric. The histogram shows the 5,000 bootstrap medians, with the gold bar marking the central 95%.
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.hist(median_stats, bins=30, color='steelblue', edgecolor='white')
ax.plot([med_lo, med_hi], [0, 0], color='gold', lw=8, solid_capstyle='butt', label='Central 95%')
ax.set_xlabel('Median order value of a resample (pounds)', fontsize=12)
ax.set_ylabel('Number of resamples', fontsize=12)
ax.set_title('Bootstrap medians of order value', fontsize=13)
ax.legend()
plt.show()
This interval estimates the median of the population of orders, not the range that holds 95% of individual orders. Individual orders vary far more than their median does. The plot has no line for the true median, because in a real analysis you do not know it, and so you cannot check whether this particular interval captured it. The 95% describes the method across fresh samples. Here the sample came from a known list of 33,398 orders, so you can look afterwards: the median of that full list is £301.02, inside this interval. A real analysis has no such list to check against.
For the manager: the median order value is likely between about £279 and £311, so a planning figure of £300 is reasonable. A claim that the median is £250 or £350 would not fit this sample.
11.3.2.1. Practice#
### Exercise: Interval for a Median
# A help desk recorded the length of 15 calls in minutes.
# 1. Resample call_minutes with replacement 2,000 times using ex_rng.choice,
# at the same size as the sample, and collect each resample's median.
# 2. Compute the central 95% interval with np.percentile(..., method='nearest').
# 3. Print the sample median, the interval, and whether a median call
# length of 10 minutes is inside the interval.
# Print exactly:
# Sample median: 7.0
# 95% interval: 5.0 to 9.0
# 10 minutes inside the interval: False
import numpy as np
call_minutes = np.array([4, 7, 5, 12, 6, 9, 3, 8, 15, 6, 5, 22, 7, 4, 10])
ex_rng = np.random.default_rng(21)
### Your code starts here.
### Your code ends here.
Sample median: 7.0
95% interval: 5.0 to 9.0
10 minutes inside the interval: False
11.3.3. Estimating a Mean#
The mean order value matters for revenue: total sales are the number of orders times the mean. The sample mean is £373.02, higher than the median because of the large orders. Apply the same recipe with np.mean as the statistic.
mean_stats = bootstrap_stats(order_values, np.mean, 5000, seed=1132)
mean_lo, mean_hi = central_interval(mean_stats, 95)
print('Sample mean: ', round(np.mean(order_values), 2))
print('95% interval: ', round(mean_lo, 2), 'to', round(mean_hi, 2))
inside = np.mean((order_values >= mean_lo) & (order_values <= mean_hi))
print('Share of individual orders inside this interval:', round(inside, 3))
Sample mean: 373.02
95% interval: 332.21 to 418.96
Share of individual orders inside this interval: 0.13
The 95% interval for the population mean is about £332.21 to £418.96. Only 13.0% of the individual orders in the sample fall inside it, which is a reminder that the interval describes the average, not the orders. As with the median, the full list of 33,398 orders allows a check afterwards: its mean is £393.77, inside this interval. The next figure puts the two distributions side by side.
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
axes[0].hist(order_values, bins=np.arange(0, 4600, 200), color='steelblue', edgecolor='white')
axes[0].set_xlabel('Order value (pounds)', fontsize=12)
axes[0].set_ylabel('Number of orders', fontsize=12)
axes[0].set_title('Individual orders: skewed', fontsize=13)
axes[1].hist(mean_stats, bins=30, color='steelblue', edgecolor='white')
axes[1].plot([mean_lo, mean_hi], [0, 0], color='gold', lw=8, solid_capstyle='butt')
axes[1].set_xlabel('Mean order value of a resample (pounds)', fontsize=12)
axes[1].set_ylabel('Number of resamples', fontsize=12)
axes[1].set_title('Bootstrap means: bell-shaped', fontsize=13)
plt.tight_layout()
plt.show()
The orders on the left are skewed, but the bootstrap means on the right form a symmetric bell. The Central Limit Theorem (CLT), introduced in Descriptive Distributions, helps explain this: for independent observations from a population with finite variance, the sampling distribution of the mean becomes approximately normal as the sample size grows. Strong skew or extreme values can require a much larger sample, and n = 30 is not a universal guarantee. The histogram on the right describes how the sample mean varies from sample to sample, while the one on the left describes how individual orders vary.
The bell shape applies to the mean. The distribution of a median or another statistic can look quite different, which is one reason to plot the bootstrap distribution before trusting an interval.
11.3.3.1. Practice#
### Exercise: The Mean Versus Individual Orders
# A store's random sample of 20 order values (in dollars) is in ex_values.
# 1. Resample ex_values with replacement 2,000 times using ex_rng.choice,
# at the same size as the sample, and collect each resample's mean.
# 2. Compute the central 95% interval with np.percentile(..., method='nearest').
# 3. Compute the share of the 20 individual orders that fall inside the interval.
# 4. Print the sample mean, the interval rounded to 2 decimals, and the share.
# Print exactly:
# Sample mean: 50.9
# 95% interval: 46.15 to 57.05
# Share of individual orders inside: 0.4
import numpy as np
ex_values = np.array([38, 52, 45, 61, 47, 55, 40, 49, 58, 44, 51, 46, 63, 42, 50, 95, 36, 48, 57, 41])
ex_rng = np.random.default_rng(31)
### Your code starts here.
### Your code ends here.
Sample mean: 50.9
95% interval: 46.15 to 57.05
Share of individual orders inside: 0.4
11.3.4. Confidence Level and Width#
Why 95%? There is a trade-off. A higher confidence level gives a wider interval, so it is harder for the method to miss the parameter, but the answer is less specific. A lower level gives a narrower, more specific interval that misses more often. A narrower interval is more precise: it pins the parameter down more tightly. Precision is not accuracy, though. A precise interval from a biased sample can be narrow and still miss the parameter.
You can see this from a single bootstrap distribution. Leaving 10% in each tail instead of 2.5% shortens the interval.
lo95, hi95 = central_interval(mean_stats, 95)
lo80, hi80 = central_interval(mean_stats, 80)
print('95% interval:', round(lo95, 2), 'to', round(hi95, 2), ' width', round(hi95 - lo95, 2))
print('80% interval:', round(lo80, 2), 'to', round(hi80, 2), ' width', round(hi80 - lo80, 2))
95% interval: 332.21 to 418.96 width 86.75
80% interval: 345.34 to 402.54 width 57.2
The 80% interval, about £345.34 to £402.54, is narrower than the 95% interval of £332.21 to £418.96. From the same bootstrap distribution, an 80% central interval can never be wider than the 95% one; ties could make the widths equal. The narrower interval is more specific but would miss the true mean more often over repeated samples.
To get a narrower interval at the same confidence level, collect more data. A larger random sample carries more information about the population. To see the effect, compare the intervals from a random subsample of 100 orders and from all 400.
small_sample = orders.sample(100, random_state=11)['order_value'].to_numpy()
small_stats = bootstrap_stats(small_sample, np.mean, 5000, seed=1133)
small_lo, small_hi = central_interval(small_stats, 95)
print('100 orders: mean', round(small_sample.mean(), 2),
' 95% interval', round(small_lo, 2), 'to', round(small_hi, 2),
' width', round(small_hi - small_lo, 2))
print('400 orders: mean', round(order_values.mean(), 2),
' 95% interval', round(mean_lo, 2), 'to', round(mean_hi, 2),
' width', round(mean_hi - mean_lo, 2))
100 orders: mean 383.58 95% interval 302.34 to 496.42 width 194.08
400 orders: mean 373.02 95% interval 332.21 to 418.96 width 86.75
With 100 orders the 95% interval for the mean runs from £302.34 to £496.42, a width of £194.08. With all 400 orders the width falls to £86.75, a little under half. Four times the data cut the width to about half or a bit less, which fits the pattern from Sampling Variability: the variability of a mean shrinks with the square root of the sample size.
Do more resamples have the same effect? No. The number of resamples B is a simulation setting. The number of orders n is the information you have. The next cell builds the 95% interval for the mean from all 400 orders using different values of B and two different seeds each.
print(' B seed lower upper width')
for reps in [200, 1000, 5000, 20000]:
for seed in [1, 2]:
stats = bootstrap_stats(order_values, np.mean, reps, seed=seed)
lo, hi = central_interval(stats, 95)
print(f'{reps:>5} {seed:>4} {lo:>7.2f} {hi:>7.2f} {hi - lo:>6.2f}')
B seed lower upper width
200 1 337.85 416.86 79.00
200 2 335.01 415.66 80.65
1000 1 335.44 418.34 82.90
1000 2 334.71 417.84 83.13
5000 1 334.55 418.87 84.31
5000 2 333.09 419.09 86.00
20000 1 334.00 418.96 84.96
20000 2 333.31 418.81 85.49
With few resamples the endpoints move noticeably from one seed to the next. With thousands, the two seeds agree closely. With only 200 resamples the interval comes out a little narrow (widths of about 79 to 81), because so few resamples land in the far tails; by a few thousand resamples the width settles near 85. Beyond that, the width stays about the same however large B grows, far from the narrowing that more data gives. More resamples reduce simulation noise in the endpoints; they cannot repair an unrepresentative sample or add information the 400 orders do not contain. Five thousand resamples is plenty for the intervals in this chapter.
11.3.4.1. Practice#
### Exercise: More data or more resamples?
# order_values holds the 400 sampled order values (pounds). Their order is random,
# so the first 100 are a random sample of 100 orders.
# 1. Write a function that builds B bootstrap means of some data with rng.choice
# and returns the width of the central 95% interval (method='nearest').
# 2. Using the one generator rng, in this order, find the width for:
# the first 100 orders with B = 1000, the first 100 with B = 4000,
# and all 400 with B = 1000.
# 3. Print the three widths rounded to 2 decimals.
# Print exactly:
# n = 100, B = 1000: width 197.74
# n = 100, B = 4000: width 198.94
# n = 400, B = 1000: width 87.3
import numpy as np
import pandas as pd
order_values = pd.read_csv('../../data/online_retail_orders.csv')['order_value'].to_numpy()
rng = np.random.default_rng(1)
### Your code starts here.
### Your code ends here.
n = 100, B = 1000: width 197.74
n = 100, B = 4000: width 198.94
n = 400, B = 1000: width 87.3
11.3.5. Estimating a Proportion#
The retailer also wants the population proportion of large orders, those worth more than £500. In the sample, 75 of the 400 orders have large_order equal to 1. A proportion is a mean of 0s and 1s: adding the 1s counts the large orders, and dividing by the number of orders gives the share. So the same bootstrap recipe applies, with np.mean as the statistic and the column of 0s and 1s as the data.
print('Large orders:', large_flags.sum(), 'of', len(large_flags))
print('Sample proportion:', large_flags.mean())
prop_stats = bootstrap_stats(large_flags, np.mean, 5000, seed=1135)
prop_lo, prop_hi = central_interval(prop_stats, 95)
print('95% interval:', round(prop_lo, 3), 'to', round(prop_hi, 3), ' width', round(prop_hi - prop_lo, 3))
Large orders: 75 of 400
Sample proportion: 0.1875
95% interval: 0.152 to 0.225 width 0.073
The sample proportion is 0.1875, or 18.75%. The 95% interval is about 0.152 to 0.225, or 15.2% to 22.5%, for the proportion of all orders that are large. The width is 0.073, about 7.3 percentage points. This is an interval for a share of orders, not a prediction for any one order.
Suppose a marketing report claims that at least 20% of orders are large. You can compare the claim with the interval.
for claim in [0.20, 0.30]:
inside = prop_lo <= claim <= prop_hi
print(f'Claimed proportion {claim}: inside the 95% interval? {inside}')
lo80, hi80 = central_interval(prop_stats, 80)
print('80% interval:', round(lo80, 3), 'to', round(hi80, 3))
Claimed proportion 0.2: inside the 95% interval? True
Claimed proportion 0.3: inside the 95% interval? False
80% interval: 0.162 to 0.212
The value 0.20 lies inside the 95% interval (0.152 to 0.225), and also inside the 80% interval (0.162 to 0.212). The data therefore do not rule out a proportion of 20%. That is as far as the interval goes. It does not show that the proportion is 20% or higher; the sample proportion, 18.75%, is in fact below 20%, and many values under 20% are also plausible. By contrast, 0.30 is far outside the interval, so a claim that 30% of all orders are large does not fit these data.
The full list of 33,398 orders allows a check afterwards: 21.6% of them are large. The 20% claim happens to be true, even though the sample proportion was below 20%. The sample alone could not have shown that; “inside the interval” meant “not ruled out”, and that was the right conclusion.
In general: a value inside the interval is plausible, a value outside is hard to reconcile with the sample, and neither case proves anything about the exact value. Before acting on the 20% claim, the retailer should weigh what a wrong decision would cost.
11.3.5.1. Practice#
### Exercise: Interval for a proportion
# 1. Resample the 40 flags below with replacement 2,000 times, using ex_rng.choice.
# 2. Compute the proportion of 1s in each resample, then the 95% interval with np.percentile(..., method='nearest').
# 3. Print the sample proportion, the interval, and whether 0.60 is inside it.
# Print exactly:
# Sample proportion: 0.35
# 95% interval: 0.2 to 0.5
# 0.60 inside the interval: False
import numpy as np
# Survey of 40 customers: 1 = would order again, 0 = would not.
ex_flags = np.array([1] * 14 + [0] * 26)
ex_rng = np.random.default_rng(7)
### Your code starts here.
### Your code ends here.
Sample proportion: 0.35
95% interval: 0.2 to 0.5
0.60 inside the interval: False
11.3.6. Limits of the Percentile Method#
Before an interval supports a management decision, check the data and the process that produced it.
Define the population and the statistic. A median, a mean, and a proportion answer different questions. State the units and the period the population covers, for example all orders this year.
Check the original sample. The method assumes a random sample. A large convenience sample can still be biased, and resampling cannot recover customers or orders that are systematically missing from the data.
Respect dependence. This chapter resamples rows as if they were independent. If one customer placed several of the orders, or the orders came from a few stores in clusters, or they form a time series, the rows are related and a different resampling design is needed. Some customers in this chapter’s data placed several orders, but the 400 orders were drawn at random from the list of orders, so resampling orders matches how the sample was drawn.
Separate n from B. A few thousand resamples are enough for teaching. For a consequential analysis, check that the endpoints are stable with more. Repeating the bootstrap does not increase the original sample size.
Watch difficult statistics. A resample cannot contain a value larger than the sample’s largest value or smaller than its smallest. Extremes such as the maximum are therefore badly handled, as the next cell shows. Very small samples, strong bias, and statistics that depend on a few values can also give poor coverage. A bell-shaped histogram alone does not prove the interval is valid.
Interpret a threshold cautiously. If a proposed value lies inside an interval, the data do not rule it out. That does not prove the value, or show that a supplier meets a requirement. Report the interval together with the requirement and the cost of a wrong decision.
Here is the maximum order value. The sample’s largest order is £4,406.61. The population’s largest order is almost certainly larger, because the sample is only part of it.
max_stats = bootstrap_stats(order_values, np.max, 5000, seed=1136)
max_lo, max_hi = central_interval(max_stats, 95)
print('Sample maximum:', order_values.max())
print('Largest bootstrap maximum:', max_stats.max())
print('Share of resamples whose maximum equals the sample maximum:', round(np.mean(max_stats == order_values.max()), 3))
print('95% interval for the maximum:', round(max_lo, 2), 'to', round(max_hi, 2))
Sample maximum: 4406.61
Largest bootstrap maximum: 4406.61
Share of resamples whose maximum equals the sample maximum: 0.646
95% interval for the maximum: 1894.01 to 4406.61
About 65% of the resamples have exactly the sample maximum as their maximum, and none can exceed it. The upper end of the “interval” is just the sample maximum, so it can never reach larger values that exist in the population. The method cannot say how large the biggest order could be.
Finally, what does “95% confidence” mean? It describes the procedure, not this one interval. Over many fresh random samples, about 95% of the intervals built this way would contain the fixed population value. Once you compute an interval from your sample, it either contains the true value or it does not. Do not say there is a 95% probability that the parameter lies in it, and do not say that 95% of orders fall inside it. The coverage is also approximate, and it depends on the sample and on the statistic.
11.3.7. Section Practice#
Use this exercise to check the main workflow of the section.
### Exercise: Practice Confidence Intervals
# 1. Build 2,000 bootstrap means with rng.choice(ex_orders, size=len(ex_orders), replace=True).
# The seed is set once; do not reset it in the loop.
# 2. Compute the 95% confidence interval with np.percentile(..., method='nearest').
# 3. Is $60 inside the interval? Print the sample mean, the interval, and the answer.
# Print exactly:
# Sample mean: 50.1
# 95% CI: 47.15 to 53.05
# $60 inside the interval: False
import numpy as np
import pandas as pd
# A store's random sample of 20 order values (in dollars). A manager claims
# the average order value of all orders is $60.
ex_orders = pd.Series([42, 55, 48, 61, 39, 52, 47, 58, 44, 50, 63, 41, 49, 56, 45, 53, 46, 51, 59, 43])
rng = np.random.default_rng(1)
### Your code starts here.
### Your code ends here.
Sample mean: 50.1
95% CI: 47.15 to 53.05
$60 inside the interval: False