Descriptive Statistics and Exploratory Data Analysis

Foundations · Data Science Statistics

What EDA Is For

Before any model, look at the data. Exploratory data analysis (EDA) finds the shape of each variable, the missing values, the outliers and the relationships, so the later statistics are applied to data you actually understand. Every number here has a pandas one-liner.

Types of data
The first questions
  • Numerical, continuous: any value in a range (price, temperature).
  • Numerical, discrete: counts (orders per day).
  • Categorical, nominal: labels without order (country, plan).
  • Categorical, ordinal: ordered labels (small / medium / large, star ratings).
  • Datetime: timestamps; usually becomes several features (hour, weekday, elapsed time).
  • Text, IDs: not statistics until transformed; IDs should never be treated as numbers.
  • How many rows and columns? What is one row (a customer, a session, a day)?
  • Which columns have missing values, and are they missing at random?
  • What is the distribution of each numeric column: center, spread, skew, outliers?
  • What are the category counts? Any rare levels or typos ("NY" vs "New York")?
  • Which pairs of variables move together? Anything that leaks the target?
  • Is there a time component, and does the data drift over it?

Measures of Center

Mean
Median

\[\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i\]

Uses every value, so it is pulled toward outliers and long tails. The right center for symmetric data and for anything you will later add up (revenue, totals).

The middle value when sorted (average of the middle two for even \(n\)). Robust to outliers. The right center for skewed data such as income, house prices and response times.

Mode
Trimmed mean

The most frequent value. The only center that works for nominal categories; rarely useful for continuous data unless binned.

Drop the top and bottom \(p\%\) then average. A compromise between the mean and the median; scipy.stats.trim_mean(x, 0.1).

Mean vs median tells you the skew. Mean > median means a right (positive) skew with a long tail of large values; mean < median means a left skew. If they differ a lot, report the median and quartiles, not the mean and SD.

Center in pandas

import pandas as pd
df = pd.read_csv("orders.csv")
df["amount"].mean(), df["amount"].median(), df["amount"].mode()[0]
df.describe()                       # count, mean, std, min, quartiles, max for every numeric column
df.describe(include="object")       # count, unique, top, freq for text / category columns

Measures of Spread

Variance and standard deviation
Range, IQR, MAD

\[s^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i-\bar{x})^2 \qquad s = \sqrt{s^2}\]

The sample versions divide by \(n-1\) (Bessel's correction) so they are unbiased for the population variance. The SD is in the units of the data; the variance is in squared units. pandas .std() uses \(n-1\); NumPy np.std uses \(n\) unless you pass ddof=1.

\[\text{IQR} = Q_3 - Q_1\]

\[\text{MAD} = \operatorname{median}\left(|x_i - \tilde{x}|\right)\]

The range is fragile (two points decide it). The interquartile range covers the middle 50% and ignores tails. The median absolute deviation is the robust cousin of the SD; multiply by 1.4826 to put it on the SD scale for normal data.

Coefficient of variation
Standard error vs standard deviation

\[\text{CV} = \frac{s}{\bar{x}}\]

Spread relative to the mean, unit-free, so you can compare the variability of columns measured in different units. Only meaningful for ratio data with a positive mean.

\[\text{SE}_{\bar{x}} = \frac{s}{\sqrt{n}}\]

The SD describes how spread out the data are. The standard error describes how uncertain the mean is, and shrinks with \(\sqrt{n}\). Error bars should say which one they show.

Spread in pandas

s = df["amount"]
s.std(), s.var()                       # n-1 denominator
s.quantile([0.25, 0.5, 0.75])          # quartiles
iqr = s.quantile(0.75) - s.quantile(0.25)
mad = (s - s.median()).abs().median()
s.std() / s.mean()                     # coefficient of variation
s.sem()                                # standard error of the mean

Shape: Skewness, Kurtosis, Quantiles

Skewness
Kurtosis

\[g_1 = \frac{\frac{1}{n}\sum (x_i-\bar{x})^3}{s^3}\]

Zero for a symmetric distribution; positive for a right tail; negative for a left tail. Beyond about \(\pm 1\) is strongly skewed and a log transform is worth trying before modeling.

\[g_2 = \frac{\frac{1}{n}\sum (x_i-\bar{x})^4}{s^4} - 3\]

Measures heavy tails, not peakedness. The normal has excess kurtosis 0 (pandas and SciPy report excess by default). High kurtosis means outliers are more common than a normal would predict, which matters for anything relying on the SD.

Percentiles and quantiles
Z-scores

The \(p\)th percentile is the value below which \(p\%\) of the data fall. Quartiles split into four; deciles into ten. Software differs on the interpolation rule for in-between positions; pandas default is linear interpolation. Percentiles are the language of SLAs: “p95 latency” is the 95th percentile.

\[z = \frac{x - \bar{x}}{s}\]

How many SDs a value sits from the mean. Puts different columns on one scale (standardization) and gives a quick outlier rule: \(|z| \gt 3\) is rare under normality. Use the robust version \((x - \tilde{x}) / \text{MAD}\) when outliers inflate \(s\) itself.

Shape in pandas

s.skew(), s.kurt()                     # excess kurtosis
s.quantile(0.95)                       # p95
z = (s - s.mean()) / s.std()
outliers = df[z.abs() > 3]
import numpy as np
np.log1p(s)                            # log(1 + x): tames right skew and keeps zeros finite

Outliers and Missing Values

Finding outliers
Handling them
  • 1.5 IQR rule: flag \(x \lt Q_1 - 1.5\,\text{IQR}\) or \(x \gt Q_3 + 1.5\,\text{IQR}\) (the boxplot whiskers).
  • Z-score rule: \(|z| \gt 3\); assumes roughly normal data.
  • Domain rule: negative ages, 300% discounts, timestamps in the future: data errors, not statistics.
  • Multivariate: a point normal on each axis but odd in combination (Mahalanobis distance, isolation forest).
  • First decide if it is an error (fix or drop) or a real extreme (keep; it is information).
  • Winsorize: cap at the 1st and 99th percentiles rather than deleting.
  • Transform: log or Box-Cox pulls tails in.
  • Use robust statistics and models (median, MAD, Huber loss, tree models) that are not swayed.
  • Report what you did. Silent deletion is the most common way analyses are quietly wrong.
Kinds of missingness
Handling missing values
  • MCAR (completely at random): missingness unrelated to anything. Dropping rows loses power but not validity.
  • MAR (at random): depends on observed variables (older customers skip the income field). Imputation using those variables works.
  • MNAR (not at random): depends on the missing value itself (high earners hide income). No imputation fixes this; model the missingness or collect better data.
  • Count and visualize first: df.isna().mean() per column; a missingness heatmap.
  • Drop columns that are mostly empty; drop rows only when few and MCAR.
  • Impute: median for skewed numerics, mode for categories, or a model (KNN, iterative imputer).
  • Add a missing indicator column: the fact that a value was missing is often predictive.
  • Fit the imputer on the training split only, then apply to the test split (no leakage).

Outliers and missing values in pandas

df.isna().sum()                                   # missing per column
df.isna().mean().sort_values(ascending=False)     # share missing
df["income"].fillna(df["income"].median())
df["income_missing"] = df["income"].isna().astype(int)
lo, hi = s.quantile([0.01, 0.99]); s.clip(lo, hi)   # winsorize
q1, q3 = s.quantile([0.25, 0.75]); iqr = q3 - q1
mask = (s < q1 - 1.5 * iqr) | (s > q3 + 1.5 * iqr)

Relationships Between Variables

Numeric with numeric
Categorical with numeric
  • Scatter plot first. Correlation only measures the linear part.
  • Pearson \(r\) for linear association; Spearman \(\rho\) for monotonic association and outlier resistance (chapter 8).
  • Check for clusters, curves and heteroscedasticity (fan shapes) that a single number hides.
  • Grouped summaries: df.groupby("plan")["amount"].agg(["mean", "median", "count"]).
  • Box plots or violin plots per group; compare medians and spreads, not just means.
  • Formal test later: t-test for two groups, ANOVA or Kruskal-Wallis for more (chapter 6).
Categorical with categorical
Simpson's paradox
  • Contingency table: pd.crosstab(df.plan, df.churned, normalize="index") gives row percentages.
  • Chi-square test of independence (chapter 6); Cramér's V for strength on a 0 to 1 scale.

A trend that appears in every subgroup can reverse when the groups are combined, because group sizes differ (the Berkeley admissions case). Always check whether a relationship holds within the natural strata before trusting the pooled number.

Relationships in pandas and seaborn

df[["amount", "visits", "age"]].corr()                  # Pearson
df[["amount", "visits", "age"]].corr(method="spearman")
pd.crosstab(df["plan"], df["churned"], normalize="index")
df.groupby("plan")["amount"].describe()
import seaborn as sns
sns.pairplot(df[["amount", "visits", "age"]]); sns.boxplot(data=df, x="plan", y="amount")

EDA Checklist

  1. df.shape, df.dtypes, df.head(): what a row is, which columns are the wrong type.
  2. df.describe(include="all") and df.isna().mean().
  3. Histogram or KDE of every numeric column; bar chart of every categorical column. Note skew and rare levels.
  4. Box plots for outliers; decide error vs extreme.
  5. Correlation matrix and pairplot for numerics; crosstabs for categoricals; grouped box plots across.
  6. If there is a time column: plot the key metrics over time; look for breaks, seasonality, drift.
  7. Write down the questions the data raised. Those become the hypotheses in chapters 6 and 7.

Probability Essentials

Foundations · Data Science Statistics

The Rules

Probability is the grammar underneath every statistic in this sheet: p-values, confidence intervals, likelihoods, Bayesian posteriors and classification scores are all probabilities. These are the handful of rules that generate everything else.

Axioms and complements
Addition rule

\[0 \le P(A) \le 1 \qquad P(S) = 1 \qquad P(A^c) = 1 - P(A)\]

The complement rule is the workhorse: “at least one” is \(1 - P(\text{none})\).

\[P(A \cup B) = P(A) + P(B) - P(A \cap B)\]

For mutually exclusive events the overlap is zero and you just add.

Conditional probability
Multiplication rule

\[P(A \mid B) = \frac{P(A \cap B)}{P(B)}\]

“Probability of A given B.” Conditioning shrinks the sample space to B. Every classifier outputs \(P(\text{class} \mid \text{features})\).

\[P(A \cap B) = P(A \mid B)\,P(B) = P(B \mid A)\,P(A)\]

Chain it for longer sequences: \(P(A \cap B \cap C) = P(A)\,P(B \mid A)\,P(C \mid A \cap B)\).

Independence
Law of total probability

\[P(A \cap B) = P(A)\,P(B) \iff P(A \mid B) = P(A)\]

Knowing B tells you nothing about A. Independence is an assumption, not a default: user sessions, repeated measurements and time series points are usually dependent. Naive Bayes assumes features are independent given the class and works anyway, often.

\[P(A) = \sum_i P(A \mid B_i)\,P(B_i)\]

When the \(B_i\) partition the space. This is how you average a conditional rate over a mix of groups, and the denominator in Bayes' theorem.

Bayes' Theorem

\[P(H \mid D) = \frac{P(D \mid H)\,P(H)}{P(D)} = \frac{P(D \mid H)\,P(H)}{P(D \mid H)\,P(H) + P(D \mid H^c)\,P(H^c)}\]

The pieces
Base-rate neglect
  • \(P(H)\): the prior, the belief before the data.
  • \(P(D \mid H)\): the likelihood, how probable this data is if H is true.
  • \(P(D)\): the evidence, the total probability of the data; a normalizer.
  • \(P(H \mid D)\): the posterior, the updated belief.

A test with 99% sensitivity and 99% specificity for a condition with 1% prevalence: \(P(\text{sick} \mid +) = \frac{0.99 \times 0.01}{0.99 \times 0.01 + 0.01 \times 0.99} = 0.5\). Half of positives are false. Rare events stay fairly unlikely even after a positive signal; the same logic governs fraud detection and spam filters.

Bayes in Python

prevalence, sens, spec = 0.01, 0.99, 0.99
p_pos = sens * prevalence + (1 - spec) * (1 - prevalence)
posterior = sens * prevalence / p_pos
print(round(posterior, 3))
0.5

Odds form. Posterior odds = prior odds × likelihood ratio. With prior odds 1:99 and a likelihood ratio of 99, posterior odds are 99:99 = 1:1. The odds form is why log-odds (logits) add up so neatly in logistic regression.

Random Variables

Discrete
Continuous

\[E[X] = \sum_x x\,p(x) \qquad \operatorname{Var}(X) = E[X^2] - (E[X])^2\]

A probability mass function \(p(x)\) gives the probability of each value. The expectation is the long-run average; the variance is the expected squared distance from it.

\[P(a \le X \le b) = \int_a^b f(x)\,dx \qquad E[X] = \int x\,f(x)\,dx\]

A density \(f(x)\) is not a probability; only areas are. \(P(X = x) = 0\) for any single point. The cumulative distribution function is \(F(x) = P(X \le x)\); the quantile function is its inverse.

Linearity of expectation
Variance of sums

\[E[aX + bY + c] = a\,E[X] + b\,E[Y] + c\]

Always true, dependent or not. This is why the expected total of many small bets is the sum of their expectations.

\[\operatorname{Var}(aX + bY) = a^2\operatorname{Var}(X) + b^2\operatorname{Var}(Y) + 2ab\operatorname{Cov}(X, Y)\]

The covariance term vanishes only under independence. For \(n\) independent copies, \(\operatorname{Var}(\bar{X}) = \sigma^2 / n\), which is where the standard error comes from.

Covariance and correlation
Joint, marginal, conditional

\[\operatorname{Cov}(X,Y) = E[(X-\mu_X)(Y-\mu_Y)]\]

\[\rho = \frac{\operatorname{Cov}(X,Y)}{\sigma_X \sigma_Y}\]

Correlation is covariance rescaled to \([-1, 1]\). Zero correlation does not imply independence (a parabola has zero correlation and perfect dependence).

The joint distribution \(p(x, y)\) is the whole table. Summing a row gives a marginal \(p(x)\). Dividing a cell by its row total gives a conditional \(p(y \mid x)\). A pandas crosstab with normalize=None, "all", "index" gives counts, joint and conditional in turn.

Counting

Permutations and combinations
Multiplication principle

\[{}_nP_k = \frac{n!}{(n-k)!} \qquad \binom{n}{k} = \frac{n!}{k!\,(n-k)!}\]

Order matters for permutations (rankings, passwords); not for combinations (committees, which 3 of 10 features). \(\binom{n}{k}\) is the coefficient in the binomial distribution.

If a task has \(m\) ways and the next has \(n\), together there are \(mn\). Sampling with replacement from \(n\) items \(k\) times gives \(n^k\) sequences. The number of rows in a full factorial of features is the product of their level counts.

Counting in Python

from math import comb, perm, factorial
comb(10, 3), perm(10, 3)       # 120, 720
from scipy.special import comb as scomb   # scomb(10, 3, exact=True) for big numbers

The second line prints (120, 720): 120 ways to pick 3 of 10 features when order is irrelevant, 720 when it matters. The two are tied by \(720 = 120 \times 3!\), because each set of 3 can be ordered 6 ways. Worked example: the probability that a random 3-feature subset contains one specific feature is the number of subsets that include it, \(\binom{9}{2} = 36\) (the other two chosen from the remaining 9), over \(\binom{10}{3} = 120\): \(36/120 = 0.3\). The same answer by the multiplication principle: \(3/10\), since each feature has 3 of 10 chances of being picked.

Simulation: When the Algebra Is Hard

Data scientists often estimate probabilities by simulation rather than by formula. Generate many random trials, count the outcome, divide. The law of large numbers (chapter 4) guarantees convergence, and the error shrinks like \(1/\sqrt{N}\).

Monte Carlo estimates

import numpy as np
rng = np.random.default_rng(42)
# P(at least one shared birthday in a room of 23)
N = 100_000
rooms = rng.integers(0, 365, size=(N, 23))
shared = np.array([len(set(r)) < 23 for r in rooms]).mean()
print(round(shared, 3))        # ~0.507
# Expected number of rolls to see every face of a die
def rolls_to_collect():
    seen, n = set(), 0
    while len(seen) < 6:
        seen.add(rng.integers(1, 7)); n += 1
    return n
np.mean([rolls_to_collect() for _ in range(20_000)])   # ~14.7

Both quantities have exact answers to check the simulation against. \(P(\text{shared birthday}) = 1 - \prod_{i=0}^{22}\frac{365 - i}{365} = 0.507\), and the expected number of rolls to collect all six faces is \(6\left(1 + \tfrac12 + \tfrac13 + \tfrac14 + \tfrac15 + \tfrac16\right) = 14.7\). The printed estimates land within a standard error of these: for the birthday run, \(\sqrt{0.5 \times 0.5 / 100{,}000} \approx 0.0016\). When no formula exists, that standard error is still the right way to say how precise your simulated answer is.

Seed the generator (default_rng(42)) so results reproduce, and report how many trials you ran. A simulated probability from 1,000 trials has a standard error near \(\sqrt{p(1-p)/1000} \approx 0.016\).

Probability Distributions

Foundations · Data Science Statistics

Why Distributions Matter in Data Science

A distribution is a model of how a variable behaves. Choosing the right one decides which test, which confidence interval, which loss function and which generative model are appropriate. Every distribution below is in scipy.stats with the same four methods: pmf or pdf (probability), cdf (cumulative), ppf (quantile, the inverse CDF) and rvs (random draws).

The scipy.stats pattern

from scipy import stats
d = stats.norm(loc=0, scale=1)
d.pdf(1.0), d.cdf(1.96), d.ppf(0.975), d.rvs(size=5, random_state=0)
# every distribution works the same way:
stats.binom(n=10, p=0.3).pmf(4); stats.poisson(mu=3).cdf(5); stats.t(df=12).ppf(0.975)

Discrete Distributions

DistributionModelsParametersMeanVariancescipy.stats
BernoulliOne yes/no trial (did the user click?)\(p\)\(p\)\(p(1-p)\)bernoulli(p)
BinomialNumber of successes in \(n\) independent trials with the same \(p\) (clicks out of \(n\) impressions)\(n, p\)\(np\)\(np(1-p)\)binom(n, p)
PoissonCount of events in a fixed window when events are independent at a constant rate (arrivals per minute, defects per sheet)\(\lambda\)\(\lambda\)\(\lambda\)poisson(mu)
GeometricTrials until the first success (sessions until first purchase)\(p\)\(1/p\)\((1-p)/p^2\)geom(p)
Negative binomialTrials until the \(r\)th success; or overdispersed counts where the variance exceeds the mean\(r, p\)\(r(1-p)/p\)\(r(1-p)/p^2\)nbinom(n, p)
Discrete uniformEqually likely integers (a fair die)\(a, b\)\((a+b)/2\)\(((b-a+1)^2-1)/12\)randint(a, b+1)
MultinomialCounts across \(k\) categories in \(n\) trials (which of 4 plans each signup chose)\(n, p_1 \ldots p_k\)\(np_i\)\(np_i(1-p_i)\)multinomial(n, p)
Binomial
Poisson

\[P(X = k) = \binom{n}{k} p^k (1-p)^{n-k}\]

Conversion counts, defect counts, survey yes-counts. For large \(n\) with \(np \ge 10\) and \(n(1-p) \ge 10\) it is close to a normal with the same mean and variance. The proportion \(\hat{p} = X/n\) has variance \(p(1-p)/n\).

\[P(X = k) = \frac{e^{-\lambda}\lambda^k}{k!}\]

Mean equals variance. If a count column has variance much bigger than its mean (overdispersion, the usual case with real traffic), the negative binomial fits better. The Poisson is the limit of the binomial when \(n\) is large and \(p\) small with \(np = \lambda\).

Discrete examples

# P(at least 15 conversions out of 200 at a 5% rate)
1 - stats.binom(200, 0.05).cdf(14)
# P(more than 8 arrivals in a minute when the average is 5)
stats.poisson(5).sf(8)                         # sf = 1 - cdf, more accurate in the tail
# Overdispersion check on a count column
c = df["orders_per_day"]; c.var() / c.mean()  # >> 1 means not Poisson

Continuous Distributions

DistributionModelsParametersMeanVariancescipy.stats
UniformAnything equally likely across an interval; random number generators\(a, b\)\((a+b)/2\)\((b-a)^2/12\)uniform(a, b-a)
Normal (Gaussian)Sums and averages of many small effects; measurement noise; the CLT limit\(\mu, \sigma\)\(\mu\)\(\sigma^2\)norm(mu, sigma)
Log-normalProducts of many effects: incomes, prices, file sizes, durations; right-skewed positives\(\mu, \sigma\) of \(\ln X\)\(e^{\mu + \sigma^2/2}\)\((e^{\sigma^2}-1)e^{2\mu+\sigma^2}\)lognorm(s, scale=e^mu)
ExponentialWaiting time between Poisson events; memoryless lifetimes\(\lambda\) (rate)\(1/\lambda\)\(1/\lambda^2\)expon(scale=1/lam)
GammaWaiting time for \(k\) events; positive skewed quantities; prior for a Poisson rate\(k\) (shape), \(\theta\) (scale)\(k\theta\)\(k\theta^2\)gamma(a, scale)
BetaA probability or proportion on \([0,1]\); prior for a conversion rate\(\alpha, \beta\)\(\frac{\alpha}{\alpha+\beta}\)\(\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}\)beta(a, b)
WeibullTime to failure with rising or falling hazard (churn, hardware)\(k\) (shape), \(\lambda\)\(\lambda\,\Gamma(1 + 1/k)\)see docsweibull_min(c, scale)
Pareto / power lawHeavy tails: wealth, city sizes, word frequencies, viral shares\(x_m, \alpha\)\(\frac{\alpha x_m}{\alpha-1}\) for \(\alpha \gt 1\)infinite for \(\alpha \le 2\)pareto(b, scale)
The normal distribution
The exponential and memorylessness

