Probability & Statistics

Rapid calculation of probabilities and a deep theoretical understanding of statistical testing used in product and risk environments.

Key Takeaways

  • Bayes' Theorem: $P(A|B) = \frac{P(B|A)P(A)}{P(B)}$ — base rate matters enormously in fraud/medical contexts.
  • Expected value $E[X] = \sum x \cdot P(X=x)$ — the foundation of all risk-adjusted decisions.
  • Type I error ($\alpha$) = false positive; Type II ($\beta$) = false negative; Power = $1 - \beta$.
  • A 95% CI means: 95% of CIs constructed this way contain the true parameter — not "95% chance the parameter is in this interval."
  • Binomial → Poisson approximation valid when $n$ is large and $p$ is small (rare events).
  • Power increases with larger effect size, larger sample size, lower variance, and higher $\alpha$.
  • Effect size (Cohen's d) measures practical significance — a p-value tells you the effect is real; effect size tells you if it matters.

1. Bayesian Inference & Probability

Bayes' Theorem

$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$

Use the Law of Total Probability to expand the denominator when $P(B)$ is not given directly:

$$P(B) = P(B|A)P(A) + P(B|\neg A)P(\neg A)$$

Capital One example: A fraud model has 99% specificity (true negative rate) and 80% sensitivity (true positive rate). 1 in 1,000 transactions is fraudulent. What fraction of flagged transactions are actually fraud?

$$P(\text{fraud} | \text{flagged}) = \frac{0.80 \times 0.001}{0.80 \times 0.001 + 0.01 \times 0.999} \approx 7.4\%$$

This illustrates the base rate fallacy: even a highly accurate model flags mostly non-fraud when the event is rare.

Expected Value

$$E[X] = \sum_{x} x \cdot P(X = x) \quad \text{(discrete)}$$

$$E[X] = \int_{-\infty}^{\infty} x \cdot f(x)\, dx \quad \text{(continuous)}$$

For risk/reward matrices: approve a loan when $E[\text{approve}] > E[\text{decline}]$. See Module 9 for the full expected value framework.

Combinatorics

Permutations (order matters): $P(n, k) = \frac{n!}{(n-k)!}$

Combinations (order doesn't matter): $\binom{n}{k} = \frac{n!}{k!(n-k)!}$

2. Statistical Distributions

Distribution Key Properties Use Case
Normal 68–95–99.7 rule; Z-score = $(x - \mu)/\sigma$ Many natural phenomena; CLT approximation
Binomial $n$ trials, probability $p$; $E[X]=np$, $\text{Var}=np(1-p)$ Conversion rates, click-through rates
Poisson $\lambda$ = mean rate; $P(X=k) = \frac{e^{-\lambda}\lambda^k}{k!}$ Rare events: fraud counts, defaults per day
Exponential Memoryless; $P(X > t) = e^{-\lambda t}$ Time between events (e.g., time to default)
Log-Normal $\ln(X)$ is normal; skewed right Income, transaction amounts, prices

Binomial → Poisson approximation: valid when $n$ is large and $p$ is small, with $\lambda = np$.

3. Hypothesis Testing & A/B Testing

Test Selection

Scenario Test
Two group means, unknown variance Two-sample t-test
Two proportions (large $n$) Two-proportion z-test
Categorical association Chi-square test
Three or more group means One-way ANOVA
Pre/post within same group Paired t-test

Error Types & Power

  • Type I Error ($\alpha$): False Positive — reject a true $H_0$. Set by significance level (e.g., 0.05).
  • Type II Error ($\beta$): False Negative — fail to reject a false $H_0$.
  • Statistical Power ($1 - \beta$): Probability of detecting a real effect. Target ≥ 80%.

Factors that increase power: larger sample size, larger true effect size, lower metric variance, higher $\alpha$.

Confidence Intervals

A 95% CI does not mean "95% probability the parameter is in this interval." It means: if you repeated the experiment many times, 95% of the constructed intervals would contain the true parameter.

4. Non-Parametric Tests

Use non-parametric tests when data is non-normal, ordinal, or sample sizes are small (n < 30). They make no distributional assumptions but generally have lower power than their parametric counterparts.

When to Use Non-Parametric Tests

  • Distribution is clearly skewed or has heavy tails
  • Data is ordinal (Likert scales, rankings)
  • Small samples where normality can't be verified
  • Presence of outliers that can't be removed

Key Tests

Parametric Non-Parametric Equivalent Use Case
Independent t-test Mann-Whitney U Compare two independent groups
Paired t-test Wilcoxon Signed-Rank Compare two paired/matched samples
One-way ANOVA Kruskal-Wallis Compare 3+ independent groups
Pearson correlation Spearman / Kendall rank Monotonic association between variables

Mann-Whitney U Test

Tests whether one distribution stochastically dominates another. Null hypothesis: the probability that a random draw from group A exceeds a random draw from group B equals 0.5.

from scipy import stats

group_a = [12.1, 14.3, 11.8, 13.5, 15.2]
group_b = [10.5, 11.2, 12.0, 9.8, 11.5]

stat, p_value = stats.mannwhitneyu(group_a, group_b, alternative='two-sided')
print(f"U statistic: {stat}, p-value: {p_value:.4f}")
# If p < 0.05: reject H0 that distributions are equal

Kruskal-Wallis Test

Extension of Mann-Whitney U to 3+ groups. Ranks all observations together, then tests whether groups differ in their mean rank. If significant, use Dunn's test for pairwise post-hoc comparisons.

from scipy import stats
import scikit_posthocs as sp

group1 = [23, 25, 28, 22, 27]
group2 = [31, 29, 35, 30, 33]
group3 = [19, 21, 18, 22, 20]

stat, p = stats.kruskal(group1, group2, group3)
print(f"H statistic: {stat:.3f}, p-value: {p:.4f}")

# Post-hoc if p < 0.05
data = group1 + group2 + group3
groups = [1]*5 + [2]*5 + [3]*5
print(sp.posthoc_dunn([group1, group2, group3], p_adjust='bonferroni'))

5. Effect Size

A statistically significant result tells you the effect is real. Effect size tells you how big it is. With large samples, even trivial differences become significant — always report both.

Cohen's d (Two-Group Comparison)

$$d = \frac{\mu_1 - \mu_2}{s_{\text{pooled}}}$$

where $s_{\text{pooled}} = \sqrt{\frac{(n_1-1)s_1^2 + (n_2-1)s_2^2}{n_1+n_2-2}}$

|d| Interpretation Practical Note
0.2 Small Visible under a microscope; often not actionable
0.5 Medium Noticeable in practice
0.8 Large Obvious to a casual observer
import numpy as np
from scipy import stats

def cohens_d(group1, group2):
    n1, n2 = len(group1), len(group2)
    s_pooled = np.sqrt(((n1-1)*np.var(group1, ddof=1) + (n2-1)*np.var(group2, ddof=1)) / (n1+n2-2))
    return (np.mean(group1) - np.mean(group2)) / s_pooled

control = [50, 52, 48, 53, 49]
treatment = [55, 58, 54, 57, 56]

t_stat, p = stats.ttest_ind(control, treatment)
d = cohens_d(control, treatment)
print(f"p-value: {p:.4f}, Cohen's d: {d:.3f}")
# p may be significant but d tells you if it matters

Other Effect Size Measures

  • Hedges' g — bias-corrected Cohen's d for small samples ($n < 20$)
  • r (rank-biserial) — effect size for Mann-Whitney U: $r = 1 - \frac{2U}{n_1 n_2}$
  • Eta-squared ($\eta^2$) — proportion of variance explained in ANOVA: $\eta^2 = SS_{\text{between}} / SS_{\text{total}}$
  • Odds ratio — effect size for binary outcomes in logistic models

6. Bayesian vs. Frequentist Inference

Core Philosophical Difference

Frequentist Bayesian
Probability means Long-run frequency of events Degree of belief, updated with evidence
Parameters Fixed unknown constants Random variables with prior distributions
Output Point estimate + CI, p-value Posterior distribution over parameters
Prior knowledge Not incorporated formally Explicitly encoded as prior $P(\theta)$
Small samples Can be unreliable Prior regularizes; more robust

Bayesian Update

$$P(\theta | \text{data}) = \frac{P(\text{data} | \theta) \cdot P(\theta)}{P(\text{data})}$$

Posterior $\propto$ Likelihood $\times$ Prior. As data grows, the posterior is dominated by the likelihood and the prior matters less.

Practical Implications

  • Confidence interval vs. credible interval: A 95% frequentist CI does not mean "95% probability the parameter is inside." A 95% Bayesian credible interval does — it contains the true parameter with 95% posterior probability.
  • When to prefer Bayesian: Small samples, strong domain knowledge to encode as a prior, sequential updating as data arrives, need for probability statements about parameters.
  • When to prefer frequentist: Large samples, well-understood test procedures, regulatory contexts that require p-values, computational simplicity.
  • Bayesian A/B testing: Compute $P(\theta_B > \theta_A | \text{data})$ directly — no p-value threshold required, and you can stop early without inflating Type I error.

Practice Questions

Q1: A fraud model has 99% specificity and 80% sensitivity. 1 in 1,000 transactions is fraudulent. What fraction of flagged transactions are actually fraud?

Apply Bayes' Theorem:

$P(\text{fraud}|\text{flagged}) = \frac{P(\text{flagged}|\text{fraud}) \cdot P(\text{fraud})}{P(\text{flagged})}$

$= \frac{0.80 \times 0.001}{(0.80 \times 0.001) + (0.01 \times 0.999)} = \frac{0.0008}{0.0008 + 0.00999} \approx \mathbf{7.4\%}$

Even with a very accurate model, only ~7.4% of flagged transactions are actual fraud. The low base rate (0.1%) dominates. This is the base rate fallacy — critical for fraud and medical diagnosis contexts.

Q2: You run an A/B test with α=0.05 and 80% power. Your p-value is 0.03. Should you conclude the treatment works?

p < α, so you reject H₀. But don't stop there. Also ask:

  • Was this pre-registered? Post-hoc hypothesis testing inflates false positives.
  • Multiple comparisons? If you ran 20 tests, one false positive is expected at α=0.05.
  • Practical significance? A tiny p-value can come from a trivially small effect with huge n. Check effect size.
  • Did the experiment run long enough? Novelty effects and seasonal patterns must pass through.
Q3: What is the difference between a Z-test and a t-test? When do you use each?

A Z-test assumes the population variance is known (or n > 30, using CLT). A t-test is used when the population variance is unknown and estimated from the sample — which is almost always in practice. The t-distribution has heavier tails for small n, accounting for additional uncertainty. For n > 30, results are nearly identical. Default to t-test when comparing means.

Q4: What four factors most increase statistical power in an A/B test?
  1. Larger sample size — the most controllable lever.
  2. Larger true effect size (MDE) — not controllable, but setting a realistic MDE avoids underpowered tests.
  3. Lower metric variance — use variance reduction techniques like CUPED (Control-Using Pre-Experiment Data).
  4. Higher α — increases power but also increases Type I error risk; only appropriate in low-stakes contexts.
When should you use a Mann-Whitney U test instead of a t-test?

Use Mann-Whitney U when: (1) the data is non-normal (test with Shapiro-Wilk if unsure); (2) the data is ordinal rather than continuous; (3) sample sizes are small (n < 30) and you can't verify normality; or (4) there are outliers you can't justify removing. Mann-Whitney tests whether one distribution stochastically dominates the other — it's more robust than the t-test but has lower power when normality actually holds. Always report effect size (rank-biserial r) alongside the p-value.

You run an A/B test and get p = 0.03. Your manager asks: "How big is the effect?" What do you report?

Report Cohen's d (or the relevant effect size metric): compute the standardized difference between group means. Interpret it against benchmarks: d = 0.2 small, 0.5 medium, 0.8 large. Additionally, report the absolute difference in the business metric (e.g., conversion rate lifted from 4.0% to 4.3%) and the 95% confidence interval on that difference. A p-value of 0.03 only tells you the effect is unlikely to be zero — it says nothing about whether the effect is large enough to matter. With millions of users, you can detect d = 0.01 as "significant" while the actual business impact is negligible.

Action Items

  • Memorize PDF/PMF formulas for Normal, Binomial, and Poisson distributions.
  • Practice 5 complex Bayes' Theorem word problems (fraud detection, medical testing).
  • Calculate sample size for a two-proportion test from 5% to 6% conversion (α=0.05, 80% power).
  • Write out the differences between Type I error, Type II error, and power in your own words.