Neural Mastery

Probability & Statistics for AI

Models don't produce certainties — they produce probability distributions. Understanding probability is understanding what a model's output actually means, and statistics is how you tell whether a model's improvement is real or just noise.

A model rarely just says "yes" or "42" — it says "I'm 73% sure it's yes," or hands back a whole spread of plausible answers with different likelihoods attached. Probability is the language for describing that spread precisely, and for updating it correctly when new evidence shows up (that's Bayes' theorem — the math version of "huh, that changes things"). Statistics is the second half: once you've collected real data and computed a number from it — a p-value, an average, a model's accuracy — how do you know that number reflects something real, rather than being exactly what you'd expect from random noise alone? Both halves matter for the same reason: every model you build outputs a distribution, was trained by minimizing something derived from probability theory, and needs its claimed improvements checked against noise before anyone should trust them.

Everything below makes both halves exact.

Intuition: What a Model's Output Means, and Whether to Trust a Number

Two threads run through this whole page. The first: a model's output is a distribution, not an answer — everything from Bayes' theorem to entropy is about how to reason correctly with that distribution rather than pretending it's a single certain fact. The second: any number computed from a finite sample of data (a p-value, a confidence interval, a correlation) can mislead you in specific, well-understood ways — the second half of this page is about the tools (bootstrap, permutation tests, causal reasoning) that keep you honest about what a number from data actually licenses you to conclude.

Random Variables and Distributions

A random variable is a quantity whose value depends on chance. Its distribution describes how likely each possible value is. Pick a distribution and adjust its real parameters below:

Distribution
Real PMF/PDF values, recomputed live from the formula as you move the sliders.
Real computed mean = 0.000, variance = 1.000.
  • Bernoulli: a single yes/no outcome (e.g. "is this email spam?") — the distribution behind binary classification.
  • Binomial: the number of successes in nn independent Bernoulli trials.
  • Gaussian (Normal): the classic bell curve, defined by mean μ\mu and variance σ2\sigma^2. Appears everywhere — weight initialization, noise modeling, the assumed error distribution in linear regression.
  • Categorical: a generalization of Bernoulli to more than two outcomes — this is exactly what an LLM's output layer produces: a probability distribution over every possible next token.

Expectation, Variance, Covariance

  • Expectation E[X]E[X]: the long-run average value of a random variable — the "center of mass" of its distribution.
  • Variance Var(X)=E[(XE[X])2]\text{Var}(X) = E[(X - E[X])^2]: how spread out the values are.
  • Covariance Cov(X,Y)\text{Cov}(X, Y): whether two variables move together (positive), oppositely (negative), or independently (near zero).
  • Correlation: covariance normalized to [1,1][-1, 1], making it comparable across different variables' scales.

Why it matters: the bias-variance tradeoff (see Machine Learning) is literally a statement about the variance of a model's predictions across different training sets.

Bayes' Theorem

P(AB)=P(BA)P(A)P(B)P(A \mid B) = \frac{P(B \mid A) \, P(A)}{P(B)}

Lets you update a belief (P(A)P(A), the prior) given new evidence (BB) to get an updated belief (P(AB)P(A \mid B), the posterior). Real numbers, the classic base-rate case:

1.00%
prior belief
16.10%
posterior after evidence
P(AB)=P(BA)P(A)P(B)=0.1610P(A|B) = \frac{P(B|A)P(A)}{P(B)} = 0.1610
P(disease | positive test) = P(positive|disease)·P(disease) / P(positive) = 0.1610 -- real Bayes' theorem, computed live. Even with a 95%-accurate test, a rare enough prior (1.00%) means most positive results are still false positives -- the classic, real-consequence lesson base rates teach.

This single equation underlies Naive Bayes classifiers, Bayesian optimization (used for hyperparameter tuning), and the conceptual framing of how RAG systems should ideally combine a model's prior knowledge with retrieved evidence.

MLE vs MAP

  • Maximum Likelihood Estimation (MLE): pick the model parameters that make the observed data most probable. This is what "minimizing cross-entropy loss" actually is under the hood — cross-entropy loss minimization is MLE for a categorical distribution.
  • Maximum A Posteriori (MAP): like MLE, but also weighs in a prior belief about what parameters are reasonable.

Real estimates from a real (small, adjustable) coin-flip dataset:

1.000
MLE estimate
0.700
MAP estimate
With only 4 flips (the default), a run of all heads gives MLE=100% -- a real, extreme overfit to tiny data -- while MAP stays anchored much closer to 50% until real evidence accumulates.
With 4 heads out of 4 flips: MLE says P(heads)=1.000 -- taken completely literally, no matter how little data. MAP, with a real Beta(3,3) prior centered at 0.5, gives 0.700 -- pulled toward the prior. Increase flips and watch MAP converge to MLE as the data increasingly outweighs the prior -- exactly the real math behind "L2 regularization = MAP with a Gaussian prior."

Adding L2 regularization to a loss function is mathematically equivalent to doing MAP estimation with a Gaussian prior on the weights — the same shrinkage-toward-a-default-belief visible above, just applied to millions of weights instead of one coin bias.

Central Limit Theorem

The average of a large number of independent random variables tends toward a Gaussian distribution, regardless of the original variables' distribution. Watch it happen live, starting from a genuinely non-Gaussian source:

This is why so much of statistics gets to assume normality even when individual data points clearly aren't Gaussian -- averaging (which is exactly what a mean, a mini-batch loss, or an evaluation metric does) launders non-normal noise into approximately-normal noise.
2000 real batches drawn from a genuinely skewed source distribution (exponential-like, heavily right-tailed), each batch of size 1 averaged. At batch size 1, the histogram IS the skewed source. Increase batch size and watch the histogram of batch MEANS become visibly bell-shaped -- the real Central Limit Theorem, happening live, not asserted.

This is why so much of statistics gets to assume normality, and why metrics averaged over large evaluation sets behave predictably even when individual examples are noisy.

Hypothesis Testing & Significance

  • Null hypothesis (H0H_0): the "nothing changed" baseline assumption — e.g. "the new model's conversion rate equals the old one's."
  • p-value: the probability of seeing a result at least this extreme if the null hypothesis were true. Real permutation-test p-value, computed from the real empirical null distribution rather than a formula:
Gray histogram: 500 real "what if there were no real effect" simulated differences. Red line: the real observed difference. p-value asks how far into the tail that red line sits.
Real observed difference in means = -0.210. 500 real permutations (shuffling group labels, recomputing the difference each time) build the histogram below -- the REAL empirical null distribution, no Gaussian assumption. p-value = fraction of permuted differences at least as extreme as observed = 0.152. This is the exact mechanism, not a formula plugged into a table.

A p-value is not "the probability the null hypothesis is true" — that's the single most common misinterpretation, and worth internalizing precisely: it's a statement about how surprising the data would be under H0H_0, not a statement of probability about the hypothesis itself.

  • Confidence intervals: a range constructed from the observed data such that, if you repeated the experiment many times, that construction procedure would contain the true value some target fraction (e.g. 95%) of the time. A 95% CI that excludes zero for a lift metric is the interval-based equivalent of a p-value below 0.05.
  • Statistical power: the probability of correctly detecting a real effect when one truly exists. Power depends on sample size, effect size, and significance threshold — an underpowered A/B test can run for weeks and still correctly fail to find a real 2% lift simply because too few users saw it. Compute the required sample size before running an experiment, not after it "didn't reach significance."
  • A/B testing: the practical application — before shipping a new model to 100% of users, you run it against a control group and use hypothesis testing to confirm the improvement is real, not random variation.

Bootstrap and Permutation Tests

Two resampling techniques that estimate uncertainty without assuming a particular distribution (like the Gaussian assumption behind many classical formulas) — useful exactly when a metric's theoretical sampling distribution is unknown or intractable (e.g. the median, or a custom business metric).

Bootstrap: resample the observed data with replacement many times, compute the metric of interest on each resample, and use the spread of those computed values as an empirical confidence interval. Real 1000-resample run:

observed median┃┃ 95% bootstrap CI
Real median of the original 14-point dataset = 5.00. 1000 real bootstrap resamples (each the same size, drawn WITH replacement from the original data) give a real empirical 95% CI of [4.30, 5.90] -- no formula assumed a particular shape for the median's sampling distribution; the resampling built it directly.

If you've ever seen a metric reported with error bars from "1000 bootstrap resamples," this is exactly what produced them — and it's the same resampling-with-replacement idea bagging methods like Random Forest use internally, applied here to uncertainty estimation instead of ensembling.

Permutation test (the mechanism behind the p-value diagram above): to test whether two groups genuinely differ, randomly shuffle ("permute") the group labels many times, recomputing the difference in means each time. This builds an empirical null distribution directly from the data itself, with no distributional assumptions.