\[f(x) = \frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)\]

\[z = \frac{x-\mu}{\sigma}\]

68% of values within 1 SD, 95% within 2 (1.96), 99.7% within 3. Standardizing to \(z\) puts any normal on the standard \(N(0,1)\) scale. It is the default because of the central limit theorem (chapter 4), not because data are usually normal; incomes, latencies and counts usually are not.

\[f(x) = \lambda e^{-\lambda x} \qquad P(X \gt s + t \mid X \gt s) = P(X \gt t)\]

Having waited \(s\) minutes already does not change the remaining wait. Realistic for radioactive decay and for arrivals in a Poisson process; unrealistic for human lifetimes and hardware, where the hazard changes with age (use Weibull).

Continuous examples

# P(latency > 800 ms) if latency ~ lognormal fit to the data
shape, loc, scale = stats.lognorm.fit(df["latency_ms"], floc=0)
stats.lognorm(shape, loc, scale).sf(800)
# Normal: share of values beyond 2 SD
2 * stats.norm.sf(2)                           # 0.0455
# Exponential waits with 5 arrivals/minute: P(wait > 30 s)
stats.expon(scale=1/5).sf(0.5)

Sampling Distributions You Will Meet in Tests

DistributionArises asUsed forscipy.stats
Student's \(t\)A standardized mean when \(\sigma\) is estimated by \(s\); heavier tails than normal, approaches it as \(df \to \infty\)t-tests, CIs for means and regression coefficientst(df)
Chi-square \(\chi^2\)Sum of \(k\) squared standard normals; \((n-1)s^2/\sigma^2\)Goodness of fit, independence in contingency tables, variance tests, likelihood-ratio testschi2(df)
\(F\)Ratio of two scaled chi-squaresANOVA, comparing two variances, overall regression significancef(dfn, dfd)
Standard normal \(z\)CLT limit of standardized sums and proportionsz-tests for proportions, large-sample CIsnorm()

t vs z. Use \(t\) with \(n-1\) degrees of freedom whenever the SD is estimated from the sample, which in practice is always for means. At \(n = 30\) the 97.5th percentile is 2.04 instead of 1.96; by \(n = 200\) the difference is negligible.

Checking Which Distribution Fits

Visual checks
Formal checks
  • Histogram with a fitted density overlaid: does the shape match?
  • Q-Q plot: sample quantiles against theoretical quantiles; a straight line means a good fit. Curving up at the right means a heavier right tail than the model.
  • Log-scale histogram: if a right-skewed variable looks normal after logging, it is log-normal.
  • Empirical CDF against the model CDF.
  • Shapiro-Wilk (stats.shapiro) for normality on small samples; at large \(n\) it rejects trivial departures, so prefer the Q-Q plot.
  • Kolmogorov-Smirnov (stats.kstest) against any fully specified CDF; weak in the tails.
  • Anderson-Darling (stats.anderson) weights the tails more.
  • AIC / BIC between candidate fits: lower is better; dist.fit then dist.logpdf(x).sum().

Fit checks

import matplotlib.pyplot as plt
x = df["latency_ms"].dropna()
stats.probplot(np.log(x), dist="norm", plot=plt); plt.show()      # Q-Q plot of log(latency)
stats.shapiro(x.sample(500, random_state=0))                        # W, p on a subsample
cands = {"lognorm": stats.lognorm, "gamma": stats.gamma, "expon": stats.expon}
for name, d in cands.items():
    params = d.fit(x, floc=0)
    ll = d.logpdf(x, *params).sum(); k = len(params)
    print(name, "AIC", round(2 * k - 2 * ll, 1))

Sampling and the Central Limit Theorem

Inference · Data Science Statistics

Population, Sample, Statistic

Inference is the move from the sample you have to the population you care about. A parameter (\(\mu, \sigma, p\)) describes the population and is unknown. A statistic (\(\bar{x}, s, \hat{p}\)) is computed from the sample and estimates it. The statistic changes from sample to sample; its distribution across samples is the sampling distribution, and that is what every standard error, confidence interval and p-value is about.

Ways to sample
Bias that sampling cannot fix
  • Simple random: every subset equally likely. The baseline the formulas assume.
  • Stratified: random within strata (country, plan) so small groups are represented; lowers variance.
  • Cluster: pick whole groups (stores, schools) then everyone inside. Cheap, but units within a cluster are correlated, so the effective sample size is smaller.
  • Systematic: every \(k\)th record. Fine unless the data have a period of \(k\).
  • Convenience: whoever shows up. No valid inference; the common case in product data.
  • Selection bias: the sampled units differ systematically from the population (only active users answer).
  • Survivorship bias: you only see the units that lasted (customers still around in year 3).
  • Nonresponse: who refuses is not random.
  • Measurement bias: the instrument is off (leading questions, a broken logger).
  • More data does not remove bias; it only makes a biased answer more precise.

Sampling in pandas and scikit-learn

sample = df.sample(n=500, random_state=0)                        # simple random
strat = df.groupby("plan", group_keys=False).apply(lambda g: g.sample(frac=0.1, random_state=0))
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.2, stratify=df["churned"], random_state=0)

Law of Large Numbers

\[\bar{X}_n \to \mu \quad \text{as } n \to \infty\]

