Chapter 13: Probability and Statistics
Probability is the mathematics of reasoning under uncertainty, and statistics is the craft of drawing conclusions from data. For anyone who builds software, and especially anyone who builds learning systems, both are everywhere. Every weight a neural network starts with is a random draw; every token a language model emits is sampled from a distribution; every count-based model is an estimate; and every claim that “model B is better” is a statement about noise. Beyond machine learning, the same ideas analyse randomized algorithms and hashing, size queues and load balancers, and run A/B tests in production.
Concepts from other sections (33)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Load balancer: a component that spreads traffic across instances of a service by round-robin, least connections, or consistent hashing, at layer 4 (TCP) or layer 7 (HTTP). Read more: Chapter 1: System Design in Systems Engineering
- Central limit theorem: the standardized sample mean tends to for any distribution with finite variance. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
- Confidence interval: a procedure that, over repeated samples, produces intervals covering the fixed true parameter at the stated rate. Read more: 13.11 Probability problem set, part c: limit theorems and confidence intervals
- Random variable: a number assigned to each outcome of a random experiment; a discrete one is a table of values and probabilities. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Law of large numbers: the sample mean converges to the true mean as grows. Read more: 13.5 LLN, CLT, confidence intervals, bootstrap
- Permutation test: a test whose null distribution comes from relabelling the data in ways the null says are harmless. Read more: 13.6 Hypothesis tests: paired and two-sample permutation, McNemar, Holm
- Rejection sampling: drawing from a proposal and accepting each draw with a probability chosen so that accepted draws follow the target . Read more: 13.7 Rejection sampling and residual distributions
- speculative decoding: drafting several tokens cheaply and verifying them in one target-model pass, preserving the output distribution. Read more: Chapter 20: Inference Engines and GPU Deployment in AI Engineering
- Logistic regression: a model in which the log-odds are linear in the features. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
- Conditional probability: , probability restricted to and renormalized. Read more: 13.9 Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
- Bayes’ rule: , which inverts a conditional using the base rate. Read more: 13.9 Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
- Covariance: , a measure of linear co-movement; zero does not imply independence. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- Box-Muller: the transform , that turns two uniforms into two independent standard normals. Read more: 13.9 Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
- Alias table: equal columns, each holding at most two ids, that allow categorical draws. Read more: 13.2 Categorical sampling: inverse CDF, Gumbel-max, alias method
- Likelihood: , the probability of the observed data as a function of the parameter. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- Newton’s method: the iteration , jumping to the zero of the tangent line. Read more: 7.2 Newton’s Method
- ECE: expected calibration error, the count-weighted mean gap between accuracy and confidence over confidence bins. Read more: 13.8 Logistic regression (IRLS), ROC-AUC, calibration (ECE)
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python
- trapezoid rule: joining neighboring points by straight lines; second order, exact on lines. Read more: 7.4 Definite Integrals: Trapezoid and Simpson
- Pure function: a function whose output depends only on its inputs and which mutates nothing. Read more: Chapter 4: Coding and Design Patterns in Software Engineering
- Maximum-likelihood estimate (MLE): the distribution that maximizes the log-likelihood; for counts, the frequency . Read more: 13.3 MLE, Laplace, absolute discounting
- Add-alpha (Laplace) smoothing: adding a pseudo-count to every word of the vocabulary before normalizing. Read more: 13.3 MLE, Laplace, absolute discounting
- Absolute discounting: subtracting a fixed from each seen count and giving the freed mass to a backoff distribution. Read more: 13.3 MLE, Laplace, absolute discounting
- Kaiming (He) initialization: weight variance (or ), compensating for ReLU zeroing half its inputs. Read more: 13.4 Variance propagation and initialization
- p-value: the probability under the null of a statistic at least as extreme as the one observed. Read more: 13.6 Hypothesis tests: paired and two-sample permutation, McNemar, Holm
- Accept-or-resample: accept a drafted when , else sample from the residual; the emitted token’s law is exactly . Read more: 23.9 Speculative decoding in the engine in AI Engineering
- Little’s law: for any stable system. Read more: 13.12 Probability problem set, part d: hypothesis tests, regression, queueing, balls into bins
- Orthogonal projection: , the closest point to on the line through . Read more: 9.6 Inner products, projections, cosine similarity, and top-k
- Expected value: the average outcome across many repetitions of a situation under the model. Read more: Chapter 4: Uncertainty and evidence
- Standard normal: the distribution with density . Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Exponential distribution: the waiting-time distribution with . Read more: 13.2 Categorical sampling: inverse CDF, Gumbel-max, alias method
- Joint distribution: the table over pairs of values; it determines marginals and conditionals. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
The bridge between the two subjects is the central limit theorem: whatever the underlying distribution, sample means are approximately normal, and that is why confidence intervals and hypothesis tests work at all. This chapter walks that bridge in the order a system needs it. It starts with random variables, expectation, and variance, and turns uniform random numbers into normal ones. It then samples categorical distributions three ways, estimates distributions from counts, and uses variance to choose how neural network weights are initialized. With those in hand it builds the inferential layer: the law of large numbers, the central limit theorem, confidence intervals and the bootstrap, and permutation tests for comparing models. It closes with rejection sampling, the exact probability behind speculative decoding, and with logistic regression, ROC-AUC, and calibration, the tools for fitting and trusting a classifier. Four problem sets, placed alongside the sections they support, let you work every idea by hand.
Each build section comes with a reference implementation under course/solutions/python/tinyllm/prob/, and each problem set has worked answers inline.
Learning objectives
- Use the axioms, conditional probability, and Bayes’ rule, and compute expectations, variances, and covariances of discrete and continuous random variables.
- Sample any distribution from uniform random numbers: by inverse CDF, by Box-Muller, by Gumbel-max, by alias tables, and by rejection.
- Estimate distributions by maximum likelihood, smooth them, and fit logistic regression by Newton’s method.
- Explain the law of large numbers and the central limit theorem, and build t, Wilson, and bootstrap intervals.
- Compare models with permutation tests, McNemar, and Holm’s correction, and evaluate a classifier with ROC-AUC and ECE.
Before you begin
Section titled “Before you begin”The chapter assumes integration from Calculus 2, including the Gaussian integral, and counting and sets from Discrete Math 1. Several sections draw their uniform random numbers from the PCG32 generator built in Modular arithmetic, hashing, and PCG32 in Python, and the last section reuses LU from Linear Algebra and Newton’s method and the trapezoid rule from Calculus 1. The overview below reviews the classical foundations; if they are new to you, read it with one of the textbooks listed under “Further reading” open beside it.
In this chapter
Section titled “In this chapter”The sections and problem sets are listed in the order you should read them.
- Probability problem set, part a: axioms, Bayes, random variables, Box-Muller. The vocabulary for the whole chapter, by hand: axioms, conditioning, Bayes’ rule, discrete and continuous random variables, their moments, and the normal.
- Random variables, expectation, variance, and normal draws by Box-Muller. Defines expectation and variance, computes variance stably in two passes, and turns PCG32’s uniforms into normals in a fixed draw order.
- Categorical sampling: inverse CDF, Gumbel-max, alias method. Three exact ways to draw a token id from a distribution, each a pure function of its uniforms, plus Poisson arrivals from exponential gaps.
- MLE, Laplace, absolute discounting. Why count over total is the maximum-likelihood estimate, why it fails on unseen outcomes, and how add-alpha smoothing and absolute discounting repair it.
- Probability problem set, part b: joint distributions, covariance, MLE. Joint and conditional tables, covariance and the variance of a sum, maximum likelihood by calculus, and one EM step by hand.
- Variance propagation and initialization. Derives the variance of a layer’s pre-activation and from it the Xavier and Kaiming initializations and residual scaling.
- LLN, CLT, confidence intervals, bootstrap. Why error bars shrink as , and how to build t, Wilson, and percentile-bootstrap intervals reproducibly.
- Probability problem set, part c: limit theorems and confidence intervals. The weak law proved from Chebyshev, CLT tail approximations, the three intervals by hand, and what a 95% interval actually promises.
- Hypothesis tests: paired and two-sample permutation, McNemar, Holm. P-values built by relabelling, exact tests for classifiers on the same examples, and a correction for many comparisons.
- Rejection sampling and residual distributions. Von Neumann’s sampler and the accept-or-resample rule that makes speculative decoding sample the target distribution exactly.
- Logistic regression (IRLS), ROC-AUC, calibration (ECE). Fits a classifier by Newton’s method and measures whether it ranks well and whether its probabilities mean what they say.
- Probability problem set, part d: hypothesis tests, regression, queueing, balls into bins. The tests and regression by hand, then Little’s law, the M/M/1 queue, and the balls-into-bins arithmetic behind load balancing.
The foundations at a glance
Section titled “The foundations at a glance”The sections above build specific tools. This overview collects the classical results they rest on, with one worked example for each topic, so that you can check a definition quickly or fill a gap before a section needs it.
Probability foundations
Section titled “Probability foundations”A sample space is the set of all possible outcomes, and an event is a subset of . Probability satisfies three axioms: ; ; and for disjoint and , extending to countable unions. Conditional probability is , and and are independent if .
Three theorems follow. Bayes’ theorem, , reverses a conditional probability: weight the likelihood by the prior and normalize. It is the engine of Bayesian inference. The law of total probability, for a partition of , computes the probability of by considering all the mutually exclusive ways it can happen. And inclusion-exclusion, , is the set identity carried over to probabilities.
Here is the classic example. A test for a disease is 99% sensitive () and 95% specific (), and the prevalence is 1%. By total probability, , and by Bayes, . Despite 99% sensitivity, the positive predictive value is only 16.7%, because the disease is rare.
Discrete random variables
Section titled “Discrete random variables”A random variable is a function that assigns a number to each outcome. Its probability mass function gives for each value, and its cumulative distribution function is . The expected value is , the variance is , and the standard deviation is .
Four discrete distributions cover most needs. A Bernoulli() variable takes values in with , so and . A Binomial() counts successes in independent Bernoulli trials: , , . A Geometric() counts trials until the first success: and . A Poisson() counts events in a fixed interval: and .
Linearity of expectation, , always holds, even for dependent variables; it is one of the most useful properties in all of probability. For independent and , : independent fluctuations add in quadrature.
For example, roll a fair die 10 times and let count the sixes, so . Then , , , and . Linearity also solves the coupon collector problem: the expected number of draws needed to collect all coupon types is , a sum of geometric waiting times.
Continuous random variables
Section titled “Continuous random variables”A continuous variable has a probability density function with and . Its CDF is , so . Expectation and variance become integrals: and .
The Uniform() density is on , with and . The Exponential() density is for , with and . The Normal() density is , the bell curve, with and ; standardizing, .
Two facts are worth memorizing. The 68-95-99.7 rule says a normal puts about 68% of its mass within one standard deviation of the mean, 95% within two, and 99.7% within three: it concentrates tightly. The exponential is memoryless, : it forgets how long you have been waiting, so the remaining wait has the same distribution regardless. It is the continuous analogue of the geometric distribution.
For example, if scores are Normal(72, 64), so the standard deviation is 8, the fraction above 88 is , about 2.3%. And if service time is Exponential(), then .
Joint distributions
Section titled “Joint distributions”A joint mass function or density gives probabilities for pairs. The marginal of is (or ), and the conditional is . Covariance, , measures linear association, and correlation, , always lies in .
and are independent if and only if for all : knowing tells you nothing about . In general , so positively correlated variables sum to something that fluctuates more than independent ones would. Covariance is bilinear: , , and .
For example, let , , , . The marginals are , , , . Since , the variables are not independent. With , , and (only the cell contributes), .
Limit theorems
Section titled “Limit theorems”The sample mean is , and converges in probability to if for every . The weak law of large numbers says that if are iid with mean , then in probability: the average of many independent measurements converges to the true mean, which is why sampling works. The central limit theorem says that if the are iid with mean and variance , then converges in distribution to : whatever the shape of the original distribution, the sample mean becomes approximately normal for large , which is why the normal appears everywhere. Chebyshev’s inequality, , is a distribution-free bound on spread: weak, but universally applicable.
For example, a factory produces items with mean weight 500 g and standard deviation 10 g. For a sample of , the CLT gives , so : about a 2.3% chance. Chebyshev, for any distribution with and , gives : at most 11.1% of values lie three or more standard deviations out, against 0.3% for a normal. Chebyshev is loose but general.
Descriptive statistics
Section titled “Descriptive statistics”The measures of center are the mean (arithmetic average), median (middle value), and mode (most frequent value). The measures of spread are the range, the interquartile range , the variance, and the standard deviation, where , (the median), and are the 25th, 50th, and 75th percentiles. A box plot displays the minimum, , median, , and maximum, and flags outliers beyond from the quartiles. A distribution is left-skewed when mean < median, right-skewed when mean > median, and symmetric when they are equal.
For example, for the data 3, 7, 7, 12, 15, 18, 22: the mean is and the median is 12 (the 4th value); , , and . The outlier fences are and , so there are no outliers.
Inference
Section titled “Inference”A point estimate is a single value estimating a parameter, as estimates . A confidence interval is an interval with , for example . Its interpretation is about the procedure, not any single interval: if you repeat the experiment many times, 95% of the 95% intervals constructed will contain the true parameter.
A test starts from a null hypothesis , the default claim (say ), and an alternative , the claim you seek evidence for (, or ). The test statistic is , or when is estimated. The p-value is the probability, assuming , of a statistic as extreme as or more extreme than the one observed. In the Neyman-Pearson framework you choose the significance level before the experiment and reject when , so controls how often you falsely declare an effect. A type I error rejects a true (probability ); a type II error fails to reject a false one (probability ).
For example, a company claims its batteries last 500 hours, and a sample of 36 gives and . Testing against at , and , so you reject : there is significant evidence that the mean lifetime is below 500 hours. The 95% interval excludes 500, consistent with the rejection.
Regression
Section titled “Regression”Simple linear regression fits with and . A residual is , observed minus predicted. The coefficient of determination is the proportion of the variance in explained by , and the correlation coefficient is , with for simple regression.
The least-squares estimates minimize : among all lines, the regression line makes the total squared error smallest, which is orthogonal projection from linear algebra, . The Gauss-Markov theorem adds that under the regression assumptions (linearity, independence, homoscedasticity, no perfect multicollinearity), the least-squares estimators are the best linear unbiased estimators: no unbiased linear estimator has smaller variance.
For example, take the points (1, 2), (2, 4), (3, 5), (4, 4), (5, 5), so and . Then and , giving and . The line is , predicting 4.0 at . The residual sum of squares is , and , so : the model explains 60% of the variance in .
Which technique when
Section titled “Which technique when”The table collects the techniques above by the question each answers.
| Technique | When to use | Key formula or idea |
|---|---|---|
| Bayes’ theorem | Reverse a conditional probability | |
| Law of total probability | Decompose by cases | |
| Linearity of expectation | Expected value of a sum | , always |
| CLT approximation | Distribution of a sample mean | for large |
| Z-test or t-test | Test a hypothesis about a mean | Compare the statistic with a critical value |
| Confidence interval | Estimate a parameter with uncertainty | |
| Least squares | Fit a linear model | Minimize the sum of squared residuals |
| Standardization | Convert to the standard normal |
Where these ideas appear in computing
Section titled “Where these ideas appear in computing”The same handful of ideas turns up across the field. Bayes’ theorem drives spam filters (naive Bayes) and probabilistic classification, and conditional probability underlies hidden Markov models and Bayesian networks. Poisson and exponential distributions model network traffic and queues. Linearity of expectation is the main tool for analysing randomized algorithms such as quicksort and hashing. The CLT and hypothesis testing are what make A/B tests and feature-flag experiments trustworthy, and regression is the baseline for machine learning. Variance and covariance appear in portfolio theory, PCA, and feature engineering.
In industry, this is the daily language of experimentation and data science: A/B testing at scale and experiment design at large web companies; demand forecasting, recommendation confidence, and pricing experiments in retail; risk models, option pricing, and stochastic processes in quantitative finance; Bayesian inference and evaluation metrics in machine learning; and Bayesian rating systems such as TrueSkill and Elo for matchmaking in games.
Key terms
Section titled “Key terms”- Sample space: the set of all possible outcomes of an experiment; an event is a subset of , and probability assigns each event a number between 0 and 1.
- Law of total probability: for a partition of the sample space; it computes a probability by adding up the mutually exclusive ways the event can happen, and it supplies the denominator in Bayes’ rule.
- Probability mass function (PMF): for a discrete random variable, the function giving the probability of each value; the values are nonnegative and sum to 1.
- Cumulative distribution function (CDF): , defined for every random variable, discrete or continuous; it rises from 0 to 1, and for a continuous variable its derivative is the density.
- Probability density function (PDF): for a continuous random variable, a function that integrates to 1, with ; a density value is not itself a probability.
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself.
- Linearity of expectation: , which holds even when and are dependent; it is the main tool for analysing randomized algorithms, such as the coupon collector’s expected draws.
- Binomial distribution: the number of successes in independent trials that each succeed with probability , with , mean , and variance ; a single trial is a Bernoulli variable.
- Poisson distribution: the count of events in a fixed interval when they occur independently at rate , with and mean and variance both ; it models arrivals at queues and servers.
- Normal distribution / Gaussian distribution: the bell-shaped density with mean and variance ; about 68%, 95%, and 99.7% of its mass lies within one, two, and three standard deviations of the mean, and the central limit theorem makes it the limit of sample means.
- Memoryless property: , so the remaining wait does not depend on how long you have already waited; the exponential distribution is the only continuous distribution with it, and the geometric the only discrete one.
- Correlation coefficient: , covariance rescaled to lie in ; it measures the strength of linear association, and zero correlation does not imply independence.
- Interquartile range (IQR): , the spread of the middle half of the data between the 25th and 75th percentiles; points more than beyond the quartiles are flagged as outliers in a box plot.
- Type-II error: failing to reject a null hypothesis that is false; its probability is , and is the power of the test.
- Least-squares regression: fitting the line that minimizes the sum of squared residuals , with ; it is orthogonal projection onto the column space.
- Coefficient of determination: , the fraction of the variance in that a regression explains; for simple linear regression it equals the squared correlation .
- Gauss-Markov theorem: under linearity, independence, constant error variance, and no perfect multicollinearity, the least-squares estimators have the smallest variance among all linear unbiased estimators.
Further reading
Section titled “Further reading”- Grinstead and Snell, Introduction to Probability (free): https://math.dartmouth.edu/~prob/prob/prob.pdf. Chapters 1 and 4 cover the foundations, 2 and 5 continuous densities, 5 and 6 discrete random variables, 7 joint distributions, and 8 and 9 the limit theorems. Useful exercises: Ch. 1 #1-8, #13-18; Ch. 2 #1-10; Ch. 4 #1-10, #17-22 (challenge #25-30); Ch. 5 #1-22 (continuous sections #10-20, challenge #25-30); Ch. 6 #1-8 (challenge #15-20); Ch. 7 #1-10, #15-20 (challenge #23-28); Ch. 8 #1-8; Ch. 9 #1-6 (challenge #10-14).
- OpenStax, Introductory Statistics (CC BY 4.0): https://openstax.org/details/books/introductory-statistics. Chapters 1 and 2 cover descriptive statistics, 8 to 10 inference, and 12 regression. Useful exercises: Ch. 2 #1-12, #20-28 (challenge #45-52); Ch. 8 #1-12; Ch. 9 #1-14 (challenge #60-70); Ch. 10 #1-10 (challenge #40-48); Ch. 12 #1-14, #30-40 (challenge #55-65).
- Seeing Theory, interactive visualizations of distributions, the CLT, and regression.
- Simulating experiments in Python with NumPy and SciPy is the fastest way to check a theoretical result; solve by hand first, then verify.