Comprehensive Guide to Confidence Intervals and Hypothesis Testing Inversion
Python Environment and Initial Data Preparation
The core Python computational stack for hypothesis testing and confidence interval estimation comprises three primary libraries:
pandas(imported aspd) for tabular data ingestion, filtering, and summary statistics.numpy(imported asnp) for vectorized array manipulation and numerical operations such as square roots.scipy.stats(imported fromscipy) for computing standard normal probability density functions, cumulative distribution functions, and percent point functions.
Python import setup:
import pandas as pd
import numpy as np
from scipy import stats
The High Time Resolution Universe (HTRU) Pulsar Survey dataset is utilized to analyze the physical properties of pulsars, specifically treating confirmed pulsars as a random sample of all pulsars in the universe.
- Remote dataset location:
"https://github.com/UM-Data-Science-101/data/raw/refs/heads/main/Old/HTRU_2.csv" - Attribute column names assigned during loading:
"intensity""profile_sd""profile_excess_kurtosis""profile_skewness""snr_mean""snr_sd""snr_excess_kurtosis""snr_skewness""pulsar"
- Remote dataset location:
Loading and filtering data in Python:
htru_url = ("https://github.com/UM-Data-Science-101/data/raw/" "refs/heads/main/Old/HTRU_2.csv")
htru = pd.read_csv(htru_url, names=["intensity", "profile_sd", "profile_excess_kurtosis", "profile_skewness", "snr_mean", "snr_sd", "snr_excess_kurtosis", "snr_skewness", "pulsar"])
pulsars = htru.loc[htru["pulsar"] == 1]
n = len(pulsars)
- The resulting sample size of confirmed pulsars is .
Two-Sided Hypothesis Testing for Population Mean Intensity
Two-sided hypothesis testing evaluates whether an unknown population expected value equals a specific hypothesized constant , against the alternative that it differs from :
- Null hypothesis:
- Alternative hypothesis:
Computing sample statistics for pulsar intensity:
- Sample mean (observed statistic):
observed_statistic = pulsars["intensity"].mean() - Sample variance:
s2 = pulsars["intensity"].var() - Standard error of the mean:
standard_error = np.sqrt(s2 / n)
- Sample mean (observed statistic):
Standard error computation formula:
Decision rule for a significance level (5% probability of committing a Type I error):
- Under the standard normal approximation, reject if the observed sample mean lies more than 2 standard errors away from the hypothesized value .
- Rejection threshold: reject if , where the test statistic is defined by:
Test 1: Hypothesized mean
- Hypotheses: vs
Computed test statistic:
- Conclusion: Because , the test statistic falls deep within the rejection region. Reject the null hypothesis .
Test 2: Hypothesized mean
- Hypotheses: vs
Computed test statistic:
- Conclusion: Because , the test statistic does not exceed the critical boundary. Fail to reject the null hypothesis .
Test 3: Hypothesized mean
- Hypotheses: vs
Computed test statistic:
Conclusion: Because , the test statistic falls into the rejection region. Reject the null hypothesis .
Mathematical implication: Any hypothesized mean will yield a -score greater than , and any will yield a -score less than . Therefore, all values and are rejected at .
Theoretical Foundations and Derivation of Confidence Intervals
Point estimation principles:
- For independent and identically distributed (I.I.D.) data, the sample mean is an unbiased estimator for , meaning .
- By the Law of Large Numbers (LLN), as the sample size increases, converges in probability to the true population mean .
- Because a single point estimate provides no measure of uncertainty, an interval of plausible parameter values is required.
Inversion of hypothesis tests:
- A confidence interval (CI) is formally defined as the set of all null hypothesized values that fail to be rejected at significance level .
- Testing the family of hypotheses versus across all real numbers yields the confidence interval.
- Setting corresponds directly to a 95% confidence interval.
Algebraic derivation of acceptance regions:
- Fix such that the two-tailed rejection region is , where is the critical value.
- The acceptance region (region of non-rejection) for a test statistic with standard error is defined by:
Substituting the -score formula:
Defining for algebraic convenience:
Multiplying across all sides by (where ):
Subtracting from all sides:
Multiplying through by (reversing inequalities):
In interval notation, the set of non-rejected values is:
For , the standard critical value is (via the empirical rule approximation), yielding the classic 95% confidence interval formula:
Calculating Confidence Intervals for the Mean
- 95% Confidence Interval for pulsar mean intensity (, ):
(round(observed_statistic - 2 * standard_error, 2), round(observed_statistic + 2 * standard_error, 2))
# Output: (55.21, 58.17)
Lower bound:
Upper bound:
Interpretation: At an error tolerance of , any hypothesis smaller than or larger than is rejected. The plausible range for is .
- 99.7% Confidence Interval for pulsar mean intensity (, ):
Formulated to limit Type I error to no more than 0.3% of tests.
(round(observed_statistic - 3 * standard_error, 2), round(observed_statistic + 3 * standard_error, 2))
# Output: (54.47, 58.91)
- Lower bound:
- Upper bound:
- Precision vs. Confidence Trade-off: The 99.7% interval contains substantially more values than the 95% interval . Decreasing the permissible Type I error rate widens the interval, reducing precision.
Confidence Intervals for Population Proportions
Standard error differences between single-hypothesis testing and interval estimation:
- Under an isolated null hypothesis (e.g., ), the standard error is evaluated directly at the hypothesized null parameter:
When testing an entire continuum of hypotheses simultaneously to construct a confidence interval, is estimated from data using the sample proportion :
Case Study: Proportion of Michigan owner-occupied homes with a mortgage:
- Source data: American Community Survey (ACS) Public Use Microdata Sample (PUMS) dataset:
- URL:
"https://github.com/UM-Data-Science-101/data/raw/refs/heads/main/Old/pums_short.csv.gz" - Filtering criteria:
- State identifier:
ST == 26(Michigan) - Housing tenure:
TEN.isin([1, 2])(owner-occupied housing) - Mortgage status:
TEN == 1indicates owned with a mortgage or loan;TEN == 2indicates owned free and clear
Python implementation for ACS mortgage data:
pums_url = ("https://github.com/UM-Data-Science-101/data/raw/" "refs/heads/main/Old/pums_short.csv.gz")
homes = pd.read_csv(pums_url)
owned = homes.loc[(homes["ST"] == 26) & homes["TEN"].isin([1, 2])]
mortgage = owned["TEN"] == 1
phat = mortgage.mean()
se = np.sqrt(phat * (1 - phat) / len(owned))
ci_95 = (round(phat - 2 * se, 3), round(phat + 2 * se, 3))
# Output: (0.554, 0.578)
- The 95% confidence interval for the proportion of Michigan owner-occupied homes with an active mortgage is .
Critical Values for Arbitrary Significance Levels
Origin of standard multipliers:
- Multipliers and are approximations based on the Gaussian empirical rule (68-95-99.7 rule).
- For arbitrary confidence levels , the critical value must satisfy:
Due to the symmetry of the normal distribution, the probability in each tail is . Therefore, the cumulative probability up to is:
Finding critical values in Python:
- The function
scipy.stats.norm.ppf(q)computes the quantile (percent point function) corresponding to a lower-tail cumulative probability . - For a 90% confidence interval ():
- Area in each tail:
- Target quantile:
- Computation:
a = stats.norm.ppf(0.95)
- The function
Computing the 90% confidence interval for the mortgage proportion:
a = stats.norm.ppf(0.95)
ci_90 = (round(a, 3), round(phat - a * se, 3), round(phat + a * se, 3))
# Output: (1.645, 0.556, 0.576)
- The critical value is .
- The 90% confidence interval is , which is narrower than the 95% interval .
Empirical Verification of Confidence Interval Coverage Rates
Definition of coverage rate:
- The coverage rate is the long-run proportion of repeated independent random samples from the same population in which the computed confidence interval contains the true population parameter.
- A correctly calibrated confidence interval must achieve a coverage rate equal to .
Simulation design:
- Population: The entire set of Michigan owner-occupied homes from the ACS dataset is treated as the true finite population.
- True population parameter:
p_true = mortgage.mean(). - Sample size per trial: .
- Number of Monte Carlo iterations: .
Python implementation of coverage simulation:
p_true = mortgage.mean()
def ci_covers(n, confidence):
sample = mortgage.sample(n)
phat = sample.mean()
se = np.sqrt(phat * (1 - phat) / n)
a = stats.norm.ppf(1 - (1 - confidence) / 2)
return (phat - a * se <= p_true) and (p_true <= phat + a * se)
coverage_90 = pd.Series([ci_covers(200, 0.90) for _ in range(0, 10000)])
coverage_99 = pd.Series([ci_covers(200, 0.99) for _ in range(0, 10000)])
Simulation results for 90% confidence level:
- First 5 sampled outcomes (
coverage_90.head()): - Index 0:
True - Index 1:
False - Index 2:
True - Index 3:
True - Index 4:
True - Empirical coverage rate:
coverage_90.mean()= (approximately 89.91%, matching the theoretical 90% target).
- First 5 sampled outcomes (
Simulation results for 99% confidence level:
- First 5 sampled outcomes (
coverage_99.head()): - Index 0:
True - Index 1:
True - Index 2:
True - Index 3:
True - Index 4:
True - Empirical coverage rate:
coverage_99.mean()= (approximately 98.92%, matching the theoretical 99% target).
- First 5 sampled outcomes (
Structural Characteristics and Methodological Notes
Interval estimators:
- Confidence intervals serve as interval estimators, outputting a set of plausible values for an unknown parameter rather than a single point estimate.
Central Limit Theorem approximations:
- The use of standard normal critical values relies on the Central Limit Theorem (CLT) to approximate the distribution of the test statistic under the null hypothesis.
- Consequently, confidence intervals constructed via the CLT have approximate coverage rather than exact nominal coverage.
- The accuracy of this approximation depends directly on the sample size ; smaller samples exhibit greater deviation from nominal coverage.
Duality between confidence intervals and p-values:
- There is a direct mathematical equivalence between hypothesis testing, p-values, and confidence intervals:
- Any hypothesized value that lies inside a confidence interval has a p-value strictly greater than ().
- Any hypothesized value that falls outside the confidence interval has a p-value less than or equal to ().