The sample mean converges to the population mean. It says nothing about any single draw and nothing about “being due” (the gambler's fallacy). It is why simulation works and why averages over big logs are stable.

Running mean

rng = np.random.default_rng(1)
x = rng.exponential(scale=2.0, size=100_000)       # true mean 2
running = np.cumsum(x) / np.arange(1, len(x) + 1)
running[[9, 99, 999, 9999, 99999]]                 # drifts toward 2.0

The last line prints the running mean after 10, 100, 1,000, 10,000 and 100,000 draws, something like 2.18, 2.08, 2.02, 2.00, 1.99 for this seed. Read it as the gap to the true mean (2.0) shrinking roughly by a factor of \(\sqrt{10} \approx 3\) each time \(n\) grows tenfold, because the standard error of the mean is \(\sigma/\sqrt{n}\) with \(\sigma = 2\) here. Change the seed and the first few entries move a lot while the last ones barely budge: that is the law in action.

The Central Limit Theorem

\[\bar{X} \;\dot\sim\; N\!\left(\mu,\ \frac{\sigma^2}{n}\right)\]

\[\text{equivalently}\]

\[\frac{\bar{X} - \mu}{\sigma/\sqrt{n}} \;\dot\sim\; N(0, 1)\]

What it says
What it does not say
  • The sampling distribution of the mean (and of sums, proportions and most averages) is approximately normal for large \(n\), whatever the shape of the population.
  • Its center is the population mean and its spread is \(\sigma / \sqrt{n}\), the standard error.
  • Quadrupling \(n\) halves the standard error. Precision has diminishing returns.
  • It is why normal-based intervals and tests work on skewed data once \(n\) is decent.
  • The data do not become normal. Only the statistic does.
  • “Large” depends on the skew: 30 is enough for mild skew; heavy tails or rare-event proportions can need thousands.
  • It needs finite variance (power-law tails break it) and roughly independent observations.
  • The median, the maximum and ratios have their own sampling distributions; the bootstrap handles them.

See the CLT happen

pop = rng.lognormal(mean=0, sigma=1, size=1_000_000)       # very skewed population
for n in (5, 30, 200):
    means = rng.choice(pop, size=(20_000, n)).mean(axis=1)
    print(n, round(means.mean(), 3), round(means.std(), 3), round(pop.std() / np.sqrt(n), 3), round(stats.skew(means), 2))
# the skew of the sampling distribution falls toward 0 as n grows

Each printed row is: sample size \(n\), the mean of the 20,000 sample means (close to the population mean \(e^{0.5} \approx 1.65\) at every \(n\)), their standard deviation, the CLT prediction \(\sigma/\sqrt{n}\) for that standard deviation, and the skewness of the sample means. The third and fourth columns should match (about 0.97, 0.39 and 0.15 for \(n = 5, 30, 200\), since the population SD is 2.16), which confirms the standard error formula. The skewness column starts well above 1 and falls toward 0: the raw data stay log-normal, but the averages become normal, and with a population this skewed \(n = 30\) is not yet enough.

Standard Errors

StatisticStandard errorNotes
Mean \(\bar{x}\)\(\dfrac{s}{\sqrt{n}}\)Use \(t_{n-1}\) for intervals
Proportion \(\hat{p}\)\(\sqrt{\dfrac{\hat{p}(1-\hat{p})}{n}}\)Needs \(n\hat{p}\) and \(n(1-\hat{p})\) of at least 10 or so
Difference of means\(\sqrt{\dfrac{s_1^2}{n_1} + \dfrac{s_2^2}{n_2}}\)Welch form; no equal-variance assumption
Difference of proportions\(\sqrt{\dfrac{\hat{p}_1(1-\hat{p}_1)}{n_1} + \dfrac{\hat{p}_2(1-\hat{p}_2)}{n_2}}\)The A/B test standard error
Regression slope\(\dfrac{s_{\text{resid}}}{\sqrt{\sum (x_i - \bar{x})^2}}\)Spread in \(x\) buys precision
Anything elsebootstrapMedian, percentiles, ratios, AUC, custom metrics
Reading the table
Worked example
  • \(s\), \(s_1\), \(s_2\): sample standard deviations (the ddof=1 version); \(n\), \(n_1\), \(n_2\): the sample sizes; \(\hat{p}\): the observed proportion \(k/n\).
  • A standard error is the SD of the statistic across repeated samples, in the units of the statistic. It is what you multiply by 1.96 (or \(t^*\)) to get a margin of error, and what you divide a difference by to get a \(z\) or \(t\).
  • Every formula here assumes independent observations. Clustered or repeated data (several sessions per user) make the true SE larger than the formula says.

Revenue per user: \(n = 400\), \(\bar{x} = 52\), \(s = 40\). \(\text{SE} = 40/\sqrt{400} = 40/20 = 2.0\). The sample mean is 52 give or take about 2, so the population mean is plausibly anywhere from roughly 48 to 56 (two SEs either side).

Conversion: 57 of 1,200 visitors converted, \(\hat{p} = 0.0475\). \(\text{SE} = \sqrt{0.0475 \times 0.9525 / 1200} = \sqrt{0.0000377} = 0.0061\), so the rate is 4.75% give or take about 0.6 points. To halve that SE you would need four times the visitors, 4,800.

Finite population correction. When you sample more than about 5% of a finite population without replacement, multiply the SE by \(\sqrt{(N-n)/(N-1)}\). Rare in product analytics, common in surveys of small groups.

The Bootstrap

Resample your sample with replacement, compute the statistic, repeat thousands of times. The spread of those values estimates the sampling distribution without a formula. It works for medians, percentiles, ratios, model metrics and anything else, with the same caveats as the CLT about independence and extreme tails.

Bootstrap SE and CI

def bootstrap(x, stat, B=5000, seed=0):
    rng = np.random.default_rng(seed); x = np.asarray(x)
    return np.array([stat(rng.choice(x, size=len(x), replace=True)) for _ in range(B)])

x = df["latency_ms"].dropna().to_numpy()
boots = bootstrap(x, np.median)
se = boots.std(ddof=1)
ci = np.percentile(boots, [2.5, 97.5])          # percentile bootstrap CI for the median
# SciPy's version (BCa interval by default)
res = stats.bootstrap((x,), np.median, confidence_level=0.95, random_state=0)
res.confidence_interval

boots holds 5,000 medians, one per resample; its standard deviation se is the bootstrap standard error of the median, a number no simple formula gives you. ci is the pair of values that cut off the lowest and highest 2.5% of those medians, so it reads exactly like a formula interval: “the population median latency is between ci[0] and ci[1] ms with 95% confidence.” SciPy's res.confidence_interval returns low and high for the same thing with the BCa correction; the two intervals should be close, and if they differ much the statistic's distribution is skewed and BCa is the one to report.

Bootstrap tips
Permutation tests
  • Resample rows, so paired columns stay paired (for regression, correlation, AUC).
  • For grouped or time-dependent data, resample whole groups or blocks, not single rows.
  • B = 1,000 is enough for a standard error; use 5,000 to 10,000 for 95% interval endpoints.
  • Percentile intervals are simple; BCa corrects for bias and skew and is the better default.

The bootstrap's sibling for hypothesis tests: shuffle the group labels, recompute the difference, repeat. The share of shuffled differences at least as extreme as the observed one is the p-value, with no distributional assumption. See chapter 6.

Estimation and Confidence Intervals

Inference · Data Science Statistics

Point Estimates and Their Properties

What makes an estimator good
Mean squared error
  • Unbiased: its expected value equals the parameter. \(\bar{x}\) for \(\mu\); \(s^2\) with \(n-1\) for \(\sigma^2\).
  • Low variance (efficient): tight sampling distribution.
  • Consistent: converges to the truth as \(n\) grows.
  • The bias-variance trade-off: a slightly biased estimator with much lower variance often has lower total error. Regularized regression and shrinkage estimators are built on this (chapter 10).

\[\text{MSE}(\hat\theta) = \operatorname{Var}(\hat\theta) + \text{Bias}(\hat\theta)^2\]

The same decomposition drives model evaluation: test error = variance + bias\(^2\) + irreducible noise.

Worked example: estimator A is unbiased with variance 4, so \(\text{MSE}_A = 4 + 0^2 = 4\). Estimator B is off by 1 on average (bias 1) but has variance 1, so \(\text{MSE}_B = 1 + 1^2 = 2\). B is typically closer to the truth even though it is biased; that is the trade a shrinkage estimator makes on purpose.

Maximum Likelihood

\[\hat\theta_{\text{MLE}} = \arg\max_\theta \; \mathcal{L}(\theta) = \arg\max_\theta \sum_{i=1}^{n} \log f(x_i \mid \theta)\]

The idea
Familiar MLEs

Pick the parameter values that make the observed data most probable. Working with the log turns products into sums and is numerically stable. MLEs are consistent, asymptotically normal and efficient, which is why they are the default fitting method for distributions and for logistic regression.

  • Normal: \(\hat\mu = \bar{x}\), \(\hat\sigma^2 = \frac{1}{n}\sum (x_i - \bar{x})^2\) (note \(n\), so slightly biased).
  • Bernoulli / binomial: \(\hat{p} = k/n\).
  • Poisson: \(\hat\lambda = \bar{x}\).
  • Linear regression with normal errors: least squares is maximum likelihood.
  • Logistic regression: no closed form; solved by gradient methods on the log-likelihood (the cross-entropy loss).

MLE by hand and by SciPy

from scipy.optimize import minimize
x = df["orders_per_day"].to_numpy()
nll = lambda lam: -stats.poisson(lam[0]).logpmf(x).sum()      # negative log-likelihood
res = minimize(nll, x0=[1.0], bounds=[(1e-9, None)])
res.x[0], x.mean()                                             # identical: the Poisson MLE is the mean
# distribution fitting in SciPy is MLE under the hood
stats.gamma.fit(df["latency_ms"], floc=0)

nll returns the negative log-likelihood of the whole column for a candidate rate; minimize searches for the rate that makes it smallest, starting from 1.0 and never going below zero. res.x[0] is that rate and the line prints it next to x.mean(): the two agree to several decimals, which is the point. The last line returns the fitted gamma's (shape, loc, scale); with floc=0 the location is pinned at zero so only shape and scale are estimated, which is what you want for a strictly positive quantity like latency.

Confidence Intervals: The Idea

A 95% confidence interval is built by a procedure that captures the true parameter in 95% of repeated samples. It is a statement about the procedure, not a 95% probability that the truth lies in this interval (that is the Bayesian credible interval, chapter 11). In practice: the interval is the range of parameter values compatible with the data, and its width is the honest measure of your uncertainty.

\[\text{estimate} \;\pm\; (\text{critical value}) \times (\text{standard error})\]

Reading an interval

  • Width shrinks with \(\sqrt{n}\): four times the data for half the width.
  • A 99% interval is wider than a 95%; more confidence costs precision.
  • If a 95% CI for a difference excludes 0, the two-sided test at \(\alpha = 0.05\) rejects. Intervals and tests are the same information; the interval shows the size too.
  • Two overlapping CIs do not mean no significant difference. Compute the CI of the difference.

Critical values

Confidencez*t*, df = 10t*, df = 30
90%1.6451.8121.697
95%1.9602.2282.042
99%2.5763.1692.750

Interval Formulas

Mean (SD unknown, the usual case)
Proportion (Wald)

\[\bar{x} \pm t^*_{n-1}\,\frac{s}{\sqrt{n}}\]

Robust to non-normality for \(n\) above about 30 unless the data are very skewed; then log-transform, or bootstrap.

\[\hat{p} \pm z^*\sqrt{\frac{\hat{p}(1-\hat{p})}{n}}\]

Poor when \(\hat{p}\) is near 0 or 1 or \(n\) is small. Prefer Wilson (proportion_confint(method="wilson")) or the Agresti-Coull fix: add 2 successes and 2 failures, then use the Wald formula.

Difference of two means (Welch)
Difference of two proportions

\[(\bar{x}_1 - \bar{x}_2) \pm t^*\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}\]

Degrees of freedom from the Welch-Satterthwaite formula; software handles it. Do not assume equal variances unless you have a reason.

\[(\hat{p}_1 - \hat{p}_2) \pm z^*\sqrt{\frac{\hat{p}_1(1-\hat{p}_1)}{n_1} + \frac{\hat{p}_2(1-\hat{p}_2)}{n_2}}\]

The interval you report with an A/B test on conversion. Also report the relative lift \((\hat{p}_2 - \hat{p}_1)/\hat{p}_1\) with its own (bootstrap or delta-method) interval.

Variance
Anything else: bootstrap

\[\left[\frac{(n-1)s^2}{\chi^2_{\alpha/2}},\ \frac{(n-1)s^2}{\chi^2_{1-\alpha/2}}\right]\]

Sensitive to non-normality; rarely reported in data science, but it is what the F-test compares.

Median, p95, ratio of means, AUC, lift in revenue per user: resample rows, recompute, take the 2.5th and 97.5th percentiles (chapter 4). Report the bootstrap interval the same way as a formula one.

Steps for any interval
Worked example: a mean and a proportion
  1. Name the parameter (a mean, a proportion, a difference) and the confidence level; that fixes the formula and the critical value.
  2. Compute the estimate and its standard error from the table in chapter 4.
  3. Look up the critical value: \(z^*\) for proportions, \(t^*_{n-1}\) for a mean (\(t^*\) for 24 df at 95% is 2.064; stats.t.ppf(0.975, 24)).
  4. Margin of error = critical value × SE; interval = estimate ± margin.
  5. State it in units and in context, and say what it rules out.

Order value: \(n = 25\), \(\bar{x} = 52\), \(s = 8\). \(\text{SE} = 8/\sqrt{25} = 1.6\); \(t^*_{24} = 2.064\); margin \(= 2.064 \times 1.6 = 3.30\). Interval \(52 \pm 3.30 = (48.70,\ 55.30)\). Reading: the long-run average order is between about 48.7 and 55.3; a target of 50 is still compatible with the data, a target of 60 is not.

Conversion: 57 of 1,200, \(\hat{p} = 0.0475\), \(\text{SE} = 0.00614\) (chapter 4), \(z^* = 1.96\). Margin \(= 1.96 \times 0.00614 = 0.0120\); interval \(0.0475 \pm 0.0120 = (0.0355,\ 0.0595)\), that is 3.6% to 6.0%. Both \(n\hat{p} = 57\) and \(n(1 - \hat{p}) = 1143\) exceed 10, so the Wald form is acceptable here; Wilson gives nearly the same numbers.

Watch out. An interval for the mean is not a range that contains 95% of the data; individual orders spread about \(\pm 2s = \pm 16\) around 52, far wider than \(\pm 3.3\). And using \(z^* = 1.96\) where \(t^*\) belongs makes small-sample intervals too narrow: at \(n = 10\) the right multiplier is 2.262, 15% wider.

Intervals in statsmodels and by hand

import statsmodels.stats.api as sms
from statsmodels.stats.proportion import proportion_confint
x = df["amount"].dropna()
sms.DescrStatsW(x).tconfint_mean(alpha=0.05)                     # CI for the mean
proportion_confint(count=57, nobs=1200, alpha=0.05, method="wilson")
a, b = df.loc[df.group == "A", "amount"], df.loc[df.group == "B", "amount"]
sms.CompareMeans(sms.DescrStatsW(a), sms.DescrStatsW(b)).tconfint_diff(usevar="unequal")
# by hand
n, m, s = len(x), x.mean(), x.std(ddof=1)
tcrit = stats.t.ppf(0.975, df=n - 1); (m - tcrit * s / np.sqrt(n), m + tcrit * s / np.sqrt(n))

Each call returns a (lower, upper) pair. tconfint_mean is the \(t\) interval for the mean of amount; proportion_confint is the Wilson interval for \(57/1200\); tconfint_diff(usevar="unequal") is the Welch interval for the difference in mean amount between groups A and B (if it contains 0, the two groups are not distinguishable at the 5% level). The last two lines rebuild the first interval by hand, so you can check that software and formula agree.

Sample Size for a Target Margin of Error

For a mean
For a proportion

\[n = \left(\frac{z^*\,\sigma}{E}\right)^2\]

\(E\) is the half-width you want. Use a pilot SD or a conservative guess for \(\sigma\). Round up.

Worked example: a pilot gives \(\sigma \approx 40\) for order value and you want the mean to within \(\pm 5\) at 95%. \(n = (1.96 \times 40 / 5)^2 = 15.68^2 = 245.9\), so collect 246 orders. For \(\pm 2.5\) the answer quadruples to 984.

\[n = \frac{(z^*)^2\,p(1-p)}{E^2} \quad\le\quad \frac{(z^*)^2 \cdot 0.25}{E^2}\]

With \(p = 0.5\) as the worst case, a \(\pm 3\%\) margin at 95% needs \(n \approx 1{,}068\); \(\pm 1\%\) needs about 9,604. Sample size for detecting a difference is a power calculation: chapter 7.

Margin of error does not scale with population size. A random sample of 1,000 gives a \(\pm 3\%\) margin whether the population is 100,000 or 300 million, as long as it is a random sample.

Hypothesis Testing

Inference · Data Science Statistics

The Logic

Assume the boring explanation (the null hypothesis \(H_0\): no difference, no effect, no association). Compute how surprising the data would be if \(H_0\) were true. If surprising enough, reject \(H_0\) in favor of the alternative \(H_a\). The test never proves \(H_0\); it either rejects it or fails to.

  1. State \(H_0\) and \(H_a\) (two-sided unless you decided a direction before seeing the data).
  2. Choose the significance level \(\alpha\) (0.05 by convention; lower when false positives are costly).
  3. Pick the test from the table below based on the data types and design; check its assumptions.
  4. Compute the test statistic and the p-value.
  5. Decide: \(p \le \alpha\) rejects \(H_0\). Report the effect size and a confidence interval alongside the p-value.

The p-value

The probability, if \(H_0\) is true, of a test statistic at least as extreme as the one observed. It is not the probability that \(H_0\) is true, not the probability the result is due to chance, and not a measure of effect size. A tiny p-value with a huge \(n\) can mean a trivially small effect.

Errors and power

H0 trueH0 false
Reject \(H_0\)Type I error (false positive), probability \(\alpha\)Correct: power \(= 1 - \beta\)
Fail to rejectCorrectType II error (false negative), probability \(\beta\)

Statistical vs practical significance. With a million users, a 0.01% lift is “significant.” Always ask whether the estimated effect is big enough to matter, and whether the interval excludes effects that would.

Choosing a Test