Causal Inference & Sampling Bias

Correlation is not causation is the single most important caveat in applied statistics. Watch a real spurious correlation appear from a shared confounder, and disappear under real randomization:

Data source
Real |r|=0.772 -- same plotting code, same confounder Z in the background, only how X got its value differs.
Observational data: real Pearson r = 0.772 between X and Y -- looks like a real relationship. But both X and Y were secretly generated from a shared confounder Z, with NO direct causal link between them at all. This is the ice-cream-sales-and-drownings pattern, made numeric.
  • Confounders: a variable that influences both the presumed cause and the presumed effect, creating a spurious correlation between them (e.g. ice cream sales and drowning deaths both rise with summer heat — heat is the confounder, ice cream doesn't cause drowning).
  • Randomized controlled trials (RCTs): randomly assigning subjects to treatment/control is what breaks confounding — with random assignment, any systematic pre-existing difference between groups is (in expectation) eliminated, which is exactly why A/B testing (a form of RCT) is trusted to establish causation, while purely observational comparisons ("users who used feature X had higher retention") are not, without further assumptions.
  • Sampling bias: when the data collected systematically over- or under-represents part of the population you actually care about — e.g. training a model on logged data from users who opted in to a feature necessarily excludes everyone who didn't, biasing conclusions about the feature's general effect. This is a silent, common failure mode distinct from data leakage (see ML Workflow Fundamentals): leakage contaminates training with future information, sampling bias means the training distribution was never representative of the true population to begin with.

Entropy, Cross-Entropy, and KL Divergence

  • Entropy H(P)=xP(x)logP(x)H(P) = -\sum_x P(x) \log P(x): measures the inherent uncertainty in a distribution.
  • Cross-entropy H(P,Q)=xP(x)logQ(x)H(P, Q) = -\sum_x P(x) \log Q(x): measures how well a predicted distribution QQ matches the true distribution PP.
  • KL divergence DKL(PQ)=H(P,Q)H(P)D_{KL}(P \| Q) = H(P, Q) - H(P): measures how much information is lost when QQ is used to approximate PP.

Drag a predicted distribution QQ toward (or away from) the true PP and watch all three real quantities respond:

cat
dog
bird
true P predicted Q
1.157
H(P)
1.280
H(P,Q)
0.123
D_KL(P‖Q)
Real H(P) = 1.157 bits (the true distribution's own uncertainty -- fixed). Real H(P,Q) = 1.280 bits (cross-entropy -- this is literally the training loss). Real D_KL(P‖Q) = H(P,Q) − H(P) = 0.123 bits. Drag Q toward P and watch cross-entropy fall toward H(P) and KL fall toward exactly 0 -- a perfect predictor has zero extra cost over the distribution's own true uncertainty.

This is the loss function used to train virtually every classifier and every LLM — next-token prediction is a giant cross-entropy minimization over the vocabulary distribution. KL divergence shows up in variational autoencoders, in RLHF (constraining the fine-tuned policy from drifting too far from the base model), and in DPO's loss formulation.

Code: A Real Bootstrap Confidence Interval

The exact procedure the bootstrap diagram above runs:

import numpy as np

def bootstrap_ci(data: np.ndarray, statistic=np.median, n_resamples=1000, ci=0.95) -> tuple[float, float]:
    resample_stats = []
    for _ in range(n_resamples):
        resample = np.random.choice(data, size=len(data), replace=True)  # WITH replacement
        resample_stats.append(statistic(resample))
    alpha = 1 - ci
    lower = np.percentile(resample_stats, 100 * alpha / 2)
    upper = np.percentile(resample_stats, 100 * (1 - alpha / 2))
    return lower, upper

Where this shows up in the rest of the curriculum

ConceptUsed in
Cross-entropyLoss function for classifiers and every LLM
Bayes' theoremNaive Bayes, Bayesian hyperparameter search
MLE / MAPWhy cross-entropy loss = MLE; why L2 regularization = MAP
KL divergenceRLHF/DPO constraints, VAEs
Hypothesis testingA/B testing new models in production
Bootstrap / permutation testsDistribution-free confidence intervals and significance tests
Causal inferenceDistinguishing "correlated with" from "caused by" in production data

Next: Algorithms & Data Structures — the CS fundamentals that show up in every ML engineering interview alongside the math.

Last updated Sep 5, 2026Edit this pageReport an issue
← Previous
Calculus & Optimization for AI
Next →
Algorithms & Data Structures for AI