Inference Module
The xpyrment.analyze.inference module contains submodules and components for inference.
inference
Statistical inference engines, frameworks, and decision-making systems.
This package provides standard and state-of-the-art inferential frameworks for computing treatment effects, confidence bounds, and decision probabilities.
Submodules:
- frequentist: Standard hypothesis tests including Welch's t-test and Mann-Whitney U rank sums.
- bayesian: Conjugate posterior models (Beta-Binomial, Normal-Normal) and expected loss decisions.
- sequential: Always-Valid Confidence Intervals (AVCIs) derived from mSPRT boundaries.
- bootstrap: Non-parametric percentile and BCa resampling estimators.
- router: Automated matching between metric structures, designs, and calculation engines.
| MODULE | DESCRIPTION |
|---|---|
bayesian |
Bayesian conjugate models and decision-making parameters. |
bootstrap |
Non-parametric bootstrap resampling and confidence interval estimation (Block 54). |
frequentist |
Frequentist parametric and non-parametric statistical tests. |
router |
Intelligent statistical inference engine router. |
sequential |
Sequential inference, continuous peeking, and always-valid confidence intervals (AVCI). |
| CLASS | DESCRIPTION |
|---|---|
BayesianInference |
Computes Bayesian posterior parameters, probability of being best, expected loss, and ROPE. |
SequentialInference |
Computes sequential monitoring bounds and always-valid confidence intervals (AVCIs). |
| FUNCTION | DESCRIPTION |
|---|---|
run_bootstrap_ci |
Computes non-parametric bootstrap confidence intervals for arbitrary complex metrics. |
run_block_bootstrap_ci |
Computes non-parametric block bootstrap confidence intervals for dependent/autocorrelated data. |
run_welch_t_test |
Performs Welch's t-test for difference of means with unequal variances. |
run_mann_whitney_u |
Performs nonparametric Mann-Whitney U test for ordinal or non-normal continuous data. |
route_inference_engine |
Routes to the correct statistical engine based on metric and design types. |
BayesianInference
Computes Bayesian posterior parameters, probability of being best, expected loss, and ROPE.
Bayesian inference offers a direct, probabilistic interpretation of treatment effects, avoiding the complex and frequently misunderstood reasoning of frequentist p-values. It provides answers to intuitive questions like: "What is the probability that Treatment B is superior to Control A?" or "What is the expected loss if I ship Treatment B?"
Mathematical Formulation of Conjugate Models
Conjugate models allow the analytical calculation of posterior distributions without requiring expensive Markov Chain Monte Carlo (MCMC) sampling:
- Beta-Binomial Model (for binary conversion rates, \(p \in [0, 1]\)):
- Prior: \(p \sim \text{Beta}(\alpha_0, \beta_0)\) (e.g., \(\text{Beta}(1, 1)\) for a flat, uniform prior).
- Likelihood: Binomial (\(k\) conversions out of \(n\) trials).
- Posterior: $$ p|k, n \sim \text{Beta}(\alpha_0 + k, \ \beta_0 + n - k) $$
- Normal-Normal Model (for continuous averages, \(\mu \in \mathbb{R}\), with known variance \(\sigma^2\)):
- Prior: \(\mu \sim \mathcal{N}(\mu_0, \sigma_0^2)\).
- Likelihood: Normal (\(N\) observations with sample mean \(\bar{Y}\) and variance \(\sigma^2\)).
- Posterior: $$ \mu| \bar{Y} \sim \mathcal{N}(\mu_N, \sigma_N^2) $$ where the posterior precision (\(1/\sigma_N^2\)) and posterior mean (\(\mu_N\)) are calculated as: $$ \frac{1}{\sigma_N^2} = \frac{1}{\sigma_0^2} + \frac{N}{\sigma^2} \quad \text{and} \quad \mu_N = \sigma_N^2 \left( \frac{\mu_0}{\sigma_0^2} + \frac{N\bar{Y}}{\sigma^2} \right) $$
- Gamma-Poisson Model (for discrete counts/rates, \(\lambda \in [0, \infty)\)):
- Prior: \(\lambda \sim \text{Gamma}(\alpha, \beta)\) (shape \(\alpha\), rate \(\beta\)).
- Likelihood: Poisson (\(k\) total counts across \(n\) units).
- Posterior: $$ \lambda|k, n \sim \text{Gamma}(\alpha + k, \beta + n) $$
Decision-Making Criteria and Analytics
- Probability of Being Best (PBB): The probability that the treatment parameter \(\theta_T\) is strictly greater than the control parameter \(\theta_C\): $$ \text{PBB} = P(\theta_T > \theta_C) = \int_{-\infty}^{\infty} f_C(\theta_C) [1 - F_T(\theta_C)] \, d\theta_C $$
- Expected Loss (\(L\)): The expected metric drop if the treatment is shipped but is actually inferior: $$ L(T) = \mathbb{E}[\max(\theta_C - \theta_T, 0)] = \int_{-\infty}^{\infty} \int_{-\infty}^{\theta_C} (\theta_C - \theta_T) f_T(\theta_T) f_C(\theta_C) \, d\theta_T \, d\theta_C $$
| ATTRIBUTE | DESCRIPTION |
|---|---|
model_type |
Conjugate model pairing label. Options:
TYPE:
|
| PARAMETER | DESCRIPTION |
|---|---|
model_type
|
Conjugate model to use (
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
estimate_posterior |
Estimates conjugate posterior distributions based on prior settings and raw observations. |
Source code in src\xpyrment\analyze\inference\bayesian.py
estimate_posterior
Estimates conjugate posterior distributions based on prior settings and raw observations.
Performs the analytical conjugate update formulas, then computes PBB, Expected Loss, and credible intervals.
| PARAMETER | DESCRIPTION |
|---|---|
prior_params
|
Prior parameters (e.g.,
TYPE:
|
observed_data
|
Observed outcomes (conversions and counts, or means and variances).
TYPE:
|
exact
|
Whether to use numerical integration for exact PBB and Expected Loss. If False, uses Monte Carlo sampling (20k samples). Defaults to True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Posterior distribution parameters, credible intervals, and decision metrics.
TYPE:
|
Source code in src\xpyrment\analyze\inference\bayesian.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
SequentialInference
Computes sequential monitoring bounds and always-valid confidence intervals (AVCIs).
In traditional experimentation, looking at confidence intervals before the test finishes (peeking) is statistically hazardous. Always-Valid Confidence Intervals (AVCIs) solve this by providing a sequence of intervals that cover the true parameter \(\\theta\) at all steps \(n \\ge 1\) simultaneously with a probability of at least \(1 - \\alpha\).
Mathematical Definition and Boundary Formulas
Let \(C_n\) be the confidence interval calculated at sample size \(n\). For any nominal error rate \(\\alpha \\in (0, 1)\): $$ \mathbb{P} \left( \forall n \ge 1, \ \theta \in C_n \right) \ge 1 - \alpha $$ This is an incredibly powerful property: it allows the experimenter to continuously plot the confidence interval over time, and if the interval does not contain zero at any point, the experiment can be stopped immediately with a guaranteed Type I error rate controlled at \(\\alpha\).
AVCI Derivation from mSPRT: By inverting the mixture Sequential Probability Ratio Test (mSPRT) statistic for a normally distributed metric with unit baseline variance \(\\sigma^2\) and mixing tuning parameter \(\\tau^2\) (representing prior effect variance), the always-valid confidence interval at step \(n\) is: $$ C_n = \left[ \bar{Y}_n - W_n, \ \bar{Y}_n + W_n \right] $$ where \(\\bar{Y}_n\) is the observed sample mean difference, and the sequential margin of error \(W_n\) is: $$ W_n = \sqrt{\frac{2\sigma^2(\sigma^2 + n\tau^2)}{n^2\tau^2} \ln\left( \frac{1}{\alpha} \sqrt{\frac{\sigma^2 + n\tau^2}{\sigma^2}} \right)} $$ Properties of \(W_n\): - For very small \(n\), \(W_n\) is wider than the traditional fixed-sample Wald margin of error (\(z_{1-\\alpha/2} \\sigma / \\sqrt{n}\)), which mathematically penalizes and compensates for the continuous peeking. - As \(n \\to \\infty\), the sequential margin \(W_n\) asymptotically matches the rate of the traditional interval, ensuring zero long-term loss in statistical efficiency.
| METHOD | DESCRIPTION |
|---|---|
calculate_always_valid_ci |
Computes continuous monitoring boundaries to prevent alpha inflation from peeking. |
calculate_always_valid_ci
Computes continuous monitoring boundaries to prevent alpha inflation from peeking.
Calculates the exact sequential margin of error (\(W_n\)) at a given sample size, yielding always-valid confidence bounds around the observed effect size.
| PARAMETER | DESCRIPTION |
|---|---|
sample_size
|
The current accumulated number of units/trials (\(n\)).
TYPE:
|
alpha
|
The target false-positive rate (\(\\alpha\)).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
A tuple of floats
TYPE:
|
Source code in src\xpyrment\analyze\inference\sequential.py
run_bootstrap_ci
run_bootstrap_ci(
data_group: ndarray,
num_resamples: int = 2000,
confidence_level: float = 0.95,
method: str = "bca",
random_seed: Optional[int] = None,
) -> tuple
Computes non-parametric bootstrap confidence intervals for arbitrary complex metrics.
Bootstrap resampling (Efron, 1979) is a non-parametric method used to estimate the standard error and confidence intervals of an estimator (such as means, medians, ratios, or quantiles). It is particularly valuable when the underlying metric distribution is highly non-normal (e.g., bi-modal, zero-inflated, or power-law) or when the estimator's mathematical variance cannot be easily derived analytically.
Mathematical and Algorithmic Formulation
Let \mathbf{x} = (x_1, x_2, \dots, x_n) be the observed sample of size \(n\), and let \hat{\theta} = s(\mathbf{x}) be the point estimate of interest.
The bootstrap sampling distribution is constructed as follows: 1. Draw a bootstrap sample \mathbf{x}^{b} of size \(n\) by sampling uniformly with replacement from the original sample \mathbf{x}\(. 2. Calculate the bootstrap replication of the estimator: \\hat{\\theta}^{*b} = s(\\mathbf{x}^{*b})\). 3. Repeat steps 1-2 a large number of times \(B\) (where \(B = \\text{num\\_resamples}\), typically \(B \\ge 2000\)), generating a set of replicates: \{\hat{\theta}^{1}, \hat{\theta}^{2}, \dots, \hat{\theta}^{B}\}.
Confidence Interval Methods
- Percentile Bootstrap (Simple and intuitive): Sorts the bootstrap replicates in ascending order: \hat{\theta}^{(1)} \le \hat{\theta}^{(2)} \le \dots \le \hat{\theta}^{(B)}. For a confidence level of \(1 - \\alpha\) (e.g., \(0.95\) with \(\\alpha = 0.05\)), the interval endpoints are the \(\\alpha/2\) and \(1 - \\alpha/2\) percentiles of the empirical bootstrap distribution: $$ \left[ \hat{\theta}^{(\lfloor B \cdot \alpha/2 \rfloor)}, \ \hat{\theta}^{*(\lfloor B \cdot (1 - \alpha/2) \rfloor)} \right] $$
- Bias-Corrected and Accelerated (BCa) Bootstrap (Robust and accurate): Adjusts the percentile endpoints to correct for both median bias (displacement of the bootstrap distribution from the point estimate) and skewness (non-constant variance, represented by acceleration \(a\)).
- The bias-correction factor \(z_0\) is: $$ z_0 = \Phi^{-1} \left( \frac{\#\{\hat{\theta}^{*b} < \hat{\theta}\}}{B} \right) $$ where \(\\Phi^{-1}\) is the inverse cumulative distribution function of the standard normal distribution.
- The acceleration parameter \(a\) is computed using jackknife (leave-one-out) estimators: $$ a = \frac{\sum_{i=1}^{n} (\bar{\theta}{(\cdot)} - \theta{(i)})^3}{6 \left[ \sum_{i=1}^{n} (\bar{\theta}{(\cdot)} - \theta{(i)})^2 \right]^{3/2}} $$ where \(\\theta_{(i)}\) is the estimate of \(\\theta\) calculated by omitting the \(i\)-th observation, and \(\\bar{\\theta}_{(\\cdot)}\) is the average of these jackknife estimates.
- Transformed confidence percentiles are then mapped back to the sorted replicates to construct the interval.
| PARAMETER | DESCRIPTION |
|---|---|
data_group
|
The raw 1D array of observed values.
TYPE:
|
num_resamples
|
The number of bootstrap iterations (\(B\)). Defaults to 2000.
TYPE:
|
confidence_level
|
The desired confidence interval width (\(1 - \\alpha\)). Defaults to 0.95.
TYPE:
|
method
|
The bootstrap method to utilize (
TYPE:
|
random_seed
|
Random seed for numpy generator reproducibility. Defaults to None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
A tuple of floats
TYPE:
|
Source code in src\xpyrment\analyze\inference\bootstrap.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
run_block_bootstrap_ci
run_block_bootstrap_ci(
data_group: ndarray,
block_size: int,
num_resamples: int = 2000,
confidence_level: float = 0.95,
bootstrap_method: str = "moving",
ci_method: str = "percentile",
random_seed: Optional[int] = None,
) -> tuple
Computes non-parametric block bootstrap confidence intervals for dependent/autocorrelated data.
Block bootstrap methods (Moving Block and Circular Block) resample contiguous blocks of data to preserve the temporal dependence structure within the time-series or sequence.
Mathematical Formulation of Block Bootstrap
Let \(\mathbf{x} = (x_1, x_2, \dots, x_n)\) be a time series of length \(n\), and let \(b\) be the block size.
-
Moving Block Bootstrap (MBB): We define \(N = n - b + 1\) overlapping blocks of length \(b\): $$ B_i = (x_i, x_{i+1}, \dots, x_{i+b-1}), \quad \text{for } i = 1, \dots, N $$ We resample \(k = \lceil n/b \rceil\) blocks with replacement from \(\{B_1, \dots, B_N\}\), concatenate them, and truncate the final sequence to length \(n\).
-
Circular Block Bootstrap (CBB): We define \(n\) overlapping blocks of length \(b\) by wrapping the time series circularly: $$ B_i = (x_i, x_{i+1}, \dots, x_{i+b-1}), \quad \text{for } i = 1, \dots, n $$ where index wrap-around uses modulo arithmetic: \(x_j = x_{((j - 1) \bmod n) + 1}\). We resample \(k = \lceil n/b \rceil\) blocks with replacement from \(\{B_1, \dots, B_n\}\), concatenate them, and truncate the final sequence to length \(n\).
| PARAMETER | DESCRIPTION |
|---|---|
data_group
|
The raw 1D array of observed values.
TYPE:
|
block_size
|
The size of contiguous blocks (\(b\)).
TYPE:
|
num_resamples
|
The number of bootstrap iterations (\(B\)). Defaults to 2000.
TYPE:
|
confidence_level
|
The desired confidence interval width (\(1 - \alpha\)). Defaults to 0.95.
TYPE:
|
bootstrap_method
|
The block bootstrap method (
TYPE:
|
ci_method
|
The confidence interval estimation method (
TYPE:
|
random_seed
|
Random seed for numpy generator reproducibility. Defaults to None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
A tuple of floats
TYPE:
|
Source code in src\xpyrment\analyze\inference\bootstrap.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
run_welch_t_test
Performs Welch's t-test for difference of means with unequal variances.
Welch's t-test is a two-sample location test used to test the hypothesis that two populations have equal means (\(H_0: \\mu_A = \\mu_B\)). Unlike Student's t-test, Welch's t-test does not assume equal variances, making it the standard default for digital and scientific A/B testing.
| PARAMETER | DESCRIPTION |
|---|---|
group_a
|
Array of numeric outcomes for control (Group A).
TYPE:
|
group_b
|
Array of numeric outcomes for treatment (Group B).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
A dictionary containing:
-
TYPE:
|
Source code in src\xpyrment\analyze\inference\frequentist.py
run_mann_whitney_u
Performs nonparametric Mann-Whitney U test for ordinal or non-normal continuous data.
The Mann-Whitney U test evaluates the null hypothesis that the probability that a randomly drawn observation from Group B is larger than a randomly drawn observation from Group A is equal to 0.5. This test is non-parametric; it does not assume normality, making it extremely robust against extreme outliers.
| PARAMETER | DESCRIPTION |
|---|---|
group_a
|
Array of numeric outcomes for control (Group A).
TYPE:
|
group_b
|
Array of numeric outcomes for treatment (Group B).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
A dictionary containing:
-
TYPE:
|
Source code in src\xpyrment\analyze\inference\frequentist.py
route_inference_engine
route_inference_engine(
metric: BaseMetric, design_type: str
) -> str
Routes to the correct statistical engine based on metric and design types.
Selects the mathematically correct statistical test and variance estimator depending on the structural type of the metric (continuous mean, ratio of random variables, binary rate) and the user's desired inferential paradigm (Frequentist, Bayesian, Sequential, or Bootstrap).
Inference Routing Matrix
+------------------+-----------------------------+-----------------------------+-------------------------------+ | Metric Type | Frequentist | Bayesian | Sequential (mSPRT) | +------------------+-----------------------------+-----------------------------+-------------------------------+ | MeanMetric | Welch's t-test (CLT) | Normal-Normal Conjugate / | Continuous Normal Likelihood | | | | Gibbs Sampler | Ratio Martingale | +------------------+-----------------------------+-----------------------------+-------------------------------+ | RatioMetric | Delta Method t-test | Normal-Normal Delta / | Ratio-Delta Likelihood | | | (Taylor approximation) | MCMC Sampler | Ratio Martingale | +------------------+-----------------------------+-----------------------------+-------------------------------+ | BinaryMetric | Pearson Z-test (Wald CI) | Beta-Binomial Conjugate | Bernoulli Likelihood | | | / Fisher's Exact Test | (Exact posterior) | Ratio Martingale | +------------------+-----------------------------+-----------------------------+-------------------------------+
Pseudocode for Routing Logic
function route_inference_engine(metric, paradigm):
1. Extract metric_class = metric.__class__.__name__ (MeanMetric, RatioMetric, etc.)
2. Match paradigm:
- "frequentist":
If MeanMetric -> return "frequentist_welch_t_test"
If RatioMetric -> return "frequentist_ratio_delta_test"
- "bayesian":
If BinaryMetric -> return "bayesian_beta_binomial"
If MeanMetric -> return "bayesian_normal_normal"
- "sequential":
return "sequential_msprt"
- "bootstrap":
return "bootstrap_resampling"
3. Raise error if the combination is mathematically invalid.
| PARAMETER | DESCRIPTION |
|---|---|
metric
|
The target metric object (MeanMetric, RatioMetric, etc.) under analysis.
TYPE:
|
design_type
|
The desired statistical framework. Options:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Engine label string identifying the specific low-level calculation function.
TYPE:
|