QuestionDataParametric testNonparametric / robust alternativeSciPy
Is one mean equal to a value?One numeric sampleOne-sample t-testWilcoxon signed-rank; bootstrap CIttest_1samp, wilcoxon
Do two independent groups differ in mean?Numeric by 2 groupsWelch two-sample t-testMann-Whitney U; permutation testttest_ind(equal_var=False), mannwhitneyu
Do paired measurements differ?Before/after on same unitsPaired t-testWilcoxon signed-rankttest_rel, wilcoxon
Do 3+ groups differ in mean?Numeric by k groupsOne-way ANOVA (F)Kruskal-Wallisf_oneway, kruskal
Is one proportion equal to a value?Yes/no countsOne-proportion z-test; exact binomialbinomtest; statsmodels proportions_ztest
Do two proportions differ?Yes/no by 2 groupsTwo-proportion z-testFisher's exact (small counts)statsmodels proportions_ztest, fisher_exact
Are two categoricals associated?Contingency tableChi-square test of independenceFisher's exact; permutationchi2_contingency
Do counts match expected shares?One categoricalChi-square goodness of fitchisquare
Are two numerics correlated?Two numeric columnsPearson correlation testSpearman, Kendallpearsonr, spearmanr, kendalltau
Do two samples come from the same distribution?Two numeric samplesKolmogorov-Smirnov; Anderson-Darlingks_2samp, anderson_ksamp
Are variances equal?Numeric by groupsF-test (fragile)Levene; Brown-Forsythelevene

Parametric tests assume a distribution for the sampling statistic (usually normal, via the CLT) and are more powerful when the assumption holds. Nonparametric tests rank the data or permute labels and hold up under skew and outliers at a modest cost in power. For \(n\) in the hundreds or more, the Welch t-test is robust and the usual choice; for small, skewed samples use Mann-Whitney or a permutation test.

Tests on Means

One-sample t
Welch two-sample t

\[t = \frac{\bar{x} - \mu_0}{s / \sqrt{n}}, \qquad df = n - 1\]

Is average session length different from the 5-minute target?

\[t = \frac{\bar{x}_1 - \bar{x}_2}{\sqrt{\dfrac{s_1^2}{n_1} + \dfrac{s_2^2}{n_2}}}\]

Do users on the new onboarding spend more? Welch is the default: it does not assume equal variances and costs almost nothing when they are equal.

Paired t
ANOVA

\[t = \frac{\bar{d}}{s_d / \sqrt{n}}, \qquad d_i = x_i^{\text{after}} - x_i^{\text{before}}\]

Same units measured twice (same stores before and after a price change). Pairing removes between-unit variation and is far more powerful than treating the two columns as independent groups.

\[F = \frac{\text{between-group variance}}{\text{within-group variance}} = \frac{\sum_g n_g(\bar{x}_g - \bar{x})^2 / (k-1)}{\sum_g \sum_i (x_{gi} - \bar{x}_g)^2 / (N-k)}\]

Tests whether any of \(k\) group means differ. A significant F says at least one does; follow with pairwise tests corrected for multiple comparisons (Tukey HSD: statsmodels.stats.multicomp.pairwise_tukeyhsd).

A complete Welch test, step by step
The numbers
  1. Hypotheses. \(H_0: \mu_A = \mu_B\) (new onboarding does not change minutes per session); \(H_a: \mu_A \ne \mu_B\). Two-sided, \(\alpha = 0.05\).
  2. Statistic. \(t = (\bar{x}_A - \bar{x}_B) / \text{SE}\) with \(\text{SE} = \sqrt{s_A^2/n_A + s_B^2/n_B}\).
  3. Degrees of freedom. Welch-Satterthwaite: \(df = \dfrac{(s_A^2/n_A + s_B^2/n_B)^2}{\frac{(s_A^2/n_A)^2}{n_A - 1} + \frac{(s_B^2/n_B)^2}{n_B - 1}}\). Software does this; by hand, \(\min(n_A, n_B) - 1\) is a safe (conservative) stand-in.
  4. p-value. \(2 \times P(T_{df} \gt |t|)\), from 2 * stats.t.sf(abs(t), df), or compare \(|t|\) with \(t^*_{df}\).
  5. Decide and conclude in context, with the effect size and its interval.

Control: \(n_A = 50\), \(\bar{x}_A = 5.4\), \(s_A = 2.0\). New onboarding: \(n_B = 60\), \(\bar{x}_B = 6.2\), \(s_B = 2.4\).

\(\text{SE} = \sqrt{4/50 + 5.76/60} = \sqrt{0.080 + 0.096} = \sqrt{0.176} = 0.420\). \(t = (5.4 - 6.2)/0.420 = -1.91\). Welch \(df = 0.176^2 / (0.080^2/49 + 0.096^2/59) = 108\). \(p = 2 \times P(T_{108} \gt 1.91) = 0.059\); the critical value \(t^*_{108} = 1.98\) and \(|t| = 1.91\) falls short of it.

Conclusion: fail to reject \(H_0\) at 5%. The new onboarding averaged 0.8 minutes more per session (about 0.36 SDs, chapter 6 effect sizes), but with these sample sizes a difference this large would arise by chance about 6% of the time, so the evidence is suggestive, not conclusive. Report the 95% interval for the difference, \(0.8 \pm 1.98 \times 0.42 = (-0.03,\ 1.63)\) minutes, which includes zero but also includes effects large enough to matter: collect more data rather than declaring no effect.

Mean tests in SciPy

a = df.loc[df.group == "A", "minutes"]; b = df.loc[df.group == "B", "minutes"]
stats.ttest_1samp(a, popmean=5)
stats.ttest_ind(a, b, equal_var=False)                       # Welch
stats.ttest_rel(df["before"], df["after"])                   # paired
stats.f_oneway(*[g["minutes"] for _, g in df.groupby("plan")])
stats.mannwhitneyu(a, b, alternative="two-sided")            # rank-based alternative
# permutation test of the difference in means
res = stats.permutation_test((a, b), lambda x, y: x.mean() - y.mean(), n_resamples=9999, random_state=0)
res.statistic, res.pvalue

Every SciPy test returns a result with .statistic and .pvalue (the \(t\), \(F\), \(U\) or permutation statistic, and the two-sided p-value); ttest_ind and ttest_1samp also carry .df and a .confidence_interval() method. Read pvalue against \(\alpha\), then go back to the group means (or res.confidence_interval()) for the size of the effect, which the p-value never tells you. mannwhitneyu tests whether one group tends to have larger values, not whether the means differ, so describe its result in those words.

Tests on Proportions and Categories

Two-proportion z
Chi-square

\[z = \frac{\hat{p}_1 - \hat{p}_2}{\sqrt{\hat{p}(1-\hat{p})\left(\frac{1}{n_1} + \frac{1}{n_2}\right)}},\]

\[\hat{p} = \frac{x_1 + x_2}{n_1 + n_2}\]

Uses the pooled proportion under \(H_0\). This is the classic A/B conversion test; equivalent to the chi-square test on the 2×2 table.

\[\chi^2 = \sum_{\text{cells}} \frac{(O - E)^2}{E},\]

\[E_{ij} = \frac{(\text{row}_i)(\text{col}_j)}{N}\]

Degrees of freedom \((r-1)(c-1)\) for independence; \(k-1\) for goodness of fit. Needs expected counts of at least about 5 per cell; otherwise use Fisher's exact or combine cells. Effect size: Cramér's \(V = \sqrt{\chi^2 / (N \cdot \min(r-1, c-1))}\).

Worked example: two conversion rates
Worked example: goodness of fit

A: 57 of 1,200 converted; B: 81 of 1,210. \(H_0: p_A = p_B\), \(H_a: p_A \ne p_B\), \(\alpha = 0.05\).

\(\hat{p}_A = 0.0475\), \(\hat{p}_B = 0.0669\). Pooled \(\hat{p} = 138/2410 = 0.0573\). \(\text{SE} = \sqrt{0.0573 \times 0.9427 \times (1/1200 + 1/1210)} = \sqrt{0.0000896} = 0.00947\). \(z = (0.0669 - 0.0475)/0.00947 = 2.05\). Two-sided \(p = 2 \times P(Z \gt 2.05) = 0.040\).

Reject \(H_0\) at 5%: B converts 1.9 percentage points better (a 41% relative lift), 95% CI for the difference \(0.0194 \pm 1.96 \times 0.00945 = (0.001,\ 0.038)\). The interval barely clears zero, so the lift is real but its size is very uncertain: anywhere from negligible to doubling.

Plan mix should be 50 / 30 / 20% across three plans; 100 signups split 48 / 35 / 17. \(H_0\): the shares are 0.5, 0.3, 0.2. Expected counts \(E = 50, 30, 20\) (share × \(N\)).

\(\chi^2 = \frac{(48-50)^2}{50} + \frac{(35-30)^2}{30} + \frac{(17-20)^2}{20} = 0.08 + 0.83 + 0.45 = 1.36\), \(df = 3 - 1 = 2\). Critical value \(\chi^2_{0.05, 2} = 5.99\); \(p = P(\chi^2_2 \gt 1.36) = 0.51\).

Fail to reject: this month's mix is consistent with the expected shares. Note that every expected count is above 5, so the test is valid, and that the test used counts, never the percentages.

Proportion and category tests

from statsmodels.stats.proportion import proportions_ztest
proportions_ztest(count=[57, 81], nobs=[1200, 1210])          # z, p for two conversion rates
table = pd.crosstab(df["plan"], df["churned"])
chi2, p, dof, expected = stats.chi2_contingency(table)
v = np.sqrt(chi2 / (table.values.sum() * (min(table.shape) - 1)))   # Cramer's V
stats.fisher_exact([[8, 2], [1, 5]])                                # small 2x2
stats.chisquare(f_obs=[48, 35, 17], f_exp=[50, 30, 20])             # goodness of fit

The first call prints (2.05, 0.040) for the two conversion rates worked above (the sign of \(z\) depends on which group you list first; the p-value does not). chi2_contingency returns four things: the statistic, its p-value, the degrees of freedom and the table of expected counts, which you should glance at for cells below 5. The last line prints (1.36, 0.51), matching the goodness-of-fit example.

Effect Sizes

Effect sizeFormulaSmall / medium / large (Cohen)For
Cohen's \(d\)\(\dfrac{\bar{x}_1 - \bar{x}_2}{s_{\text{pooled}}}\)0.2 / 0.5 / 0.8Difference of means in SD units
Risk difference\(p_2 - p_1\)contextAbsolute lift in a rate
Relative risk\(p_2 / p_1\)contextRelative lift; “1.15” is a 15% lift
Odds ratio\(\dfrac{p_2/(1-p_2)}{p_1/(1-p_1)}\)1.5 / 2.5 / 4Logistic regression; case-control designs
Cramér's \(V\)\(\sqrt{\chi^2 / (N \min(r-1,c-1))}\)0.1 / 0.3 / 0.5Strength of a categorical association
\(\eta^2\)\(SS_{\text{between}} / SS_{\text{total}}\)0.01 / 0.06 / 0.14Share of variance explained by groups (ANOVA)
\(r\), \(R^2\)chapter 80.1 / 0.3 / 0.5 for \(r\)Linear association

Report an effect size with every p-value. The p-value says whether an effect is detectable at this \(n\); the effect size says whether it matters.

Worked example (the onboarding test above): \(s_{\text{pooled}} = \sqrt{\frac{(n_A - 1)s_A^2 + (n_B - 1)s_B^2}{n_A + n_B - 2}} = \sqrt{\frac{49 \times 4 + 59 \times 5.76}{108}} = \sqrt{4.96} = 2.23\), so \(d = 0.8 / 2.23 = 0.36\): a small-to-medium effect. Pooled SD is appropriate for \(d\) even when you used the Welch test, because \(d\) describes the difference in typical-spread units rather than testing it. For the conversion example, risk difference \(= 0.0194\), relative risk \(= 0.0669/0.0475 = 1.41\), odds ratio \(= \frac{0.0669/0.9331}{0.0475/0.9525} = 1.44\); for rare outcomes the odds ratio and relative risk nearly coincide.

Multiple Comparisons

Run 20 independent tests at \(\alpha = 0.05\) on pure noise and you expect one false positive. Testing many metrics, many segments or many variants inflates the family-wise error rate: \(1 - (1 - 0.05)^{20} = 0.64\).

Bonferroni
Benjamini-Hochberg (FDR)

\[\alpha_{\text{each}} = \frac{\alpha}{m}\]

Controls the probability of any false positive. Simple and conservative; power drops fast as \(m\) grows. Holm's step-down version is uniformly better and just as safe.

Controls the false discovery rate: the expected share of rejected hypotheses that are false. Sort p-values, reject the largest \(p_{(k)} \le \frac{k}{m}\alpha\) and everything smaller. The right tool when you screen many features or segments and can tolerate some false leads.

Adjusting p-values

from statsmodels.stats.multitest import multipletests
pvals = [0.001, 0.012, 0.03, 0.04, 0.2]
reject, p_adj, _, _ = multipletests(pvals, alpha=0.05, method="holm")
reject, p_adj, _, _ = multipletests(pvals, alpha=0.05, method="fdr_bh")

What the code prints for these five p-values. Holm: sort them, compare the smallest with \(0.05/5 = 0.01\), the next with \(0.05/4 = 0.0125\), then \(0.05/3 = 0.0167\), and stop at the first failure. \(0.001 \lt 0.01\) and \(0.012 \lt 0.0125\) pass, \(0.03 \gt 0.0167\) fails, so reject is [True, True, False, False, False] and p_adj is [0.005, 0.048, 0.09, 0.09, 0.2]. Benjamini-Hochberg compares the \(k\)th smallest with \(\frac{k}{5} \times 0.05\): \(0.01, 0.02, 0.03, 0.04, 0.05\). The fourth p-value, 0.04, is at or below its threshold, so it and everything smaller are rejected: [True, True, True, True, False], with p_adj \(= [0.005, 0.03, 0.05, 0.05, 0.2]\). Same data, two more discoveries, because FDR tolerates a few false leads where Holm tolerates none.

p-hacking and the garden of forking paths. Choosing which metric, segment, time window or outlier rule to report after looking at the data is multiple testing without the correction. Pre-register the primary metric and analysis plan before the experiment runs (chapter 7).

A/B Testing and Experimental Design

Inference · Data Science Statistics

Why Randomize

Observational data can show association but confounders hide behind every correlation (users who adopt the new feature were already more engaged). Random assignment breaks that link: on average the groups differ only in the treatment, so the difference in outcomes is the causal effect. An A/B test is a randomized controlled trial run on a product.

Vocabulary
Threats to validity
  • Unit of randomization: user, session, device, store. Analyze at the same level you randomized.
  • Treatment / control (A / B): the variants; keep everything else identical.
  • Primary metric: the one pre-registered outcome the decision rides on.
  • Guardrail metrics: things that must not get worse (latency, revenue, crashes).
  • Minimum detectable effect (MDE): the smallest lift worth shipping; it sets the sample size.
  • Sample ratio mismatch: a 50/50 split that comes out 52/48 with large \(n\) means the assignment or logging is broken; chi-square test the split before anything else.
  • Interference / spillover: treated users affect control users (marketplaces, social features). Randomize by cluster or region.
  • Novelty and primacy effects: early reactions fade; run at least a full business cycle (usually 1 to 2 weeks, whole weeks).
  • Peeking: checking the p-value daily and stopping when it dips below 0.05 inflates false positives far above 5%.

Sample Size and Power

\[n_{\text{per group}} \approx \frac{2\,(z_{1-\alpha/2} + z_{1-\beta})^2\,\sigma^2}{\delta^2}\]

\[\text{for proportions: } \sigma^2 \approx \bar{p}(1-\bar{p})\]

The inputs
The uncomfortable arithmetic
  • \(\alpha\): false-positive rate, usually 0.05 two-sided (\(z = 1.96\)).
  • Power \(1 - \beta\): usually 0.8 (\(z = 0.84\)); 0.9 for expensive decisions (\(z = 1.28\)).
  • \(\delta\): the MDE in absolute units (a lift from 5.0% to 5.5% is \(\delta = 0.005\)).
  • \(\sigma^2\): the outcome variance from historical data.
  • With \(\alpha = 0.05\) and power 0.8, \((1.96 + 0.84)^2 \approx 7.85\), so \(n \approx 15.7\,\sigma^2/\delta^2\) per group.

Detecting a lift from 5.0% to 5.5% conversion needs about \(15.7 \times 0.0499 / 0.005^2 \approx 31{,}000\) users per group. Halving the MDE quadruples the sample. Small effects on rare events need enormous traffic, which is why teams use variance reduction (CUPED), proxy metrics or longer runs.

Power calculations in statsmodels

from statsmodels.stats.power import NormalIndPower, TTestIndPower
from statsmodels.stats.proportion import proportion_effectsize
p1, p2 = 0.05, 0.055
h = proportion_effectsize(p2, p1)                       # Cohen's h
NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.8, ratio=1)   # n per group ~ 31k
# continuous metric: revenue per user with sd 40, want to detect +2
TTestIndPower().solve_power(effect_size=2 / 40, alpha=0.05, power=0.8)       # ~ 6,280 per group
# power you actually have with the traffic available
TTestIndPower().power(effect_size=2 / 40, nobs1=3000, alpha=0.05)

Run time = required n ÷ eligible users per day, rounded up to whole weeks. If that is 3 months, the test is not feasible as designed: raise the MDE, pick a more sensitive metric, or reduce variance.

Analyzing the Result

Conversion metrics
Continuous metrics (revenue, time)
  • Two-proportion z-test or chi-square on the 2×2 table (chapter 6).
  • Report absolute lift, relative lift and the CI of the difference.
  • Check the sample ratio first.
  • Welch t-test on per-user values. Revenue is heavily skewed with many zeros; the CLT still works at A/B sample sizes, but check with a bootstrap.
  • Consider trimming or winsorizing extreme users by a rule fixed in advance.
  • Ratio metrics (clicks per session when you randomized by user): use the delta method or bootstrap over users, not sessions.

A/B analysis

from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep
conv = df.groupby("variant")["converted"].agg(["sum", "count"])
z, p = proportions_ztest(conv["sum"].values, conv["count"].values)
lo, hi = confint_proportions_2indep(conv.loc["B", "sum"], conv.loc["B", "count"], conv.loc["A", "sum"], conv.loc["A", "count"])
# sample ratio mismatch
stats.chisquare(conv["count"].values)             # p < 0.001 means stop and debug the assignment
# revenue
a = df.loc[df.variant == "A", "revenue"]; b = df.loc[df.variant == "B", "revenue"]
stats.ttest_ind(a, b, equal_var=False)
stats.bootstrap((b.to_numpy(), a.to_numpy()), lambda y, x: y.mean() - x.mean(), random_state=0).confidence_interval

Reading the output: z, p is the pooled two-proportion test for conversion; lo, hi is the 95% interval for \(p_B - p_A\) in absolute points, the number to quote (“B converts 1.9 points better, 95% CI 0.1 to 3.8”). The sample ratio check returns a chi-square statistic and p-value for the split of users across variants; a tiny p-value means the split itself is off and no result below it can be trusted. The revenue block gives a Welch \(t\) and p-value plus a bootstrap interval for the difference in mean revenue; if the two disagree noticeably, the revenue distribution is too skewed for the \(t\) at this \(n\) and the bootstrap interval is the one to report.

Variance Reduction: CUPED

\[Y_i^{\text{adj}} = Y_i - \theta\,(X_i - \bar{X}),\]

\[\theta = \frac{\operatorname{Cov}(X, Y)}{\operatorname{Var}(X)}\]

Use each user's pre-experiment value of the metric \(X\) to remove the part of the outcome \(Y\) that was predictable before the test. Because assignment was random, \(X\) is balanced across groups and the adjustment is unbiased. Variance falls by a factor of \(1 - \rho^2\); with a pre-period correlation of 0.7 you need half the sample. It is the same idea as including a covariate in a regression of \(Y\) on treatment.

CUPED

theta = np.cov(df["pre_revenue"], df["revenue"])[0, 1] / df["pre_revenue"].var()
df["revenue_cuped"] = df["revenue"] - theta * (df["pre_revenue"] - df["pre_revenue"].mean())
a = df.loc[df.variant == "A", "revenue_cuped"]; b = df.loc[df.variant == "B", "revenue_cuped"]
stats.ttest_ind(a, b, equal_var=False)
# the regression form gives the same answer with a standard error attached
import statsmodels.formula.api as smf
smf.ols("revenue ~ C(variant) + pre_revenue", data=df).fit().summary().tables[1]

Beyond Two Fixed-Horizon Variants

Many variants (A/B/n)
Sequential testing

ANOVA or a chi-square across all arms first, then pairwise comparisons corrected with Holm or Bonferroni (chapter 6). Each extra arm splits the traffic and lengthens the run.

If you must look early, use a method built for it: group-sequential boundaries (O'Brien-Fleming), always-valid p-values from mixture sequential probability ratio tests, or Bayesian decision rules. These spend the \(\alpha\) across looks so the overall false-positive rate stays at 5%.

Bayesian A/B
Multi-armed bandits

Put Beta priors on each conversion rate; the posteriors are Beta too (chapter 11). Then compute \(P(B \gt A)\) and the expected loss from shipping each arm by Monte Carlo. Interpretable (“94% chance B is better, and if we are wrong we lose at most 0.1 points”) and tolerant of peeking when paired with an expected-loss stopping rule.

Thompson sampling or UCB shift traffic toward the winning arm during the test. Good for short-lived decisions (headlines, promotions) where the cost of showing the loser matters more than a clean estimate; worse for learning the true effect size.

Quasi-experiments when you cannot randomize
The report
  • Difference-in-differences: compare the change over time in a treated group with the change in an untreated group; assumes parallel trends.
  • Regression discontinuity: compare units just above and just below an eligibility cutoff.
  • Interrupted time series / synthetic control: forecast what would have happened and compare.
  • Propensity matching: pair treated and untreated units with similar covariates; only adjusts for what you measured.
  • Hypothesis, primary metric and MDE as pre-registered.
  • Sample sizes per arm and the sample ratio check.
  • Estimate, CI and p-value for the primary metric; guardrails.
  • Segments only as exploratory, flagged as such.
  • Decision and the uncertainty around it.

Correlation and Linear Regression

Modeling · Data Science Statistics

Correlation

Pearson's r
Spearman's rho and Kendall's tau

\[r = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i-\bar{x})^2 \sum (y_i-\bar{y})^2}}\]

Strength and direction of a linear relationship, from \(-1\) to \(1\). Sensitive to outliers; blind to curves. \(r^2\) is the share of variance in \(y\) explained by a line in \(x\).

Pearson on the ranks. Captures any monotonic relationship and shrugs off outliers and skew. Use Spearman when the data are ordinal or heavy-tailed; Kendall for small samples with many ties.

Testing a correlation
Four warnings

\[t = \frac{r\sqrt{n-2}}{\sqrt{1-r^2}}, \qquad df = n-2\]

stats.pearsonr(x, y) returns \(r\) and the p-value against \(H_0: \rho = 0\). For a CI use the Fisher \(z\) transform or pearsonr(...).confidence_interval().

  • Correlation is not causation: confounders, reverse causation, selection.
  • Anscombe's quartet: four data sets with identical \(r\) and wildly different shapes. Plot it.
  • Restriction of range shrinks \(r\) (admitted students' test scores vs grades).
  • Ecological fallacy: a correlation across groups need not hold across individuals.

Correlation in Python

stats.pearsonr(df["ad_spend"], df["sales"])
stats.spearmanr(df["ad_spend"], df["sales"])
df.corr(numeric_only=True).style.background_gradient(cmap="coolwarm", vmin=-1, vmax=1)

Simple Linear Regression

\[\hat{y} = b_0 + b_1 x\]

\[b_1 = r\,\frac{s_y}{s_x} = \frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{\sum (x_i-\bar{x})^2}\]

\[b_0 = \bar{y} - b_1\bar{x}\]

Reading the output
Inference on the slope
  • Slope \(b_1\): the expected change in \(y\) for a one-unit increase in \(x\).
  • Intercept \(b_0\): expected \(y\) when \(x = 0\); meaningful only if 0 is in the data's range.
  • Residual \(e_i = y_i - \hat{y}_i\): what the line misses. Least squares minimizes \(\sum e_i^2\).
  • \(R^2\): share of variance in \(y\) explained; equals \(r^2\) with one predictor.
  • Residual standard error: typical size of a miss, in \(y\) units.

\[t = \frac{b_1}{\text{SE}(b_1)},\]

\[\text{SE}(b_1) = \frac{s_e}{\sqrt{\sum (x_i-\bar{x})^2}}\]

A 95% CI is \(b_1 \pm t^*_{n-2}\,\text{SE}(b_1)\). The p-value tests \(H_0: \beta_1 = 0\). A confidence interval for the mean response at \(x_0\) is narrow; a prediction interval for a single new \(y\) is much wider because it adds the residual noise.

Worked example: five points by hand
Reading what came out

Ad spend \(x\): 1, 2, 3, 4, 5 (thousands); sales \(y\): 2, 4, 5, 4, 5 (thousands). \(\bar{x} = 3\), \(\bar{y} = 4\).

\(\sum (x_i - \bar{x})(y_i - \bar{y}) = (-2)(-2) + (-1)(0) + 0(1) + 1(0) + 2(1) = 6\); \(\sum (x_i - \bar{x})^2 = 4 + 1 + 0 + 1 + 4 = 10\). So \(b_1 = 6/10 = 0.6\) and \(b_0 = 4 - 0.6 \times 3 = 2.2\): \(\hat{y} = 2.2 + 0.6x\).

Fitted values 2.8, 3.4, 4.0, 4.6, 5.2; residuals \(-0.8, 0.6, 1.0, -0.6, -0.2\); \(SSE = \sum e_i^2 = 2.4\); \(SST = \sum (y_i - \bar{y})^2 = 6\). \(R^2 = 1 - 2.4/6 = 0.60\). \(s_e = \sqrt{SSE/(n-2)} = \sqrt{2.4/3} = 0.894\). \(\text{SE}(b_1) = 0.894/\sqrt{10} = 0.283\); \(t = 0.6/0.283 = 2.12\) on 3 df, \(p = 0.12\); 95% CI for the slope \(0.6 \pm 3.182 \times 0.283 = (-0.30,\ 1.50)\).

  • Slope 0.6: each extra thousand of ad spend goes with 600 more in sales, on average.
  • Intercept 2.2: predicted sales with zero spend; here 0 is just outside the data (1 to 5), so treat it as an anchor for the line, not a forecast.
  • \(R^2 = 0.60\): the line accounts for 60% of the variation in sales; 40% is left in the residuals.
  • \(s_e = 0.89\): a typical prediction misses by about 0.9 thousand.
  • \(p = 0.12\), CI includes 0: with five points the slope is not distinguishable from zero even though it looks positive. The interval says the true effect could be anywhere from slightly negative to 1.5. More data, not a stronger adjective, is the fix.

Watch out. A high \(R^2\) does not make the slope causal, and a low p-value does not make the effect large: with \(n = 10{,}000\) a slope of 0.01 can be “highly significant.” Report the slope in units a reader can act on, with its interval.

Multiple Regression

\[\hat{y} = b_0 + b_1 x_1 + b_2 x_2 + \cdots + b_k x_k\]

\[\mathbf{b} = (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}\]

Interpreting coefficients
Judging the model
  • Each \(b_j\) is the expected change in \(y\) for a one-unit increase in \(x_j\) holding the other predictors fixed. Adding or removing predictors changes every coefficient.
  • Categorical predictors become dummy (one-hot) columns with one level left out as the baseline; each coefficient is the difference from the baseline.
  • Interactions \(x_1 x_2\) let the effect of one predictor depend on another.
  • Log transforms: \(\log y\) on \(x\): a unit of \(x\) multiplies \(y\) by \(e^{b}\) (about \(100b\%\) for small \(b\)). \(\log y\) on \(\log x\): \(b\) is an elasticity.
  • Standardized coefficients (predictors scaled to SD 1) are comparable across predictors.
  • Adjusted \(R^2\) \(= 1 - (1-R^2)\frac{n-1}{n-k-1}\) penalizes useless predictors; plain \(R^2\) never decreases when you add one.
  • F-test: do the predictors jointly explain anything? \(H_0\): all slopes are 0.
  • AIC / BIC: lower is better when comparing models on the same data.
  • Out-of-sample error (chapter 10) is the only judge that matters for prediction.

Regression in statsmodels and scikit-learn

import statsmodels.formula.api as smf
m = smf.ols("sales ~ ad_spend + price + C(region) + ad_spend:price", data=df).fit()
print(m.summary())                      # coefficients, SEs, t, p, CIs, R2, adj R2, F, AIC
m.params, m.conf_int(), m.pvalues
m.predict(pd.DataFrame({"ad_spend": [50], "price": [9.99], "region": ["West"]}))
m.get_prediction(new).summary_frame(alpha=0.05)   # mean CI and prediction interval
# scikit-learn for pipelines and prediction
from sklearn.linear_model import LinearRegression
lr = LinearRegression().fit(X_train, y_train); lr.coef_, lr.intercept_, lr.score(X_test, y_test)

Reading m.summary(): the top block gives \(R^2\), adjusted \(R^2\), the F-statistic with its p-value (do the predictors jointly explain anything), AIC and BIC. The coefficient table has one row per term: coef is \(b_j\) in the units of \(y\) per unit of \(x_j\); std err its standard error; t is coef / std err; P>|t| the two-sided p-value for \(H_0: \beta_j = 0\); [0.025 0.975] the 95% interval. A row like C(region)[T.West] is the difference between West and the baseline region, holding spend and price fixed; ad_spend:price is the interaction, meaning the effect of spend changes by that amount for each unit of price. summary_frame returns mean_ci_lower/upper (where the average sales at those inputs lie) and obs_ci_lower/upper (where a single new observation would lie, much wider). lr.score is \(R^2\) on the test set, the honest version.

Assumptions and Diagnostics

AssumptionWhy it mattersCheckFix
LinearityCoefficients mean nothing if the relationship curvesResiduals vs fitted: no patternTransform \(x\) or \(y\); add polynomial terms or splines; use a tree model or GAM
Independent errorsStandard errors are wrong under autocorrelation or clusteringDurbin-Watson near 2 for time order; think about the designCluster-robust SEs (cov_type="cluster"); time-series models; mixed models
Constant variance (homoscedasticity)SEs and intervals are off when spread grows with the fitted valueFan shape in residuals vs fitted; Breusch-Pagan testLog \(y\); robust (HC3) standard errors; weighted least squares
Normal errorsNeeded for exact small-sample t and F; not for unbiased coefficientsQ-Q plot of residualsUsually fine at large \(n\) (CLT); transform \(y\) for heavy tails; bootstrap
No perfect multicollinearityCorrelated predictors give unstable coefficients with huge SEsVIF \(= 1/(1-R_j^2)\) above 5 to 10Drop or combine predictors; ridge regression; accept it if you only need predictions
No influential outliersA single point can swing the fitCook's distance, leverage plotsCheck for data errors; robust regression (Huber); report with and without

Diagnostics

import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.stats.diagnostic import het_breuschpagan
fig = sm.graphics.plot_regress_exog(m, "ad_spend")       # residual plots
sm.qqplot(m.resid, line="45")
het_breuschpagan(m.resid, m.model.exog)                  # LM stat, p
X = m.model.exog
[variance_inflation_factor(X, i) for i in range(1, X.shape[1])]
m.get_influence().cooks_distance[0]
m_robust = smf.ols("sales ~ ad_spend + price", data=df).fit(cov_type="HC3")   # robust SEs

For prediction, the assumptions matter less than out-of-sample error. For explanation and inference (is this coefficient real, how big is it), they matter a great deal, and so does whether you have controlled for the confounders you can measure.

Regularization: Ridge and Lasso

Ridge (L2)
Lasso (L1)

\[\min_{\mathbf{b}} \sum (y_i - \hat{y}_i)^2 + \lambda \sum_j b_j^2\]

Shrinks coefficients toward zero but never to zero. Stabilizes correlated predictors and reduces variance at a small cost in bias. Standardize predictors first.

\[\min_{\mathbf{b}} \sum (y_i - \hat{y}_i)^2 + \lambda \sum_j |b_j|\]

Drives some coefficients exactly to zero: built-in feature selection. Elastic net mixes both. Choose \(\lambda\) by cross-validation (RidgeCV, LassoCV), never by in-sample fit.

Regularized regression

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import RidgeCV, LassoCV
ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 25))).fit(X_train, y_train)
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=0)).fit(X_train, y_train)
lasso[-1].alpha_, (lasso[-1].coef_ != 0).sum()      # chosen lambda, features kept

\(\lambda\) (called alpha in scikit-learn) sets the price of coefficient size: \(\lambda = 0\) is ordinary least squares, and as \(\lambda\) grows every coefficient is pulled toward zero, trading a little bias for less variance. RidgeCV and LassoCV try a grid of values and keep the one with the lowest cross-validated error; the last line prints that chosen value and how many predictors the lasso kept. Read a lasso coefficient of exactly 0 as “dropped,” and read the surviving coefficients on the standardized scale (change in \(y\) per one SD of \(x_j\)), which is why the scaler sits inside the pipeline. When two predictors are highly correlated the lasso keeps one more or less at random, so do not read its selection as a verdict on the other.

Logistic Regression and Classification Metrics

Modeling · Data Science Statistics

Logistic Regression

\[P(y = 1 \mid \mathbf{x}) = \sigma(z) = \frac{1}{1 + e^{-z}},\]

\[z = b_0 + b_1 x_1 + \cdots + b_k x_k = \log\frac{p}{1-p}\]

Why not a line
Reading coefficients

A straight line predicts probabilities below 0 and above 1 and has non-constant error variance. The logit link maps the linear predictor onto \((0, 1)\). The model is fit by maximum likelihood, minimizing the log loss (binary cross-entropy): \(-\frac{1}{n}\sum [y_i \log \hat{p}_i + (1-y_i)\log(1-\hat{p}_i)]\).

  • \(b_j\) is the change in log-odds per unit of \(x_j\), other predictors fixed.
  • \(e^{b_j}\) is the odds ratio: 1.3 means the odds of \(y = 1\) are multiplied by 1.3 per unit. Odds are \(p/(1-p)\), not probability.
  • The effect on probability depends on where you start: a given change in log-odds moves \(p\) most near 0.5 and least near 0 or 1. Report average marginal effects or predicted probabilities at typical values.
  • The intercept is the log-odds when every predictor is 0 (or at the baseline level).

Logistic regression

import statsmodels.formula.api as smf
m = smf.logit("churned ~ tenure + monthly_charges + C(contract)", data=df).fit()
print(m.summary())
np.exp(m.params)                                      # odds ratios
np.exp(m.conf_int())                                  # their CIs
m.get_margeff(at="overall").summary()                 # average marginal effects on probability
# scikit-learn (adds L2 regularization by default: set penalty=None for plain MLE)
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = clf.predict_proba(X_test)[:, 1]

Worked reading. Suppose the summary shows tenure with coef = -0.05 (per month) and P>|z| < 0.001. Then \(e^{-0.05} = 0.951\): each additional month of tenure multiplies the odds of churn by 0.951, a 4.9% drop in odds per month, and 12 months multiply the odds by \(e^{-0.6} = 0.55\). To turn a linear predictor into a probability, suppose a customer's \(z = b_0 + \sum b_j x_j\) comes to \(-1.2\): \(\hat{p} = 1/(1 + e^{1.2}) = 0.23\). At \(z = 0.4\), \(\hat{p} = 0.60\). get_margeff reports the average change in probability per unit, which is what a manager usually wants: a value of \(-0.008\) for tenure would mean about 0.8 percentage points less churn per month of tenure, averaged over the customers you have. predict_proba(...)[:, 1] is the column for class 1; column 0 is \(1 - \hat{p}\).

Multiclass: multinomial (softmax) logistic regression generalizes the logit to \(k\) classes; one-vs-rest fits \(k\) binary models. Separation: if a predictor perfectly splits the classes, the MLE diverges; regularize or use Firth's correction.

The Confusion Matrix

Predicted positivePredicted negative
Actually positiveTrue positive (TP)False negative (FN), Type II
Actually negativeFalse positive (FP), Type ITrue negative (TN)
MetricFormulaAnswersUse when
Accuracy\(\dfrac{TP + TN}{N}\)How often is the prediction right?Classes are balanced and errors cost the same; otherwise it misleads (99% accuracy on 1% fraud by predicting “no”)
Precision (PPV)\(\dfrac{TP}{TP + FP}\)Of the flagged, how many are real?False positives are costly: spam filters, fraud reviews with limited analysts
Recall (sensitivity, TPR)\(\dfrac{TP}{TP + FN}\)Of the real positives, how many did we catch?Misses are costly: disease screening, safety
Specificity (TNR)\(\dfrac{TN}{TN + FP}\)Of the real negatives, how many were cleared?Pairs with sensitivity in medical tests
F1\(\dfrac{2 \cdot P \cdot R}{P + R}\)Harmonic mean of precision and recallOne number for an imbalanced problem; \(F_\beta\) weights recall \(\beta\) times more
False positive rate\(\dfrac{FP}{FP + TN}\)Share of negatives wrongly flaggedThe x-axis of the ROC curve
Matthews correlation\(\dfrac{TP \cdot TN - FP \cdot FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}}\)Correlation between truth and predictionBalanced single score even with heavy imbalance

Precision and recall trade off through the decision threshold: lowering the probability cutoff from 0.5 catches more positives (recall up) at the cost of more false alarms (precision down). The right threshold comes from the costs of each error, not from 0.5.

Worked example: 1,000 transactions, 50 of them fraud. At a 0.5 threshold the model flags 60: \(TP = 40\), \(FP = 20\), \(FN = 10\), \(TN = 930\). Accuracy \(= 970/1000 = 0.97\), but predicting “not fraud” for everyone would score 0.95, so accuracy says almost nothing here. Precision \(= 40/60 = 0.667\): two of every three alerts are real. Recall \(= 40/50 = 0.80\): the model catches four fraud cases in five and misses one. Specificity \(= 930/950 = 0.979\); false positive rate \(= 20/950 = 0.021\). \(F_1 = 2(0.667)(0.8)/(0.667 + 0.8) = 0.727\). Lowering the threshold would move cases from FN to TP (recall up) but also from TN to FP (precision down); whether that is worth it depends on the cost of a missed fraud against the cost of an analyst reviewing a false alarm.

Watch out. Precision and recall share a numerator, not a denominator: precision divides by what was predicted positive (a column), recall by what is positive (a row). scikit-learn's confusion_matrix puts true labels on rows and predicted on columns, with the negative class first, so the layout is [[TN, FP], [FN, TP]], the opposite corner from this table.

Threshold-Free Metrics

ROC curve and AUC
Precision-recall curve and average precision

Plot true positive rate against false positive rate for every threshold. The AUC is the probability that a random positive is scored above a random negative: 0.5 is coin-flipping, 1.0 is perfect. Insensitive to class balance and to the threshold, which is both its strength and its blind spot: on rare positives a high AUC can hide poor precision.

Precision against recall across thresholds. The baseline is the positive rate, not 0.5, so it is the honest view for imbalanced problems (fraud, rare disease, click prediction). Average precision (area under PR) summarizes it.

Log loss (cross-entropy)
Brier score and calibration

\[-\frac{1}{n}\sum_{i=1}^{n}\left[y_i \log \hat{p}_i + (1 - y_i)\log(1 - \hat{p}_i)\right]\]

Punishes confident wrong predictions hard. The training objective of logistic regression and neural classifiers; the metric to watch when the probabilities themselves will be used (ranking, expected value).

\[\text{Brier} = \frac{1}{n}\sum (\hat{p}_i - y_i)^2\]

A model is calibrated when events predicted at 70% happen 70% of the time. Check with a reliability diagram (calibration_curve); fix with Platt scaling or isotonic regression (CalibratedClassifierCV). Tree ensembles and boosted models are often poorly calibrated out of the box.

Classification metrics in scikit-learn

from sklearn.metrics import (confusion_matrix, classification_report, roc_auc_score, roc_curve,
                             precision_recall_curve, average_precision_score, log_loss, brier_score_loss)
pred = (proba >= 0.5).astype(int)
confusion_matrix(y_test, pred)
print(classification_report(y_test, pred, digits=3))
roc_auc_score(y_test, proba), average_precision_score(y_test, proba)
log_loss(y_test, proba), brier_score_loss(y_test, proba)
# pick the threshold that maximizes F1 (or expected profit)
p, r, thr = precision_recall_curve(y_test, proba)
f1 = 2 * p * r / (p + r + 1e-12); best = thr[np.argmax(f1[:-1])]
from sklearn.calibration import calibration_curve
frac_pos, mean_pred = calibration_curve(y_test, proba, n_bins=10)

Imbalanced Classes

What goes wrong
What helps
  • Accuracy looks great while the model ignores the minority class.
  • The default threshold of 0.5 is far from optimal.
  • Rare-class examples get little weight in the loss.
  • Evaluate with PR-AUC, recall at a fixed precision, or cost-weighted metrics.
  • class_weight="balanced" or a custom cost matrix in the loss.
  • Resampling: undersample the majority, oversample the minority (SMOTE) inside cross-validation folds only.
  • Tune the threshold on validation data to the business cost.
  • Report the positive rate in the test set so readers can judge the baseline.

The cost matrix is the real metric. If a missed fraud costs $500 and a false alarm costs $5 of analyst time, pick the threshold that minimizes \(500 \cdot FN + 5 \cdot FP\) on validation data, then report that expected cost alongside precision and recall.

Model Evaluation, Resampling and the Bias-Variance Trade-off

Modeling · Data Science Statistics

Train, Validate, Test

A model's error on the data it was fit to is an optimistic lie. The only honest estimate of how it will do on new data comes from data it never saw. Everything in this chapter is about protecting that estimate.

The three splits
Splits that respect the data
  • Training set: fit the parameters.
  • Validation set (or cross-validation): choose hyperparameters, features, thresholds and between models.
  • Test set: touched once, at the end, to report the final error. If you go back and change the model after seeing it, it has become a validation set.
  • Typical splits 60/20/20 or 80/20 with CV inside the 80.
  • Stratified: keep the class ratio in every split.
  • Grouped: all rows from one user, patient or store go to the same split; otherwise the model memorizes the entity.
  • Time-based: train on the past, test on the future. Random splits on time series leak the future into training.
  • Random with a fixed seed so the result reproduces.

Cross-Validation

k-fold
Variants

Split into \(k\) folds (5 or 10). Train on \(k-1\), validate on the held-out fold, rotate, average the \(k\) scores. Uses all the data for both fitting and validating and gives a spread (report mean ± SD of fold scores). Leave-one-out is \(k = n\): low bias, high variance, slow.

  • StratifiedKFold for classification.
  • GroupKFold when rows cluster by an entity.
  • TimeSeriesSplit: expanding window, always validating on later data.
  • Nested CV: an inner loop tunes hyperparameters, an outer loop estimates error, so tuning does not leak into the estimate.
  • Repeated CV averages over several shufflings for a steadier estimate.

Cross-validation with pipelines

from sklearn.model_selection import cross_val_score, StratifiedKFold, GridSearchCV, TimeSeriesSplit
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))   # scaler fit inside each fold: no leakage
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(pipe, X, y, cv=cv, scoring="roc_auc"); scores.mean(), scores.std()
grid = GridSearchCV(pipe, {"logisticregression__C": np.logspace(-3, 2, 12)}, cv=cv, scoring="roc_auc").fit(X_train, y_train)
grid.best_params_, grid.best_score_
grid.score(X_test, y_test)                            # the one look at the test set
TimeSeriesSplit(n_splits=5)                           # for ordered data

scores is an array of five AUCs, one per held-out fold; report mean ± std (for instance 0.84 ± 0.02). The spread is as informative as the mean: it tells you how much the estimate would move with a different split. grid.best_params_ is the regularization strength \(C\) with the highest mean fold AUC and grid.best_score_ that AUC, which is slightly optimistic because \(C\) was chosen to maximize it. grid.score(X_test, y_test) is the number to put in the report: the AUC of the refit best model on data that played no part in fitting or tuning. If it sits well below best_score_, suspect leakage or a test set that differs from the training distribution.

Leakage is the most common cause of a model that aces validation and fails in production: scaling or imputing on the full data before splitting, target encoding with the target included, features computed from information that arrives after the prediction time, duplicate rows across splits. Put every preprocessing step inside the pipeline so it is fit on training folds only.

Bias and Variance

\[E\left[(y - \hat{f}(x))^2\right] = \underbrace{\text{Bias}[\hat{f}(x)]^2}_{\text{underfitting}} + \underbrace{\operatorname{Var}[\hat{f}(x)]}_{\text{overfitting}} + \underbrace{\sigma^2}_{\text{irreducible noise}}\]

High bias (underfitting)
High variance (overfitting)
  • Training error and validation error are both high and close together.
  • The model is too simple for the pattern: a line through a curve.
  • Fixes: more features, interactions, polynomial terms, a more flexible model, less regularization.
  • Training error is low; validation error is much higher.
  • The model learned the noise: a deep tree, a high-degree polynomial, too many features for the rows.
  • Fixes: more data, regularization, fewer features, pruning or early stopping, ensembling (bagging averages away variance), simpler model.
Learning curves
Validation curves

Plot training and validation error against training set size. Converging high: bias, more data will not help. A persistent gap: variance, more data or regularization will. sklearn.model_selection.learning_curve.

Plot both errors against one hyperparameter (tree depth, \(\lambda\), \(k\) in KNN). The sweet spot is where validation error bottoms out, just before it climbs while training error keeps falling.

Regression Metrics

MetricFormulaUnitsNotes
MSE\(\frac{1}{n}\sum (y_i - \hat{y}_i)^2\)squaredThe training loss for least squares; punishes big misses
RMSE\(\sqrt{\text{MSE}}\)same as \(y\)The most reported; roughly the SD of the errors
MAE\(\frac{1}{n}\sum |y_i - \hat{y}_i|\)same as \(y\)Robust to outliers; the typical miss; optimized by the median
MAPE\(\frac{100}{n}\sum \left|\frac{y_i - \hat{y}_i}{y_i}\right|\)percentUndefined at \(y = 0\), punishes over-forecasts more; sMAPE and WAPE are safer for demand
\(R^2\)\(1 - \frac{\sum (y_i-\hat{y}_i)^2}{\sum (y_i-\bar{y})^2}\)unitlessShare of variance explained vs predicting the mean; can be negative out of sample
Quantile (pinball) loss\(\max(q\,e, (q-1)\,e)\)same as \(y\)For predicting a percentile (p90 demand) rather than the mean

Worked example: actual daily demand \(y = 10, 12, 15, 20\); forecasts \(\hat{y} = 11, 11, 16, 18\); errors \(y - \hat{y} = -1, 1, -1, 2\). \(\text{MSE} = (1 + 1 + 1 + 4)/4 = 1.75\); \(\text{RMSE} = \sqrt{1.75} = 1.32\) units; \(\text{MAE} = (1 + 1 + 1 + 2)/4 = 1.25\) units. MAPE \(= \frac{100}{4}\left(\frac{1}{10} + \frac{1}{12} + \frac{1}{15} + \frac{2}{20}\right) = 8.75\%\). With \(\bar{y} = 14.25\), \(\sum (y_i - \bar{y})^2 = 56.75\) and \(\sum e_i^2 = 7\), so \(R^2 = 1 - 7/56.75 = 0.877\). Read: forecasts are typically off by 1.3 units (about 9%), and the model removes 88% of the variance that predicting the average would leave. RMSE exceeds MAE because the one miss of 2 is squared; when RMSE is far above MAE, a few large errors dominate and are worth looking at individually.

Regression metrics

from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, mean_absolute_percentage_error
rmse = np.sqrt(mean_squared_error(y_test, pred)); mae = mean_absolute_error(y_test, pred)
r2_score(y_test, pred), mean_absolute_percentage_error(y_test, pred)
# always compare with a naive baseline
baseline = np.full_like(y_test, y_train.mean(), dtype=float); np.sqrt(mean_squared_error(y_test, baseline))

Always report a baseline. Predicting the mean, the last value, or the same month last year. A model is only as good as its improvement over the naive answer.

Comparing Models Honestly

  • Same folds for every model (fix the CV splitter's seed) so differences are not split noise.
  • Look at the spread of fold scores, not just the mean; a 0.002 AUC difference with fold SD 0.01 is nothing.
  • A paired test across folds (or a bootstrap of the test-set metric difference) gives a CI on the gap.
  • Judge on the metric tied to the decision, plus calibration if probabilities are used downstream.
  • Prefer the simpler model when the gap is within noise: it is cheaper, more stable and easier to explain.
  • Check performance by segment (region, device, time) for models that are good on average and bad for someone.

Worked example: on the same five folds, model A scores AUC 0.843 and model B 0.846; the fold-by-fold differences (B minus A) average 0.003 with SD 0.004. Paired \(t = 0.003 / (0.004/\sqrt{5}) = 1.68\) on 4 df, \(p = 0.17\): the gap is within split noise. Unless B is also simpler or cheaper, keep A, and say in the write-up that the two were indistinguishable at this sample size rather than that A “won.”

Bayesian Statistics Basics

Modeling · Data Science Statistics

The Bayesian View

Frequentist statistics treats the parameter as fixed and the data as random: a 95% CI is a procedure that works 95% of the time. Bayesian statistics treats the parameter as uncertain and describes that uncertainty with a probability distribution that is updated by the data. The output is a posterior distribution, and you can read probabilities straight off it: “there is a 94% probability the lift is positive.”

\[\underbrace{p(\theta \mid D)}_{\text{posterior}} \;=\; \frac{\overbrace{p(D \mid \theta)}^{\text{likelihood}}\;\overbrace{p(\theta)}^{\text{prior}}}{\underbrace{p(D)}_{\text{evidence}}} \;\propto\; p(D \mid \theta)\,p(\theta)\]

Priors
Posterior summaries
  • Informative: encodes real knowledge (last quarter's conversion was 4 to 6%).
  • Weakly informative: rules out the absurd (a rate between 0 and 1, an effect smaller than 1,000%) without steering the answer. The usual recommendation.
  • Flat / uninformative: lets the data speak; with enough data every reasonable prior gives the same posterior.
  • A prior is an assumption stated out loud. The frequentist equivalents (which test, which model) are assumptions too, just quieter.
  • Posterior mean or median: the point estimate.
  • Credible interval: a 95% interval that contains the parameter with probability 0.95, which is what people wrongly think a CI means. The highest-density interval (HDI) is the narrowest such interval.
  • \(P(\theta \gt 0)\) or \(P(\theta_B \gt \theta_A)\): the probability of the thing you care about.
  • Expected loss: how much you expect to lose by picking an option if it is actually worse.

Conjugate Updates: Beta-Binomial

\[\text{Prior } \text{Beta}(\alpha, \beta) \;+\; k \text{ successes in } n \text{ trials} \;\Rightarrow\; \text{Posterior } \text{Beta}(\alpha + k,\ \beta + n - k)\]

The idea

When the prior and the likelihood match (are conjugate), the posterior is the same family with updated parameters: no integrals. Beta is conjugate to the binomial; think of \(\alpha - 1\) and \(\beta - 1\) as successes and failures seen before the data. Beta(1, 1) is flat; Beta(2, 2) mildly favors the middle; Beta(20, 380) says “about 5%, fairly sure.”

Other conjugate pairs

LikelihoodPriorPosterior
Binomial \(p\)Beta(\(\alpha, \beta\))Beta(\(\alpha + k, \beta + n - k\))
Poisson rate \(\lambda\)Gamma(\(a, b\))Gamma(\(a + \sum x_i, b + n\))
Normal mean \(\mu\) (known \(\sigma\))Normal(\(\mu_0, \tau^2\))Normal with precision-weighted mean
MultinomialDirichletDirichlet with counts added

Beta-Binomial update

from scipy import stats
prior = stats.beta(2, 2)
k, n = 57, 1200                                       # conversions, visitors
post = stats.beta(2 + k, 2 + n - k)
post.mean(), post.interval(0.95)                      # posterior mean and 95% credible interval
post.cdf(0.04)                                        # P(rate < 4%)

By hand: the posterior is \(\text{Beta}(2 + 57,\ 2 + 1143) = \text{Beta}(59, 1145)\). Its mean is \(59/1204 = 0.0490\), a hair above the raw \(57/1200 = 0.0475\) because the prior's two imaginary successes and two failures pull toward 0.5, and its SD is \(\sqrt{\frac{59 \times 1145}{1204^2 \times 1205}} = 0.0062\), essentially the frequentist standard error. post.interval(0.95) prints about (0.0375, 0.0619): a 95% probability that the true rate lies between 3.8% and 6.2%. post.cdf(0.04) prints about 0.067: a 6.7% chance the rate is below 4%, which is the kind of direct statement a confidence interval cannot make. With 1,200 observations the choice between Beta(2, 2) and Beta(1, 1) moves these numbers in the fourth decimal.

Bayesian A/B Testing

Monte Carlo on the posteriors

rng = np.random.default_rng(0)
a_k, a_n, b_k, b_n = 57, 1200, 81, 1210
post_a = stats.beta(1 + a_k, 1 + a_n - a_k); post_b = stats.beta(1 + b_k, 1 + b_n - b_k)
sa, sb = post_a.rvs(200_000, random_state=rng), post_b.rvs(200_000, random_state=rng)
p_b_better = (sb > sa).mean()                                  # P(B > A)
lift = (sb - sa) / sa; np.percentile(lift, [2.5, 50, 97.5])    # credible interval for relative lift
exp_loss_choose_b = np.maximum(sa - sb, 0).mean()              # expected loss if we ship B and it is worse
exp_loss_choose_a = np.maximum(sb - sa, 0).mean()
print(round(p_b_better, 3), round(exp_loss_choose_b, 5), round(exp_loss_choose_a, 5))

The print shows three numbers, roughly 0.98 0.00007 0.0195. First: a 98% probability that B's true conversion rate beats A's. Second: if you ship B and it is actually worse, you expect to lose about 0.007 percentage points of conversion, a negligible amount. Third: if you keep A and B was actually better, you expect to forgo about 1.95 points. The lift percentiles print as roughly [0.02, 0.40, 0.96]: B is most likely about 40% better in relative terms, with a 95% credible interval from 2% to 96%. Compare the two-proportion z-test on the same counts in chapter 6, which gave \(p = 0.040\): one minus half of that is 0.98, the same number by a different route.

Decision rule
Frequentist and Bayesian agree

Ship the arm whose expected loss falls below a threshold you set in advance (say 0.1 percentage points). Because you are estimating a quantity rather than testing a null, checking daily is less dangerous than peeking at p-values, though a stopping rule still biases the estimate a little. State the prior, the rule and the threshold before the test starts.

With flat priors and decent \(n\), \(P(B \gt A)\) is close to \(1 - p/2\) from the one-sided z-test, and the 95% credible interval nearly coincides with the 95% CI. The two frameworks differ in interpretation and in how priors and stopping are handled, not usually in the numbers.

When Conjugacy Runs Out: MCMC

Realistic models (hierarchical, regression with priors, mixtures) have no closed-form posterior. Markov chain Monte Carlo draws samples from the posterior instead; Hamiltonian Monte Carlo (NUTS) is the modern default in PyMC, Stan and NumPyro. Check convergence with \(\hat{R}\) near 1.00 and effective sample sizes in the hundreds or more, and look at the trace plots.

The same A/B model in PyMC

import pymc as pm
with pm.Model() as model:
    rate_a = pm.Beta("rate_a", 1, 1); rate_b = pm.Beta("rate_b", 1, 1)
    pm.Binomial("obs_a", n=a_n, p=rate_a, observed=a_k)
    pm.Binomial("obs_b", n=b_n, p=rate_b, observed=b_k)
    lift = pm.Deterministic("lift", (rate_b - rate_a) / rate_a)
    idata = pm.sample(2000, tune=1000, random_seed=0)
import arviz as az
az.summary(idata, var_names=["rate_a", "rate_b", "lift"], hdi_prob=0.95)
Hierarchical models
Empirical Bayes and shrinkage

Many small groups (stores, regions, SKUs) each with their own rate, tied together by a shared prior. Small groups are shrunk toward the overall mean, large groups keep their own estimates: partial pooling. The Bayesian answer to “this store only had 12 sales.”

Estimate the prior from the data itself (fit a Beta to all stores' rates, then update each store). A fast approximation with most of the benefit; the same logic behind the James-Stein estimator and ridge regression's shrinkage.

Time Series Basics

Applied · Data Science Statistics

What Makes Time Series Different

Observations in time order are not independent: today looks like yesterday. That breaks the i.i.d. assumption behind most of chapters 4 to 10, so the tools change: decomposition, autocorrelation, stationarity, models that use the past to predict the future, and validation that never trains on the future.

Components
First plots
  • Trend: the long-run direction.
  • Seasonality: a fixed-period cycle (weekly, yearly). Known period.
  • Cycle: rises and falls without a fixed period (business cycles).
  • Noise / remainder: what is left.
  • Additive \(y = T + S + R\) when the seasonal swing is constant; multiplicative \(y = T \times S \times R\) when it grows with the level (log the series to make it additive).
  • The series over time, at the native frequency and aggregated (daily and weekly).
  • Seasonal plot: one line per year over the months, or per week over the weekdays.
  • Rolling mean and rolling SD to see the trend and whether variance is stable.
  • The ACF and PACF (below).

Decomposition in pandas and statsmodels

s = df.set_index("date")["sales"].asfreq("D").interpolate()
s.rolling(7).mean(); s.rolling(28).std()
from statsmodels.tsa.seasonal import STL
res = STL(s, period=7).fit(); res.plot()           # trend, seasonal, remainder
s.resample("W").sum(); s.pct_change(); s.diff(7)    # weekly totals, growth rate, week-over-week change

Autocorrelation and Stationarity

Autocorrelation function (ACF)
Stationarity

\[r_k = \frac{\sum_{t=k+1}^{n}(y_t - \bar{y})(y_{t-k} - \bar{y})}{\sum_{t=1}^{n}(y_t - \bar{y})^2}\]

Correlation of the series with itself \(k\) steps back. Spikes at 7, 14, 21 reveal weekly seasonality; a slow decay reveals a trend. The PACF removes the effect of the shorter lags and tells you how many autoregressive terms you need.

In the formula \(y_t\) is the value at time \(t\), \(\bar{y}\) the mean of the whole series, \(k\) the lag and \(n\) the length; \(r_0 = 1\) by construction. On an ACF plot the shaded band is roughly \(\pm 1.96/\sqrt{n}\): spikes outside it are more than chance. For white noise about 1 lag in 20 pokes outside the band on its own, so do not read a single marginal spike as structure.

A stationary series has constant mean, constant variance and an autocorrelation that depends only on the lag. Most forecasting models assume it. Make a series stationary by differencing (\(y_t - y_{t-1}\), or \(y_t - y_{t-7}\) for seasonality) and by logging to stabilize variance. Test with the Augmented Dickey-Fuller test (\(H_0\): unit root, non-stationary) and KPSS (\(H_0\): stationary).

ACF, PACF and stationarity tests

from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.stattools import adfuller, kpss
plot_acf(s, lags=40); plot_pacf(s, lags=40)
adfuller(s)[1]                       # p < 0.05 rejects a unit root: stationary
kpss(s, regression="c")[1]           # p < 0.05 rejects stationarity
d = s.diff().dropna(); adfuller(d)[1]

Spurious regression. Two trending series (ice cream sales and drownings, any two stock prices) correlate strongly for no reason. Difference them, or model the relationship on the residuals, before believing a correlation between time series.

Baseline Forecasts

MethodForecastGood for
Naive\(\hat{y}_{t+1} = y_t\)Random walks; the baseline every model must beat
Seasonal naive\(\hat{y}_{t+1} = y_{t+1-m}\)Strongly seasonal series: same day last week, same month last year
Mean\(\hat{y}_{t+1} = \bar{y}\)Stationary noise around a level
Driftlast value plus the average historical changeSteady trends
Moving averagemean of the last \(k\) valuesSmoothing; a forecast only for level series

Worked example: monthly signups 100, 104, 110, 118. Naive forecast for next month: 118. Mean: 108. Drift: average change \((118 - 100)/3 = 6\) per month, so 124 next month and 130 the month after. Seasonal naive with a 12-month period: whatever last year's same month was. Fit all of them on the history, score them on a held-out stretch, and quote the best one's error as the number your real model has to beat; a model that cannot beat drift on a trending series has learned nothing.

Exponential smoothing
ARIMA(p, d, q)

\[\hat{y}_{t+1} = \alpha\,y_t + (1-\alpha)\,\hat{y}_t\]

A weighted average that forgets the past geometrically. Holt adds a trend term; Holt-Winters adds seasonality. Fast, robust, and a strong default for business series.

\(\alpha\) between 0 and 1 is the weight on the newest observation; \(\hat{y}_t\) is last period's forecast. Worked example with \(\alpha = 0.3\), starting forecast 100, and sales 110, 120, 115: \(\hat{y}_2 = 0.3(110) + 0.7(100) = 103\); \(\hat{y}_3 = 0.3(120) + 0.7(103) = 108.1\); \(\hat{y}_4 = 0.3(115) + 0.7(108.1) = 110.2\). The forecast chases the level but never fully catches a jump; a larger \(\alpha\) reacts faster and smooths less. fit() chooses \(\alpha\) (and the trend and seasonal weights) by minimizing one-step errors on the history.

\(p\) autoregressive lags of the series, \(d\) differences to reach stationarity, \(q\) lags of past errors. SARIMA adds seasonal terms \((P, D, Q)_m\). Pick orders from the ACF/PACF or by AIC search (pmdarima.auto_arima). Residuals should look like white noise (Ljung-Box test).

Smoothing and ARIMA in statsmodels

from statsmodels.tsa.holtwinters import ExponentialSmoothing
hw = ExponentialSmoothing(s, trend="add", seasonal="add", seasonal_periods=7).fit()
hw.forecast(14)
from statsmodels.tsa.statespace.sarimax import SARIMAX
m = SARIMAX(s, order=(1, 1, 1), seasonal_order=(1, 1, 1, 7)).fit(disp=False)
fc = m.get_forecast(14); fc.predicted_mean, fc.conf_int()
from statsmodels.stats.diagnostic import acorr_ljungbox
acorr_ljungbox(m.resid, lags=[14])        # p > 0.05: residuals look like white noise

Regression on Time Features and Evaluation

Feature-based forecasting
Validating forecasts
  • Calendar features: day of week, month, holiday flags, days to a known event.
  • Lag features: \(y_{t-1}, y_{t-7}, y_{t-28}\); rolling means and SDs over past windows only.
  • Exogenous drivers: price, promotions, weather, with their own lags.
  • Then any regressor (linear, gradient boosting) can forecast; Prophet-style models fit trend plus seasonality plus holidays directly.
  • Rolling-origin (walk-forward) evaluation: train up to time \(t\), forecast \(h\) steps, slide forward, repeat. TimeSeriesSplit.
  • Report error by horizon: next-day error is not next-month error.
  • Metrics: MAE, RMSE, MAPE/sMAPE/WAPE, and MASE (error relative to the seasonal naive, so 1.0 means no better than the baseline).
  • Prediction intervals matter as much as the point forecast; check their coverage.

Walk-forward validation

X = pd.DataFrame({"dow": s.index.dayofweek, "month": s.index.month,
                  "lag1": s.shift(1), "lag7": s.shift(7), "roll7": s.shift(1).rolling(7).mean()}).dropna()
y = s.loc[X.index]
from sklearn.model_selection import TimeSeriesSplit
from sklearn.ensemble import GradientBoostingRegressor
errs = []
for tr, te in TimeSeriesSplit(n_splits=5).split(X):
    gb = GradientBoostingRegressor(random_state=0).fit(X.iloc[tr], y.iloc[tr])
    errs.append(mean_absolute_error(y.iloc[te], gb.predict(X.iloc[te])))
mase = np.mean(errs) / np.mean(np.abs(s.diff(7).dropna()))      # < 1 beats seasonal naive

The Python Toolkit for Statistics

Applied · Data Science Statistics

The Stack

LibraryUse it forImport
NumPyArrays, random numbers, vectorized mathimport numpy as np
pandasTables: loading, cleaning, grouping, describingimport pandas as pd
SciPy statsDistributions, classical tests, bootstrap, permutation testsfrom scipy import stats
statsmodelsRegression with inference (summary tables), power, proportions, time seriesimport statsmodels.api as sm, import statsmodels.formula.api as smf
scikit-learnPrediction pipelines, cross-validation, metrics, preprocessingfrom sklearn...
matplotlib / seabornPlots; seaborn adds statistical plots (box, violin, regplot, heatmap)import matplotlib.pyplot as plt, import seaborn as sns
PyMC / ArviZBayesian models and their diagnosticsimport pymc as pm, import arviz as az

statsmodels answers “is this coefficient real and how big is it?” with standard errors and p-values; scikit-learn answers “how well does this predict?” with pipelines and cross-validation. Most projects use both.

A Complete Workflow

From raw file to decision

import numpy as np, pandas as pd
from scipy import stats
import statsmodels.formula.api as smf

# 1. load and look
df = pd.read_csv("experiment.csv", parse_dates=["date"])
print(df.shape); print(df.dtypes); print(df.isna().mean())
print(df.describe(include="all").T)

# 2. clean
df = df.drop_duplicates(subset="user_id")
df["revenue"] = df["revenue"].clip(upper=df["revenue"].quantile(0.99))     # pre-registered winsorizing rule
df["signup_month"] = df["date"].dt.to_period("M")

# 3. sanity check the experiment
counts = df["variant"].value_counts()
print(stats.chisquare(counts.values))                                     # sample ratio check

# 4. primary metric: conversion
conv = df.groupby("variant")["converted"].agg(["sum", "count", "mean"])
from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep
z, p = proportions_ztest(conv["sum"].values, conv["count"].values)
ci = confint_proportions_2indep(conv.loc["B", "sum"], conv.loc["B", "count"],
                                conv.loc["A", "sum"], conv.loc["A", "count"])
print(conv); print(f"z={z:.2f} p={p:.4f} diff CI={ci}")

# 5. guardrail: revenue per user, with a covariate for precision
m = smf.ols("revenue ~ C(variant) + pre_revenue", data=df).fit(cov_type="HC3")
print(m.summary().tables[1])

# 6. effect size and a bootstrap interval on relative lift
a = df.loc[df.variant == "A", "converted"].to_numpy(); b = df.loc[df.variant == "B", "converted"].to_numpy()
res = stats.bootstrap((b, a), lambda y, x: (y.mean() - x.mean()) / x.mean(), n_resamples=5000, random_state=0)
print("relative lift CI", res.confidence_interval)

Quick Reference: Which Call

NeedCall
Summary statisticsdf.describe(), s.mean(), s.median(), s.std(), s.quantile(q), s.skew(), s.kurt()
Grouped summariesdf.groupby(col)[metric].agg(["mean", "median", "count", "std"])
Crosstabpd.crosstab(a, b, normalize="index")
Correlationdf.corr(), stats.pearsonr, stats.spearmanr
Distribution probability / quantile / drawsstats.norm(mu, sd).cdf(x), .ppf(q), .rvs(n, random_state=0)
Fit a distributionstats.lognorm.fit(x, floc=0)
CI for a meansms.DescrStatsW(x).tconfint_mean()
CI for a proportionproportion_confint(k, n, method="wilson")
Bootstrap CI for anythingstats.bootstrap((x,), np.median, random_state=0)
t-testsstats.ttest_1samp, stats.ttest_ind(equal_var=False), stats.ttest_rel
Rank testsstats.mannwhitneyu, stats.wilcoxon, stats.kruskal
Proportionsproportions_ztest, stats.binomtest, stats.fisher_exact
Chi-squarestats.chi2_contingency(table), stats.chisquare(obs, exp)
ANOVA and post hocstats.f_oneway, pairwise_tukeyhsd
Permutation teststats.permutation_test((a, b), statistic, n_resamples=9999)
Multiple comparisonsmultipletests(pvals, method="holm" | "fdr_bh")
Power and sample sizeTTestIndPower().solve_power(...), NormalIndPower(), proportion_effectsize
Linear regression with inferencesmf.ols("y ~ x1 + C(cat)", df).fit().summary()
Logistic regression with odds ratiossmf.logit(...).fit(); np.exp(m.params)
Robust / clustered standard errors.fit(cov_type="HC3"), .fit(cov_type="cluster", cov_kwds={"groups": g})
Cross-validated predictioncross_val_score(pipe, X, y, cv=StratifiedKFold(5, shuffle=True, random_state=0))
Classification metricsclassification_report, roc_auc_score, average_precision_score, log_loss
Regression metricsmean_absolute_error, mean_squared_error, r2_score
Time seriesSTL, plot_acf, adfuller, ExponentialSmoothing, SARIMAX, TimeSeriesSplit

Reproducibility Habits

  • Seed everything: np.random.default_rng(0), random_state=0 in scikit-learn and SciPy.
  • Pin versions (requirements.txt or a lock file); SciPy and statsmodels change defaults between releases.
  • Keep raw data read-only; write cleaned data to a new file with the cleaning script next to it.
  • Write the analysis plan (metric, test, MDE, exclusion rules) before looking at outcomes, and keep it in the repo.
  • Report \(n\), the estimate, the interval and the p-value together, with the code that produced them.
  • Prefer a script or notebook that runs top to bottom with “Restart and run all” over a notebook with hidden state.

Formula Sheet and Glossary

Applied · Data Science Statistics

Descriptive

QuantityFormula
Sample mean\(\bar{x} = \frac{1}{n}\sum x_i\)
Sample variance, SD\(s^2 = \frac{1}{n-1}\sum (x_i - \bar{x})^2, \quad s = \sqrt{s^2}\)
Standard error of the mean\(\text{SE} = s/\sqrt{n}\)
Z-score\(z = (x - \bar{x})/s\)
IQR\(Q_3 - Q_1\); outlier fences at \(Q_1 - 1.5\,\text{IQR}\), \(Q_3 + 1.5\,\text{IQR}\)
Coefficient of variation\(s / \bar{x}\)
Covariance, correlation\(s_{xy} = \frac{1}{n-1}\sum (x_i-\bar{x})(y_i-\bar{y}), \quad r = s_{xy}/(s_x s_y)\)

Probability

RuleFormula
Complement\(P(A^c) = 1 - P(A)\)
Addition\(P(A \cup B) = P(A) + P(B) - P(A \cap B)\)
Conditional\(P(A \mid B) = P(A \cap B)/P(B)\)
Multiplication\(P(A \cap B) = P(A \mid B)P(B)\)
Independence\(P(A \cap B) = P(A)P(B)\)
Total probability\(P(A) = \sum_i P(A \mid B_i)P(B_i)\)
Bayes\(P(H \mid D) = P(D \mid H)P(H)/P(D)\)
Expectation, variance\(E[X] = \sum x\,p(x), \quad \operatorname{Var}(X) = E[X^2] - E[X]^2\)
Linear combinations\(E[aX+bY] = aE[X]+bE[Y]; \quad \operatorname{Var}(aX+bY) = a^2\operatorname{Var}X + b^2\operatorname{Var}Y + 2ab\operatorname{Cov}(X,Y)\)
Binomial\(P(X=k) = \binom{n}{k}p^k(1-p)^{n-k}; \quad \mu = np, \ \sigma^2 = np(1-p)\)
Poisson\(P(X=k) = e^{-\lambda}\lambda^k/k!; \quad \mu = \sigma^2 = \lambda\)
Normal\(f(x) = \frac{1}{\sigma\sqrt{2\pi}}e^{-(x-\mu)^2/2\sigma^2}\); 68 / 95 / 99.7 within 1 / 2 / 3 SD
Exponential\(f(x) = \lambda e^{-\lambda x}; \quad \mu = 1/\lambda\)

Inference

QuantityFormula
CLT\(\bar{X} \approx N(\mu, \sigma^2/n)\)
CI for a mean\(\bar{x} \pm t^*_{n-1}\, s/\sqrt{n}\)
CI for a proportion\(\hat{p} \pm z^*\sqrt{\hat{p}(1-\hat{p})/n}\) (prefer Wilson)
CI for a difference of means\((\bar{x}_1 - \bar{x}_2) \pm t^*\sqrt{s_1^2/n_1 + s_2^2/n_2}\)
One-sample t\(t = (\bar{x} - \mu_0)/(s/\sqrt{n})\), \(df = n-1\)
Welch t\(t = (\bar{x}_1 - \bar{x}_2)/\sqrt{s_1^2/n_1 + s_2^2/n_2}\)
Paired t\(t = \bar{d}/(s_d/\sqrt{n})\)
Two-proportion z\(z = (\hat{p}_1 - \hat{p}_2)/\sqrt{\hat{p}(1-\hat{p})(1/n_1 + 1/n_2)}\)
Chi-square\(\chi^2 = \sum (O-E)^2/E\), \(df = (r-1)(c-1)\)
Cohen's d\((\bar{x}_1 - \bar{x}_2)/s_{\text{pooled}}\)
Sample size for a margin \(E\)\(n = (z^*\sigma/E)^2\); proportion: \(n = (z^*)^2 p(1-p)/E^2\)
Sample size per group (A/B)\(n \approx 2(z_{1-\alpha/2} + z_{1-\beta})^2\sigma^2/\delta^2\)
Bonferroni\(\alpha/m\)
Benjamini-Hochbergreject \(p_{(k)} \le k\alpha/m\) and all smaller
CUPED\(Y^{\text{adj}} = Y - \theta(X - \bar{X}), \ \theta = \operatorname{Cov}(X,Y)/\operatorname{Var}(X)\)

Modeling

QuantityFormula
Simple regression\(b_1 = r\,s_y/s_x, \quad b_0 = \bar{y} - b_1\bar{x}\)
OLS (matrix)\(\mathbf{b} = (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}\)
\(R^2\), adjusted\(1 - SS_{\text{res}}/SS_{\text{tot}}; \quad 1 - (1-R^2)\frac{n-1}{n-k-1}\)
VIF\(1/(1-R_j^2)\)
Ridge, lassoadd \(\lambda\sum b_j^2\) or \(\lambda\sum|b_j|\) to the squared error
Logistic\(p = 1/(1+e^{-z}), \quad z = \log\frac{p}{1-p}\); odds ratio \(= e^{b}\)
Log loss\(-\frac{1}{n}\sum[y\log\hat{p} + (1-y)\log(1-\hat{p})]\)
Precision, recall, F1\(TP/(TP+FP), \quad TP/(TP+FN), \quad 2PR/(P+R)\)
RMSE, MAE, MAPE\(\sqrt{\frac{1}{n}\sum e^2}, \quad \frac{1}{n}\sum|e|, \quad \frac{100}{n}\sum|e/y|\)
Bias-variance\(E[\text{error}^2] = \text{Bias}^2 + \text{Variance} + \sigma^2\)
Beta-Binomial update\(\text{Beta}(\alpha, \beta) \to \text{Beta}(\alpha + k, \beta + n - k)\)
Exponential smoothing\(\hat{y}_{t+1} = \alpha y_t + (1-\alpha)\hat{y}_t\)

Glossary

TermMeaning
Alpha (\(\alpha\))Significance level: the false-positive rate you accept, usually 0.05.
Beta (\(\beta\))False-negative rate; power is \(1 - \beta\).
BiasSystematic error: an estimator or a sample that is off on average.
BootstrapResampling the sample with replacement to estimate a sampling distribution.
CalibrationPredicted probabilities match observed frequencies.
ConfounderA variable that affects both the treatment and the outcome, creating a spurious association.
Credible intervalBayesian interval containing the parameter with the stated posterior probability.
Cross-validationRotating held-out folds to estimate out-of-sample error.
Degrees of freedomNumber of values free to vary; sets the shape of \(t\), \(\chi^2\) and \(F\).
Effect sizeThe magnitude of a difference or association, separate from its p-value.
HeteroscedasticityError variance that changes with the predictors.
i.i.d.Independent and identically distributed: the standard sampling assumption.
LeakageInformation from outside the training data (often the future or the target) sneaking into a model.
LikelihoodProbability of the observed data as a function of the parameters.
MDEMinimum detectable effect: the smallest effect an experiment is powered to find.
MulticollinearityStrongly correlated predictors that make coefficients unstable.
NonparametricA method that does not assume a specific distribution (rank tests, permutation, bootstrap).
OverfittingFitting noise; low training error, high test error.
p-valueProbability, under \(H_0\), of a result at least this extreme.
PowerProbability of detecting an effect that is really there.
Prior / posteriorBelief about a parameter before / after seeing the data.
RegularizationPenalizing complexity to reduce variance.
Sampling distributionDistribution of a statistic across repeated samples.
Standard errorSD of a statistic's sampling distribution.
StationarityConstant mean, variance and autocorrelation structure over time.
Statistical significance\(p \le \alpha\); says detectable, not important.
Type I / Type II errorFalse positive / false negative.