Beginner Course Home · First-Year Statistics: Estimation and Hypothesis Testing
The three versions of the notes, the ten demonstrations, a topic map across them, how to use them in class, and where to go next.
How I teach, the courses I have taught, and open teaching materials: lecture notes, demonstrations and code for eleven open courses, and teaching demos built from my research.
True understanding is demonstrated by the ability to explain complex ideas in simple and accessible terms. I treat teaching as a reciprocal and evolving learning process centred on clarity, simplicity, and active engagement, whose central goal is to build confidence, critical thinking, and strong problem-solving skills rather than memorisation of redundant technical detail.
Two principles shape how I put this into practice. The first is research-led teaching: the questions, examples, and open problems I bring to the classroom are drawn directly from live research, so that students learn not only established results but how new knowledge is actually created, and can see where the field is heading. The second is experiment-based, learning-by-doing teaching: rather than presenting finished theory, I have students explore, form and test hypotheses, run simulations, and discover the underlying principles for themselves, so that intuition comes before formalism.
These two principles directly motivate my Software Demos, collected for the classroom in the research pack below. I turn each of my research papers, across mathematical statistics and AI for science, into a self-contained, interactive, in-browser demonstration, so that even a first-year student can grasp the core idea and intuition behind a state-of-the-art method (mixture-of-experts model selection, optimal-transport aggregation, likelihood-free inference, efficient transformers) by clicking, dragging, and watching the method run, well before meeting its full mathematical machinery. Making the frontier of research understandable to a beginner is, for me, the clearest test of both good teaching and genuine understanding. The same approach shapes the eleven open courses in the teaching pack below, from first-year statistics to advanced probabilistic machine learning: each topic opens with a demonstration to predict and explore before the formulas, and closes by showing where the idea reappears in current research.
A third principle concerns how students use worked solutions and, increasingly, generative AI. Reading a complete derivation feels like understanding, but it rarely builds the ability to produce one. So I give gaps in proofs and practice problems graded hints that unlock one at a time: first the key idea, then the mathematical tools, then the steps with intermediate results to aim for. Each hint opens after a minute of thinking about the previous one, and the full solution two minutes after the last, to check one’s own argument. Students choose how much help they need and keep doing the thinking themselves, which is where critical thinking and problem-solving skills are built. I encourage them to use generative AI the same way: to ask for intuition, a demonstration or the next hint, then try again, rather than to ask for a finished solution. Four courses are built this way in full, the first-year, mathematical statistics, probability and statistical inference and advanced probabilistic machine learning courses, with hints on 1,851 derivations and problems (try the evidence lower bound). Writing the hints meant working through every derivation again, and the slips this uncovered, including some in the textbooks, are corrected and flagged in the notes. Students share the same critical reading: every derivation and problem has a link to report an error, and confirmed reports are listed with thanks on each course page.
Everything below is free to use in class. Eleven open courses pair lecture notes that fill in the steps a textbook skips with demonstrations linked from the notes at the results they illustrate; most add worked solutions and code that reproduces the book’s figures, and the first-year, mathematical statistics, probability and statistical inference and advanced probabilistic machine learning courses have graded hints on every derivation and problem. The demonstrations built from my own papers are in the research pack that follows.
Where to start.
Estimation and hypothesis testing for an introductory course: lecture notes in three versions (one for students of every science major, a beginner version with worked examples and R code, and an advanced version with full proofs) and ten demonstrations, one for each main result, each linked from the notes at the result it illustrates. Every proof and exercise answer comes with graded hints, and the course home maps each topic across the three versions and the demonstrations and points on to the mathematical statistics course and the graduate courses below. The cards follow a standard first-year syllabus.
Beginner Course Home · First-Year Statistics: Estimation and Hypothesis Testing
The three versions of the notes, the ten demonstrations, a topic map across them, how to use them in class, and where to go next.
Beginner Lecture Notes · How Sure Are We? Statistics for Every Science Major
Confidence intervals, P-values, power and two-group comparisons for first-year students of any science major, with examples from physics, chemistry, biology, earth science, psychology and health: no calculus, optional R, and a demonstration at every step.
In class: Open with the question "is 37 °C normal?", run the hundred-teams demonstration before defining 95%, then vote on which sentence about the interval is right.
Beginner Lecture Notes · Estimation and Hypothesis Testing
Estimators, bias and standard error, confidence intervals, P-values, t-tests, tests for proportions, and Type I and II errors and power, with one running example: is 37 °C really normal?
In class: Assign Part I before the estimation lecture and use the seven-step battery exercise as a tutorial warm-up.
Advanced Lecture Notes · Estimation and Hypothesis Testing
The same topics built up from the axioms of probability: the normal-sample theorem, t and chi-squared pivots, the Cramér–Rao bound, uniform P-values, test–interval duality, power formulas, the Neyman–Pearson lemma and the Welch degrees of freedom, each with a full proof that opens on click.
In class: For mathematics and statistics majors: read a theorem, predict, open the proof, then check it with a demonstration.
Beginner Estimators on Trial · Bias, Spread and the n − 1
Repeat a study thousands of times and compare two recipes for a guess: mean versus median, and dividing by n versus n − 1.
In class: Choose Spread at n = 5 and run 1000 studies: dividing by n lands 20% below the truth, while n − 1 sits on it.
Intermediate Maximum Likelihood · Climbing the Likelihood
See the log-likelihood of each sample, its top (the estimate) and its curvature (the standard error), then collect thousands of estimates and compare their spread with the Cramér–Rao bound.
In class: Draw one sample at a time for a proportion: the top is always at x/n. Then switch to the uniform model, where the top sits at the edge and calculus fails.
Beginner Averages on Trial · The Law of Large Numbers and the Central Limit Theorem
Average n values from a normal, uniform, skewed or yes/no population thousands of times: the averages gather at the mean, and once standardised they follow the bell curve, whatever the population's shape.
In class: Choose skewed data and step n from 1 to 5 to 30: the standardised averages turn into the bell curve, and the share beyond ±1.96 settles at 5%.
Beginner Confidence Intervals · Does the Method Catch the Truth?
A hundred research teams each build a 95% confidence interval for average body temperature; watch how many catch the true value, and when the method fails.
In class: Run 100 studies at n = 130 and see about 95 of 100 intervals catch the truth; then switch to n = 5 with the normal multiplier and watch coverage drop to about 88%, before Student's t repairs it.
Intermediate Why Student's t? · Inside the Normal-Sample Theorem
Each study records its mean and standard deviation: for normal data they are independent and give exact chi-squared and t pivots; for skewed or uniform data each promise fails.
In class: Compare normal and skewed data at n = 5: the cloud of (mean, SD) is shapeless for normal data and tilted for skewed data. At n = 30 the variance interval still covers only about 72%.
Beginner Tests and Intervals · Two Views of One Object
For fixed data, plot the t-test's P-value against every hypothesised mean: the values it does not reject form exactly the confidence interval.
In class: Drag the hypothesised mean across the body-temperature interval: the P-value crosses 0.05 exactly at the endpoints, and 37 °C is far outside.
Beginner A Hypothesis Test on Trial · P-values, Errors and Power
Run thousands of t-tests: when the null hypothesis is true, false alarms happen at rate α; when it is false, the rejection rate is the power.
In class: Start with d = 0 to see flat P-values and about 5% false alarms, then try n = 5 versus n = 50 at d = 0.5: power rises from about 24% to 97%.
Beginner Power and Sample Size · Two Bell Curves
Slide the effect size and the sample size to see α, β and power as areas under two bell curves, trace the power curve, and read off the sample size for 80% or 90% power.
In class: Start at d = 0.5 and n = 25 (power 80%), then halve d: the required sample size quadruples to 99.
Intermediate Counting Successes · Exact and Approximate Methods for Proportions
Computed exactly from binomial probabilities: why the exact test cannot use its full 5%, when the z-test oversteps it, and how the coverage of the Wald interval swings below 95%.
In class: Step n from 10 to 100 for the taste test: the exact test's size zig-zags below 5% while the z-test's crosses above it.
Intermediate Two Samples · Pooled or Welch, Paired or Not?
Thousands of two-sample studies: the pooled t-test's false-alarm rate breaks when sizes and spreads both differ, Welch's holds, and pairing multiplies power.
In class: With group sizes 30 and 10 and spread ratio 3, the pooled test rejects about 21% of true null hypotheses while Welch stays at 5%; then switch to the paired sleep study.
Lecture notes, demonstrations and Python code for a course on Bayesian and probabilistic machine learning, following Chapters 1 to 14 of Bishop, C. M. (2006), Pattern Recognition and Machine Learning, Springer, and an advanced module on deep generative models, taken further in the advanced probabilistic machine learning course below. The course has lecture notes that write out every derivation the book skips, forty-six demonstrations linked from the notes at the results they illustrate, and Python code that reproduces the numerical figures and the experiments of the book's own code. Start at the course home.
Intermediate Lecture Notes · Introduction (Chapter 1)
Polynomial curve fitting and over-fitting, probability theory, the curse of dimensionality, decision theory and information theory. Every derivation the book skips is written out.
Demos: Curve fitting, over-fitting and Bayesian curve fitting · Decision theory, entropy and KL divergence
In class: Fit polynomials of order 0, 1, 3 and 9 to ten points and ask which model a new point should trust; then add data, or regularise.
Intermediate Lecture Notes · Probability Distributions (Chapter 2)
Binomial, beta, multinomial, Dirichlet and Gaussian distributions, conjugate Bayesian inference, the exponential family and nonparametric density estimation. Every derivation the book skips is written out.
Demos: Conjugate Bayesian updating · Histograms, kernels and nearest neighbours
In class: Update a beta prior one coin toss at a time and watch the posterior narrow; then switch to the Gaussian with unknown precision.
Intermediate Lecture Notes · Linear Models for Regression (Chapter 3)
Least squares and ridge regression, the bias-variance decomposition, Bayesian linear regression, the equivalent kernel and the evidence approximation. Every derivation the book skips is written out.
Demos: Bayesian linear regression · Bias and variance · The evidence approximation
In class: Draw functions from the posterior as data arrive: the band pinches around the points and fans out between them.
Intermediate Lecture Notes · Linear Models for Classification (Chapter 4)
Discriminant functions, Fisher's discriminant, the perceptron, generative and discriminative models, logistic regression with IRLS, the Laplace approximation and Bayesian logistic regression. Every derivation the book skips is written out.
Demos: Least squares, Fisher and the perceptron · Logistic regression and the Laplace approximation
In class: Add outliers to a two-class problem and see least squares tilt its boundary while logistic regression barely moves.
Advanced Lecture Notes · Neural Networks (Chapter 5)
Network functions, training, backpropagation and the Hessian, regularisation, mixture density networks and Bayesian neural networks. Every derivation the book skips is written out.
Demos: Backpropagation and over-fitting · Mixture density networks · Bayesian neural networks
In class: Train a three-hidden-unit network on a sine curve, then add units and stop early to see over-fitting and how to prevent it.
Advanced Lecture Notes · Kernel Methods (Chapter 6)
Dual representations, constructing kernels, radial basis function networks and Gaussian processes for regression and classification. Every derivation the book skips is written out.
Demos: Kernels and Nadaraya-Watson · Gaussian process regression · Gaussian process classification
In class: Draw functions from a Gaussian process prior, condition on a few points and change the length scale.
Advanced Lecture Notes · Sparse Kernel Machines (Chapter 7)
Maximum margin classifiers, support vector machines for classification and regression, and the relevance vector machine. Every derivation the book skips is written out.
Demos: Support vector machines · Relevance vector machines
In class: Move a point that is not a support vector: nothing changes; move one that is: the boundary follows.
Advanced Advanced Topics · Deep Generative Models (from Bishop to Murphy)
Four lectures that carry the course beyond Bishop: variational autoencoders with a latent-space explorer, normalizing flows with exact densities, autoregressive pixel models with causal masks, and denoising diffusion with reverse sampling. Each lecture has a demonstration that reproduces the experiment of Murphy's book code.
Demos: VAE latent space · normalizing flows · autoregressive pixels · diffusion · VAE on the Chapter 9 data · flows, classic · schedules
In class: Decode a point in the VAE latent space, then ask which direction the decoder ignores (posterior collapse) before moving on to flows and diffusion.
Advanced Lecture Notes · Graphical Models (Chapter 8)
Bayesian networks and Markov random fields, conditional independence and d-separation, factor graphs, and the sum-product and max-sum algorithms, with every proof written out.
Demos: d-separation · image de-noising · belief propagation
In class: Ask whether two causes of an alarm are independent, then observe the alarm in the d-separation demonstration and watch them become dependent: explaining away.
Advanced Lecture Notes · Mixture Models and EM (Chapter 9)
K-means, Gaussian mixtures by maximum likelihood, the EM algorithm in general and why it never decreases the likelihood, Bernoulli mixtures and EM for Bayesian linear regression, with every derivation the book skips written out.
Demos: K-means and EM on Old Faithful · why EM climbs
In class: Run K-means on Old Faithful one half step at a time and watch the cost fall at every step; then switch to EM and push one component onto a single data point to see the likelihood blow up.
Advanced Lecture Notes · Approximate Inference (Chapter 10)
Variational inference and mean field, the variational mixture of Gaussians, variational linear and logistic regression, local variational bounds and expectation propagation, with the full derivations of every update and every term of the lower bound.
Demos: KL(q‖p) versus KL(p‖q) · mean-field VB · variational mixtures · variational logistic regression · expectation propagation
In class: Ask the class which single Gaussian best approximates a two-peaked density, then show that the answer depends on which way round the KL divergence is taken.
Advanced Lecture Notes · Sampling Methods (Chapter 11)
Transformation, rejection and importance sampling, Monte Carlo EM, Markov chains and detailed balance, Metropolis–Hastings, Gibbs and slice sampling, Hamiltonian Monte Carlo and partition functions, with every proof of correctness written out.
Demos: from uniform numbers to any distribution · Metropolis and Gibbs · slice sampling and Hamiltonian Monte Carlo
In class: Run Metropolis on a strongly correlated Gaussian with a small, a good and a large step, and ask which chain has explored the target; then switch to Hamiltonian Monte Carlo.
Advanced Lecture Notes · Continuous Latent Variables (Chapter 12)
PCA by maximum variance and by minimum error, probabilistic PCA and the full derivation of its maximum-likelihood solution, EM for PCA, Bayesian PCA, factor analysis, kernel PCA and nonlinear latent variable models.
Demos: PCA and probabilistic PCA · kernel PCA · Bayesian PCA
In class: Rotate a direction through a cloud of points: the variance of the projections rises exactly as the reconstruction error falls, so the two definitions of PCA agree.
Advanced Lecture Notes · Sequential Data (Chapter 13)
Hidden Markov models with forward-backward, scaling, Viterbi and Baum-Welch, and linear dynamical systems with the Kalman filter, smoother and particle filters, each derived in full.
Demos: hidden Markov models · Kalman filter · particle filters
In class: Track a moving object with the Kalman filter, then turn up the measurement noise and ask the class whether to trust the model or the data.
Advanced Lecture Notes · Combining Models (Chapter 14)
Model averaging versus model combination, committees and bagging, AdaBoost as stagewise minimisation of the exponential error, decision trees, and conditional mixtures up to mixtures of experts.
Demos: AdaBoost · bagging and trees · mixtures of experts
In class: Add decision stumps one at a time and watch the weights move onto the points the ensemble still gets wrong.
Intermediate Mathematical Toolkit · The Identities Behind the Derivations
Jensen's inequality, the KL divergence, Lagrange multipliers, matrix derivatives, the Woodbury identity, Gaussian identities, exponential families, and the Gamma, Dirichlet, Wishart and Student t distributions, each stated once and proved.
In class: Assign it before the first lecture as a self-test: students who can prove the Lagrange simplex result and the log-determinant derivative are ready for Chapter 9.
Intermediate Python Code · Reproducing the Book's Figures
One module per chapter and one function per figure: readable numpy implementations of K-means, EM, variational Bayes, expectation propagation, PPCA, kernel PCA, GTM, AdaBoost and mixtures of experts.
In class: Ask students to change one setting (a prior, an initialisation, a data set), rerun a figure and explain what changed.
Lecture notes, demonstrations and R code for a course on statistics for biological data, following Chapters 1 to 13 of Holmes, S. and Huber, W. (2019), Modern Statistics for Modern Biology, Cambridge University Press. The notes write out the mathematics and statistics the book states without proof, forty-seven demonstrations run the methods on the book's data sets, and the R code reproduces the book's figures. Start at the course home.
Intermediate Course Home · Statistical Methods for Modern Biology
All thirteen chapters with their demonstrations and code, how the notes are organised, and how to use them in class.
Intermediate Lecture Notes · Generative Models for Discrete Data (Chapter 1)
Binomial, Poisson and multinomial models for counts, testing by simulating the null distribution, and the chi-square statistic.
Demos: Binomial counts and their Poisson limit · Is the spike real? The maximum of Poisson counts · Testing nucleotide frequencies: the chi-square statistic and power
In class: Ask whether a spike of 7 in the epitope data is surprising, let students guess, then open the maximum-of-counts demonstration and compute the exact answer.
Intermediate Lecture Notes · Statistical Modeling (Chapter 2)
Maximum likelihood and goodness of fit for counts, Bayesian updating with conjugate priors, Hardy-Weinberg equilibrium, and Markov chains for DNA sequences (CpG islands).
Demos: Likelihood for count data: Poisson, binomial and Hardy-Weinberg · Pearson's chi-square statistic: simulation against theory · Bayesian updating of a proportion: Beta prior, binomial data · Markov chain scores for CpG islands
In class: Fit the Poisson to the count data, look at the rootogram, then update a beta prior one batch at a time and compare equal-tailed and HPD intervals.
Intermediate Lecture Notes · Data visualization (Chapter 3)
The statistics behind the graphics: kernel density estimates, empirical CDFs and QQ plots, two-dimensional densities and hexagonal binning, heatmaps, colour spaces and transformations.
Demos: Kernel density estimation and the bandwidth · The empirical CDF, the DKW band and QQ plots · 45,101 points on one plot: transparency, hexagonal bins, 2-D densities and the MA plot · Variance-stabilising transformations and the delta method
In class: Show the same 45,000 points four ways (scatter, transparency, hexagons, density) and ask which plot answers which question.
Intermediate Lecture Notes · Mixture Models (Chapter 4)
Finite mixtures and the EM algorithm, zero inflation, the empirical distribution and the bootstrap, the gamma-Poisson (negative binomial) model and variance-stabilising transformations.
Demos: EM for a mixture of two normals, step by step · Zero-inflated counts: ChIP-Seq bins and the EM algorithm · The nonparametric bootstrap on Darwin's Zea mays data · Gamma-Poisson counts and variance-stabilising transformations
In class: Run EM from a poor start and watch the log-likelihood rise; then bootstrap Darwin's maize differences and compare the bootstrap and exact standard errors.
Intermediate Lecture Notes · Clustering (Chapter 5)
Distances, k-means and PAM, hierarchical clustering, density-based clustering, choosing the number of clusters, and clustering mass cytometry data and sequencing reads.
Demos: k-means, k-medoids and PAM, step by step · Mass cytometry: the asinh transform and density-based clustering (DBSCAN) · Hierarchical clustering: linkages, dendrograms and cuts · How many clusters? The gap statistic, Calinski-Harabasz and silhouettes
In class: Run k-means and PAM on the same points, then ask the class to choose k before showing the gap statistic and the silhouettes.
Intermediate Lecture Notes · Testing (Chapter 6)
Tests and p-values, permutation tests, and multiple testing: family-wise error, Benjamini-Hochberg false discovery rate control, local fdr, independent filtering and hypothesis weighting.
Demos: The exact binomial test: rejection regions, p-values and power · The t-test and the permutation test on the PlantGrowth data · P-value hacking: optional stopping and choosing the best test statistic · Multiple testing on the airway data: p-value histogram, Benjamini-Hochberg, hypothesis weighting
In class: Simulate optional stopping in the p-hacking demonstration, then apply Benjamini-Hochberg to the airway p-values and read the p-value histogram.
Intermediate Lecture Notes · Multivariate Analysis (Chapter 7)
Centring and scaling, the singular value decomposition and the Eckart-Young theorem, principal component analysis, biplots, and when components are stable.
Demos: Regression lines and the principal component line · PCA explorer: scree plot, principal plane, correlation circle and biplot · The SVD and the best rank-k approximation · When are principal components stable? Interactive demo, TrungTin Nguyen
In class: Rotate a line through the turtle data until the projected variance is largest, then compare it with both regression lines.
Advanced Lecture Notes · High-Throughput Count Data and Generalized Linear Models (Chapter 8)
RNA-seq counts: size factors, the negative binomial generalized linear model, IRLS, Wald and likelihood ratio tests, dispersion shrinkage and variance-stabilising transformations.
Demos: Size factors and the mean-variance relationship of counts · The negative binomial GLM for one gene: IRLS, Wald and likelihood ratio tests, shrinkage · Dispersion shrinkage and variance stabilisation for count data
In class: Compute size factors by hand for a small table, then fit one gene's negative binomial GLM and compare the Wald and likelihood ratio tests.
Advanced Lecture Notes · Multivariate methods for heterogeneous data (Chapter 9)
Multidimensional scaling, correspondence analysis, the horseshoe effect, t-SNE, the RV coefficient, canonical correlation and sparse CCA, and constrained ordination.
Demos: Classical and nonmetric multidimensional scaling · Correspondence analysis of contingency tables · The horseshoe effect: why gradients make arches · RV coefficient and sparse canonical correlation analysis
In class: Build a map of Ukrainian cities from their distances alone, then run correspondence analysis on hair and eye colour and read the biplot.
Advanced Lecture Notes · Networks and Trees (Chapter 10)
Graphs and their Laplacians, network analyses, substitution models and phylogenetic trees (Jukes-Cantor, neighbour joining, Felsenstein's pruning), and the minimum-spanning-tree two-sample test.
Demos: Substitution models and evolutionary distances: Jukes-Cantor and Kimura · Estimating a phylogeny: simulation down a tree, neighbour joining and Felsenstein's likelihood · Graph-based two-sample tests: the Friedman-Rafsky test on the mouse microbiome
In class: Simulate sequences down a tree, estimate the Jukes-Cantor distances and rebuild the tree with neighbour joining.
Advanced Lecture Notes · Image data (Chapter 11)
Images as arrays, filtering and convolution, thresholding and morphology, segmentation by watershed and Voronoi propagation, and spatial point patterns (Ripley's K and L, pair correlation).
Demos: Segmenting nuclei: smoothing, adaptive thresholding and morphology · Voronoi tessellation on an image manifold: segmenting cell bodies · Spatial point patterns: Ripley's K, L, the pair correlation and G
In class: Segment nuclei step by step (smooth, threshold, open, label) and count them; then test a point pattern against complete spatial randomness with Ripley's L.
Intermediate Lecture Notes · Supervised Learning (Chapter 12)
Discriminant analysis, logistic regression, overfitting and cross-validation, the curse of dimensionality, the bias-variance trade-off, ridge, lasso and elastic net, and support vector machines.
Demos: Linear and quadratic discriminant analysis on the diabetes data · Overfitting, cross-validation and the curse of dimensionality · Ridge, lasso and elastic net: penalised logistic regression on the stool microbiome
In class: Fit LDA and QDA to the diabetes data, then show selection bias by choosing features outside the cross-validation loop.
Intermediate Lecture Notes · Design of High Throughput Experiments and their Analyses (Chapter 13)
Experimental design: randomisation, blocking and pairing, power and sample size, replicates and pseudoreplication, the design effect, batch effects and regression to the mean.
Demos: Effective sample size: clustered polls, the design effect and pseudoreplication · Hotelling's weighing designs: clever combinations of measurements · Blocking and pairing: paired versus unpaired t-tests, and Darwin's maize · Power and sample size of the t-test from the noncentral t distribution
In class: Compare the paired and unpaired analyses of Darwin's maize, then find the sample size that gives 80% power in the power demonstration.
Intermediate R Code · Reproducing the Book's Figures
One script per chapter and one function per figure, reproducing 318 figures from the book's data with the CRAN and Bioconductor packages it uses.
In class: Ask students to change one choice (a transformation, a distance, a prior, a filter), rerun a figure and explain what changed.
Lecture notes, demonstrations and Python code for a course on deep learning, following Chapters 1 to 20 and the appendices of Bishop, C. M. and Bishop, H. (2024), Deep Learning: Foundations and Concepts, Springer. The notes write out every derivation the book skips and give worked solutions to the exercises, sixty-five demonstrations let students train and probe networks in the browser, and the code reproduces the book's figures with numpy and PyTorch. Chapters that overlap the Bayesian and probabilistic machine learning course link to it. Start at the course home.
Intermediate Course Home · Foundations of Deep Learning
All twenty chapters and the mathematical appendices with their demonstrations and code, how the notes are organised, and how to use them in class.
Intermediate Lecture Notes · The Deep Learning Revolution (Chapter 1)
Polynomial curve fitting, error functions, over-fitting and regularisation, model selection, and a short history of neural networks from the perceptron to deep learning.
Demos: Polynomial curve fitting on the book's data: order, data size and weight decay · Model selection: S-fold cross-validation and the optimism of the training error · Three phases of neural networks: the perceptron, backpropagation and depth
In class: Fit polynomials of increasing order to the book's ten points and ask when the test error turns up, then add weight decay.
Intermediate Lecture Notes · Probabilities (Chapter 2)
The rules of probability and Bayes' theorem, densities and the change of variables, the Gaussian and its maximum likelihood estimates, and information theory: entropy, KL divergence and mutual information.
Demos: Bayes' theorem: medical screening and the bent coin · Gaussian maximum likelihood and the bias of the variance · Change of variables: the Jacobian and the moving mode · Entropy, KL divergence and mutual information
In class: Ask the class for the probability of cancer after a positive test before showing Bayes' theorem, then move the prior.
Intermediate Lecture Notes · Standard Distributions (Chapter 3)
Discrete distributions, the multivariate Gaussian (conditionals, marginals, linear-Gaussian models), mixtures, periodic variables, the exponential family and nonparametric density estimation.
Demos: The multivariate Gaussian: geometry, conditionals, marginals and Bayes' theorem · Periodic variables and the von Mises distribution · The exponential family: sufficient statistics and moment matching
In class: Condition a two-dimensional Gaussian on one coordinate and predict the conditional mean and variance before revealing them.
Intermediate Lecture Notes · Single-layer Networks: Regression (Chapter 4)
Linear regression with basis functions, least squares as projection, sequential learning, regularised least squares, decision theory for regression and the bias-variance decomposition.
Demos: Linear regression with basis functions: least squares, the pseudo-inverse and regularisation · Sequential learning: the LMS algorithm (stochastic gradient descent for least squares) · Decision theory for regression: the Minkowski loss, mean, median and (not quite) mode
In class: Vary the regularisation strength and watch the bias and variance trade places; then fit with the LMS algorithm one point at a time.
Intermediate Lecture Notes · Single-layer Networks: Classification (Chapter 5)
Discriminant functions, decision theory and ROC curves, generative classifiers with Gaussian classes, logistic and softmax regression, probit regression and canonical links.
Demos: Training single-layer classifiers: least squares, logistic, probit and softmax regression · Decision theory: loss matrix, reject option and the ROC curve · Generative classifiers: Gaussian class densities, linear and quadratic boundaries
In class: Move the decision threshold along the ROC curve and ask which loss matrix each point corresponds to.
Advanced Lecture Notes · Deep Neural Networks (Chapter 6)
Limitations of fixed basis functions, multilayer networks and activation functions, universal approximation, depth and linear regions, error functions and mixture density networks.
Demos: The curse of dimensionality: geometry of high-dimensional spaces · Two-layer networks as universal approximators, and the choice of activation function · Linear regions of ReLU networks: width against depth · Inverse kinematics of a robot arm with a mixture density network
In class: Count the linear regions of a ReLU network as depth and width change, and compare with the curse-of-dimensionality picture.
Advanced Lecture Notes · Gradient Descent (Chapter 7)
Error surfaces and the Hessian, gradient descent and its convergence, stochastic and mini-batch gradients, initialisation, momentum, Adam, and batch and layer normalisation.
Demos: Optimisers on a two-dimensional error surface · Step size versus condition number · Initialisation and activation statistics through depth
In class: Race gradient descent, momentum and Adam on the same error surface, then push the step size past 2 over the largest eigenvalue.
Advanced Lecture Notes · Backpropagation (Chapter 8)
Backpropagation for general networks, numerical differentiation, the Jacobian and the Hessian, and automatic differentiation in forward and reverse mode.
Demos: Backpropagation step by step, with a gradient check · Forward-mode and reverse-mode automatic differentiation · The Hessian, its outer-product approximation and Hessian-vector products
In class: Step through backpropagation on a small network and confirm each gradient with finite differences.
Advanced Lecture Notes · Regularization (Chapter 9)
Inductive bias, invariance and data augmentation, weight decay and L1 sparsity, early stopping, parameter sharing, residual connections, model averaging and dropout.
Demos: L1 versus L2 regularisation: paths and sparsity · Early stopping versus weight decay · Dropout and ensembles
In class: Compare the L1 and L2 regularisation paths, then show that early stopping behaves like weight decay.
Advanced Lecture Notes · Convolutional Networks (Chapter 10)
Convolution and its equivariance, padding, stride and pooling, multi-channel layers, the backward pass, visualising trained networks, adversarial examples and detection.
Demos: Convolution arithmetic: kernel, padding, stride and dilation · Inside a small convolutional network: filters, feature maps and Grad-CAM · Adversarial examples: the fast gradient sign method
In class: Change padding, stride and dilation and predict the output size; then fool the trained network with the fast gradient sign method.
Intermediate Lecture Notes · Structured Distributions (Chapter 11)
Directed graphical models, conditional independence and d-separation, explaining away, naive Bayes, linear-Gaussian models, and Markov and autoregressive models of sequences.
Demos: Explaining away and d-separation with exact probabilities · Linear-Gaussian graphical models and ancestral sampling · Markov models of text of order k
In class: Use the fuel-gauge network to show explaining away with exact numbers before stating d-separation.
Advanced Lecture Notes · Transformers (Chapter 12)
Attention, self-attention and multi-head attention, positional encodings, the transformer layer, tokenisation and language models, sampling strategies and vision transformers.
Demos: Attention explorer: queries, keys, values, scaling, masks and positions · Sampling strategies: temperature, top-k, nucleus, greedy and beam search · A tiny character transformer generating text in the browser
In class: Change the temperature and the causal mask in the attention explorer, then let the tiny transformer write text with different sampling rules.
Advanced Lecture Notes · Graph Neural Networks (Chapter 13)
Graphs and permutation symmetry, message passing, graph convolutional networks, node, edge and graph tasks, over-smoothing, graph attention and geometric deep learning.
Demos: Permutation equivariance of a graph layer · Message passing and over-smoothing · A graph convolutional network trained live
In class: Shuffle the nodes of a graph and show that the layer's output shuffles with them; then add layers until the features over-smooth.
Intermediate Lecture Notes · Sampling (Chapter 14)
Monte Carlo estimation, rejection and importance sampling, Markov chain Monte Carlo, Langevin dynamics, energy-based models and gradient estimators for expectations.
Demos: Langevin sampling on an energy landscape · Training an energy-based model: positive and negative phases · Gradients of expectations: score function versus reparameterisation
In class: Run Langevin sampling with too large a step, then switch on the Metropolis correction.
Advanced Lecture Notes · Discrete Latent Variables (Chapter 15)
K-means and vector quantisation, Gaussian mixtures and the EM algorithm, Bernoulli mixtures, and the evidence lower bound that later chapters build on.
Demos: K-means colour quantisation and vector quantisation · The evidence lower bound during EM · A mixture of Bernoulli distributions on handwritten digits
In class: Quantise an image with K-means for K = 2, 3 and 10, then watch the evidence lower bound touch the log likelihood at each EM step.
Advanced Lecture Notes · Continuous Latent Variables (Chapter 16)
Principal component analysis, probabilistic PCA, factor analysis, independent component analysis, Kalman filters and nonlinear latent variable models.
Demos: Eigen-digits: PCA compression of handwritten threes · Independent component analysis: unmixing two sources · A nonlinear latent variable model in two dimensions
In class: Reconstruct a handwritten three from 1, 10, 50 and 250 principal components.
Advanced Lecture Notes · Generative Adversarial Networks (Chapter 17)
The adversarial game, the optimal discriminator and the Jensen-Shannon divergence, training difficulties and mode collapse, Wasserstein GANs, conditional GANs and CycleGAN.
Demos: Training a GAN on a ring of Gaussians: minimax and non-saturating losses, mode collapse · The optimal discriminator and the Jensen-Shannon divergence · Wasserstein distance versus Jensen-Shannon divergence
In class: Train a GAN on a ring of eight Gaussians and catch mode collapse as it happens.
Advanced Lecture Notes · Normalizing Flows (Chapter 18)
The change of variables for invertible networks, coupling flows, masked autoregressive and inverse autoregressive flows, and continuous flows with neural ODEs.
Demos: A trained real NVP coupling flow, run forwards and backwards · Masked and inverse autoregressive flows: which direction is cheap · A continuous normalizing flow: the trace term and Hutchinson's estimator
In class: Map a point back through each layer of a trained coupling flow and add up the log-determinants.
Advanced Lecture Notes · Autoencoders (Chapter 19)
Deterministic, sparse, denoising and masked autoencoders, the link to PCA and to the score, and variational autoencoders with the reparameterisation trick.
Demos: A linear autoencoder against PCA: subspace yes, eigenvectors no · A denoising autoencoder learns the score · The ELBO gap: a Gaussian q against a bimodal posterior · The beta trade-off in a VAE: rate, distortion and posterior collapse
In class: Increase beta in the VAE and watch reconstructions blur and latent dimensions switch off.
Advanced Lecture Notes · Diffusion Models (Chapter 20)
The forward noising process, the reverse process and its evidence lower bound, noise prediction and score matching, stochastic differential equations and guidance.
Demos: The forward process of a diffusion model and its closed form · Reverse sampling with a trained denoiser: steps, noise and determinism · Classifier-free guidance on a two-dimensional conditional mixture
In class: Noise a spiral step by step, then sample it back with 200, 20 and 5 steps and compare the stochastic and deterministic samplers.
Intermediate Mathematical Appendices · Linear Algebra, Calculus of Variations, Lagrange Multipliers
Linear algebra (determinants, inverses, eigenvectors, matrix derivatives), the calculus of variations (functional derivatives and the Euler-Lagrange equation) and Lagrange multipliers with the KKT conditions.
Demos: Eigenvectors and a matrix as a linear map · Lagrange multipliers and the KKT conditions
In class: Show the gradients of the objective and the constraint lining up at a constrained optimum, then make the constraint an inequality.
Intermediate Python Code · Reproducing the Book's Figures
One module per chapter and one function per figure: numpy and PyTorch implementations of networks, optimisers, backpropagation, CNNs, transformers, GNNs, GANs, flows, autoencoders and diffusion models, small enough to run on a CPU.
In class: Ask students to change one setting (a learning rate, an initialisation, a depth, a noise schedule), rerun a figure and explain what changed.
Lecture notes, demonstrations and Python code for a graduate course on statistical learning, following Chapters 1 to 18 of Hastie, T., Tibshirani, R. and Friedman, J. (2009), The Elements of Statistical Learning, 2nd edition, Springer. The notes write out the derivations the book leaves out and give worked solutions to the exercises, fifty-three demonstrations run the methods on the book's data, and the code reproduces the book's figures. Start at the course home.
Intermediate Course Home · Statistical Learning: Theory and Methods
All eighteen chapters with their demonstrations and code, how the notes are organised, and how to use them in class.
Intermediate Lecture Notes · Introduction (Chapter 1)
The book's motivating examples (spam, prostate cancer, handwritten digits, DNA microarrays) and the supervised-learning framework: inputs, outputs, loss, risk, training and test error.
Demos: Prostate cancer data: simple fits, training error and test error · Email spam: word frequencies by class and simple rules
In class: Fit the mean, a line and k-nearest neighbours to one prostate input and compare training and test error.
Intermediate Lecture Notes · Overview of Supervised Learning (Chapter 2)
Least squares and nearest neighbours as two extremes, statistical decision theory, the curse of dimensionality, structured regression models and the bias-variance trade-off.
Demos: Least squares versus k-nearest neighbours on the mixture data · The curse of dimensionality: neighbourhoods that are not local · The bias-variance trade-off for k-nearest-neighbour regression
In class: Move k in the nearest-neighbour classifier on the mixture data and watch training and test error part ways; then watch nearest-neighbour distances grow with the dimension.
Advanced Lecture Notes · Linear Methods for Regression (Chapter 3)
Least squares and its sampling theory, the Gauss-Markov theorem, subset selection, ridge regression and the lasso, least angle regression, principal components and partial least squares.
Demos: Ridge and lasso on the prostate data: coefficient paths and df(λ) · Least angle regression step by step, and the lasso path · PCR, PLS and ridge: shrinking along principal components
In class: Step through least angle regression on the prostate data and see where it departs from the lasso path.
Advanced Lecture Notes · Linear Methods for Classification (Chapter 4)
Indicator regression and masking, linear and quadratic discriminant analysis, reduced-rank LDA, logistic regression by IRLS, and separating hyperplanes.
Demos: Masking: regression of an indicator matrix versus LDA · Reduced-rank LDA on the vowel data · Logistic regression on the heart disease data: IRLS step by step and the L1 path
In class: Show masking with three classes on a line, then fit reduced-rank LDA to the vowel data.
Advanced Lecture Notes · Basis Expansions and Regularization (Chapter 5)
Piecewise polynomials and splines, natural cubic splines, smoothing splines and their degrees of freedom, reproducing kernel Hilbert spaces, wavelets and B-splines.
Demos: Regression splines with movable knots: truncated powers versus B-splines · Smoothing splines: degrees of freedom and the eigenvalues of the smoother · Wavelet shrinkage of a noisy signal: SURE and the universal threshold
In class: Drag the knots of a regression spline, then slide the degrees of freedom of a smoothing spline and look at the shrinking eigenvalues.
Advanced Lecture Notes · Kernel Smoothing Methods (Chapter 6)
Kernel smoothers, local linear and polynomial regression and their boundary bias, local likelihood, kernel density estimation and classification, naive Bayes.
Demos: Local regression at the boundary: Nadaraya-Watson, local linear and local quadratic · Choosing the bandwidth of a kernel density estimate by cross-validation · Local logistic regression on the heart disease data
In class: Compare Nadaraya-Watson and local linear fits at the boundary and look at their equivalent kernels.
Advanced Lecture Notes · Model Assessment and Selection (Chapter 7)
Bias, variance and model complexity, the optimism of the training error, Cp, AIC and BIC, minimum description length, the VC dimension, cross-validation and the bootstrap.
Demos: Optimism of the training error, Cp and BIC against the in-sample error · Cross-validation the wrong and the right way, after screening thousands of inputs · Bootstrap estimates of prediction error: leave-one-out, .632 and .632+ against cross-validation
In class: Cross-validate the wrong way and the right way with thousands of noise predictors.
Advanced Lecture Notes · Model Inference and Averaging (Chapter 8)
The bootstrap and maximum likelihood, Bayesian inference, the EM algorithm, MCMC and Gibbs sampling, bagging, model averaging, stacking and bumping.
Demos: Bootstrap, maximum likelihood and Bayesian bands for a B-spline smoother · Gibbs sampling against EM for a two-component mixture · Bagging classification trees: variance reduction and the 0-1 loss caveat
In class: Compare bootstrap and Bayesian bands, then run Gibbs sampling and EM on the same mixture.
Advanced Lecture Notes · Additive Models, Trees, and Related Methods (Chapter 9)
Generalized additive models and backfitting, regression and classification trees, PRIM, MARS, hierarchical mixtures of experts and missing data.
Demos: Backfitting an additive model, one smoother at a time · Growing and pruning a classification tree on the spam data · MARS: reflected pairs, the forward pass and the backward pass
In class: Grow and prune a tree on the spam data and pick the size by cross-validation with the one-standard-error rule.
Advanced Lecture Notes · Boosting and Additive Trees (Chapter 10)
AdaBoost and forward stagewise additive modelling, exponential loss, boosting trees, gradient boosting, regularisation, and interpretation with importance and partial dependence.
Demos: AdaBoost with stumps on the nested-spheres problem · Gradient boosting for regression: shrinkage, subsampling and robust losses · Relative importance and partial dependence for boosted trees on the spam data
In class: Run AdaBoost with stumps on the nested spheres and watch the test error keep falling after the training error reaches zero.
Advanced Lecture Notes · Neural Networks (Chapter 11)
Projection pursuit regression, single-hidden-layer networks, back-propagation, weight decay and starting values, and the ZIP code networks.
Demos: Projection pursuit regression: ridge functions and Gauss-Newton directions · Hidden units and weight decay on the simulated data of Chapter 11 · Local connectivity and weight sharing: the five ZIP code networks
In class: Fit a single-hidden-layer network with and without weight decay and compare test errors.
Advanced Lecture Notes · Support Vector Machines and Flexible Discriminants (Chapter 12)
The support vector classifier and its dual, kernels, the hinge loss, the SVM regularisation path, flexible, penalised and mixture discriminant analysis.
Demos: The SVM regularisation path on the mixture data · Flexible discriminant analysis by optimal scoring on the vowel data · Mixture discriminant analysis on the mixture data
In class: Trace the full SVM regularisation path and watch support vectors enter and leave.
Advanced Lecture Notes · Prototype Methods and Nearest-Neighbors (Chapter 13)
Prototype methods (K-means, LVQ, Gaussian mixtures), nearest-neighbour classifiers and the Cover-Hart bound, tangent distance and adaptive (DANN) metrics.
Demos: K-means and LVQ prototypes · The k-nearest-neighbour error and the Cover-Hart bound · Discriminant adaptive nearest neighbours (DANN)
In class: Compare Euclidean and DANN neighbourhoods around a point near the decision boundary.
Advanced Lecture Notes · Unsupervised Learning (Chapter 14)
Association rules, clustering, self-organising maps, principal components and curves, spectral clustering, kernel and sparse PCA, NMF, ICA, MDS and PageRank.
Demos: Spectral clustering and the graph Laplacian · PageRank and the damped random walk · Non-negative matrix factorisation of handwritten digits
In class: Cluster two rings with K-means and with spectral clustering, then compute PageRank on a small web.
Advanced Lecture Notes · Random Forests (Chapter 15)
Random forests: decorrelated trees, out-of-bag error, variable importance, proximity plots, and the analysis of variance and bias.
Demos: Random forests: the correlation-variance trade-off in m · Out-of-bag error against test error as a random forest grows · Gini against permutation importance in a random forest on the spam data
In class: Change the number of candidate split variables and watch the correlation between trees and the forest's variance trade off.
Advanced Lecture Notes · Ensemble Learning (Chapter 16)
Ensembles as penalised regression over a dictionary, forward stagewise and the lasso, the bet on sparsity, importance-sampled ensembles and rule ensembles.
Demos: Forward stagewise against the lasso: when do the paths agree? Interactive demo, TrungTin Nguyen · Bet on sparsity: the lasso against ridge as the truth gets denser · Post-processing a tree ensemble with the lasso (ISLE)
In class: Compare forward stagewise and the lasso paths, then run the bet-on-sparsity simulation.
Advanced Lecture Notes · Undirected Graphical Models (Chapter 17)
Markov graphs, Gaussian graphical models, estimation with a known graph, the graphical lasso, and Boltzmann machines.
Demos: The graphical lasso on the flow-cytometry data · Zeros of the precision matrix, not of the covariance · Fitting a Boltzmann machine: exact gradients against contrastive divergence
In class: Slide the graphical lasso penalty on the flow-cytometry data and watch edges disappear.
Advanced Lecture Notes · High-Dimensional Problems: p ≫ N (Chapter 18)
Problems with p much larger than N: diagonal LDA and nearest shrunken centroids, regularised classifiers, supervised principal components, and the false discovery rate.
Demos: Nearest shrunken centroids on the SRBCT microarray data · Ridge regression when p is much larger than N, through the N x N reduction · Supervised principal components versus principal components regression
In class: Shrink the class centroids of a microarray data set and pick the threshold by cross-validation.
Intermediate Python Code · Reproducing the Book's Figures
One module per chapter and one function per figure, reading the book's own data sets, with LARS, backfitting, boosting, the SVM path and the graphical lasso implemented directly.
In class: Ask students to change one setting (a penalty, a bandwidth, a tree size), rerun a figure and explain what changed.
Lecture notes, demonstrations and labs for an introductory course on statistical learning, following Chapters 1 to 13 of James, G., Witten, D., Hastie, T. and Tibshirani, R. (2021), An Introduction to Statistical Learning with Applications in R, 2nd edition, and its Python edition (James et al., 2023), Springer. Every lab is written in R and in Python side by side, the notes fill in the mathematics with links to the graduate statistical learning course, and thirty-eight demonstrations run the methods on the book's data. Start at the course home.
Beginner Course Home · Applied Statistical Learning in R and Python
All thirteen chapters with their demonstrations, the R and Python labs, and how to use them in class.
Beginner Lecture Notes · Introduction (Chapter 1)
The book's three motivating data sets (Wage, Smarket, NCI60), supervised and unsupervised learning, notation, and a first tour of R and Python.
Demos: Exploring the Wage data: wage against age, year and education · Up and down days on the stock market: the Smarket data
In class: Plot wage against age, year and education in R and in Python side by side, and compare the two languages' code.
Beginner Lecture Notes · Statistical Learning (Chapter 2)
What statistical learning estimates, prediction versus inference, parametric and non-parametric methods, training and test error, the bias-variance trade-off, the Bayes classifier and K-nearest neighbours.
Demos: Training and test error as flexibility grows · The bias-variance decomposition · The Bayes classifier and K-nearest neighbours
In class: Slide the flexibility of a fit and watch training error fall while test error turns up.
Beginner Lecture Notes · Linear Regression (Chapter 3)
Simple and multiple linear regression, standard errors, tests and intervals, qualitative predictors and interactions, diagnostics (leverage, outliers, collinearity), and regression against KNN.
Demos: Least squares with confidence and prediction bands on the Advertising data · Outliers and high-leverage points: drag a point · Collinearity and the variance inflation factor
In class: Drag a point to high leverage and watch the fit, the leverage statistic and the studentized residual change.
Beginner Lecture Notes · Classification (Chapter 4)
Logistic regression, linear and quadratic discriminant analysis, naive Bayes, KNN, the confusion matrix and the ROC curve, and Poisson regression as a generalized linear model.
Demos: The threshold and the ROC curve on the Default data · LDA, QDA, logistic regression and naive Bayes on simulated classes · Least squares or Poisson regression for the Bikeshare counts
In class: Move the threshold on the Default data and trace the ROC curve.
Beginner Lecture Notes · Resampling Methods (Chapter 5)
The validation set, leave-one-out and k-fold cross-validation (with the least-squares shortcut), and the bootstrap.
Demos: Validation set, LOOCV and k-fold cross-validation on the Auto data · The bootstrap on the Portfolio data: the standard error of the minimum-variance allocation · Which observations does a bootstrap sample contain? Interactive demo, TrungTin Nguyen
In class: Compare the validation-set, LOOCV and 10-fold estimates on Auto across random splits.
Intermediate Lecture Notes · Linear Model Selection and Regularization (Chapter 6)
Best subset and stepwise selection, Cp, AIC, BIC and adjusted R-squared, ridge regression and the lasso, principal components and partial least squares, and problems with p larger than n.
Demos: Ridge and lasso: thresholds, constraint regions and lambda on the Hitters data · Best subset against stepwise selection, with Cp, BIC and adjusted R-squared · Principal components regression against partial least squares
In class: Shrink the Hitters coefficients with ridge and the lasso and pick lambda by cross-validation.
Intermediate Lecture Notes · Moving Beyond Linearity (Chapter 7)
Polynomials and step functions, regression and natural splines, smoothing splines, local regression and generalized additive models.
Demos: Polynomials, step functions and splines on the Wage data, with standard-error bands · A smoothing spline on the Wage data: degrees of freedom, lambda and leave-one-out cross-validation · Backfitting a generalised additive model for wage: partial functions of year, age and education
In class: Fit polynomials, step functions and splines to Wage and compare their standard-error bands.
Intermediate Lecture Notes · Tree-Based Methods (Chapter 8)
Regression and classification trees and cost-complexity pruning, bagging, random forests, boosting and Bayesian additive regression trees.
Demos: Growing and pruning a regression tree on the Hitters data: recursive binary splitting and cost-complexity pruning · Bagging against random forests on the Heart data: test error, out-of-bag error and decorrelated trees · Boosting regression trees on the Hitters data: shrinkage, interaction depth and the number of trees
In class: Grow and prune a tree on Hitters, then compare bagging and a random forest.
Intermediate Lecture Notes · Support Vector Machines (Chapter 9)
The maximal margin classifier, the support vector classifier, kernels and the support vector machine, multiclass SVMs, and the link with logistic regression.
Demos: The budget C: from the maximal margin to the soft margin · Radial kernels on the Heart data: training and test ROC curves · Hinge loss against logistic loss: who pulls on the boundary
In class: Shrink the budget of a support vector classifier and watch the support vectors change.
Intermediate Lecture Notes · Deep Learning (Chapter 10)
Single and multilayer networks, convolutional and recurrent networks, backpropagation, stochastic gradient descent, dropout, and interpolation and double descent.
Demos: A single-hidden-layer network on the Hitters data, trained in your browser · Convolution, ReLU and max pooling on an MNIST digit · Double descent with minimum-norm natural splines
In class: Train a one-hidden-layer network on Hitters, then see double descent with the minimum-norm interpolant.
Intermediate Lecture Notes · Survival Analysis and Censored Data (Chapter 11)
Censoring, the Kaplan-Meier estimator, the log-rank test, proportional hazards and the Cox model, shrinkage for the Cox model, and measures of model performance.
Demos: Kaplan-Meier curves with censoring on the brain cancer data · The log-rank test as observed minus expected deaths · The Cox partial likelihood for one predictor
In class: Draw Kaplan-Meier curves for the brain cancer data and run the log-rank test step by step.
Intermediate Lecture Notes · Unsupervised Learning (Chapter 12)
Principal components and matrix completion, K-means and hierarchical clustering, and practical choices in clustering.
Demos: PCA of the USArrests data: scaling, units and signs · Matrix completion by iterated principal components · K-means against hierarchical clustering: nested or not
In class: Turn scaling on and off in the USArrests PCA and fill in missing values by matrix completion.
Intermediate Lecture Notes · Multiple Testing (Chapter 13)
Hypothesis tests and p-values, the family-wise error rate (Bonferroni, Holm, Tukey, Scheffe), the false discovery rate and Benjamini-Hochberg, and permutation approaches.
Demos: The family-wise error rate, Bonferroni and Holm as the number of tests grows · Benjamini-Hochberg on the Fund managers: the false discovery rate · Permutation null versus the t distribution on the Khan genes
In class: Apply Bonferroni, Holm and Benjamini-Hochberg to the fund managers' p-values.
Beginner R and Python Labs · Figure Code
Every lab written twice, in R and in Python, with the same data and the same questions, and a Python module per chapter that reproduces the book's figures.
In class: Let students choose a language for a lab, then swap with a partner and compare outputs line by line.
Lecture notes, demonstrations and code for a graduate course in probability and mathematical statistics, following Chapters 1 to 24 of Wasserman, L. (2004), All of Statistics: A Concise Course in Statistical Inference, Springer. The notes prove the results the book states without proof, every exercise has a worked solution, every derivation and exercise has graded hints, seventy-three demonstrations let students change a sample size, a prior or a bandwidth and see the effect, and Python code reproduces the book's figures. The mathematical statistics course is a gentler way in. Start at the course home.
Intermediate Course Home · Probability and Statistical Inference
All twenty-four chapters with their demonstrations, the Python code, and how to use them in class.
Intermediate Lecture Notes · Probability (Chapter 1)
Sample spaces and events, the axioms of probability, independence, conditional probability and Bayes' theorem, with the measure-theoretic background.
Demos: Bayes' theorem over a partition: base rates, priors and posteriors · Independence of events: pairwise against mutual · Long-run frequencies and the continuity of probability · The Monty Hall problem: sample spaces and conditioning
In class: Vary the base rate of a disease and watch the posterior probability of disease given a positive test.
Intermediate Lecture Notes · Random Variables (Chapter 2)
Random variables, distribution functions and quantiles, the standard discrete and continuous families, joint, marginal and conditional distributions, and transformations.
Demos: Inverse-cdf sampling: from uniforms to any distribution · Transformations of a random variable: the cdf method and the sum over preimages · The distribution of a sum: convolution
In class: Transform a random variable and compare the simulated histogram with the density from the change-of-variables formula.
Intermediate Lecture Notes · Expectation (Chapter 3)
Expectation, variance and covariance, the sample mean and variance, the multivariate normal, conditional expectation and moment generating functions.
Demos: The sample variance: dividing by n or by n − 1 · Conditional expectation and the law of total variance in a two-stage experiment · Moment generating functions and the distribution of sums
In class: Divide the sample variance by n and by n − 1 over many samples and see which one is unbiased.
Intermediate Lecture Notes · Inequalities (Chapter 4)
Markov, Chebyshev, Hoeffding, Mill's, Cauchy-Schwarz and Jensen inequalities, with full proofs and the confidence intervals they give.
Demos: Markov, Chebyshev, Hoeffding and the exact tail · Hoeffding's confidence interval for a proportion · Jensen's inequality, the nerve data and the Kullback-Leibler divergence
In class: Compare the Chebyshev and Hoeffding intervals for a proportion as the sample size grows.
Intermediate Lecture Notes · Convergence of Random Variables (Chapter 5)
Modes of convergence and the implications between them, the laws of large numbers, the central limit theorem, Berry-Esseen and the delta method.
Demos: Modes of convergence: in distribution, in probability, in L1, in quadratic mean and almost surely · How good is the normal approximation? The exact Berry-Esseen error for skewed laws · The delta method: the exact law of a transformed mean against its normal approximation
In class: Watch the standardised mean of skewed data approach the Normal, and compare its error with the Berry-Esseen bound.
Intermediate Lecture Notes · Models, Statistical Inference and Learning (Chapter 6)
Parametric and nonparametric models, point estimation, bias, variance and mean squared error, consistency, confidence sets and the language of testing.
Demos: Coverage of confidence intervals for a proportion: Wald, Wilson and Hoeffding · Bias, variance and mean squared error of shrinkage estimators · Consistency of an estimator as the sample grows
In class: Compare the coverage of the Wald, Wilson and Hoeffding intervals for a proportion as the true value moves to the edge.
Advanced Lecture Notes · Estimating the cdf and Statistical Functionals (Chapter 7)
The empirical distribution function, Glivenko-Cantelli and the DKW inequality, plug-in estimators of statistical functionals and the influence function.
Demos: The DKW confidence band: one band for the whole cdf · Plug-in estimators and their standard errors · The Glivenko-Cantelli theorem: the sup distance as n grows
In class: Draw a DKW confidence band around the empirical CDF and check how often it covers the truth.
Advanced Lecture Notes · The Bootstrap (Chapter 8)
Bootstrap variance estimation, normal, pivotal and percentile intervals, the jackknife, and when the bootstrap works.
Demos: Normal, pivotal and percentile bootstrap intervals: do they cover? Interactive demo, TrungTin Nguyen · The jackknife against the bootstrap: estimating a standard error · How many bootstrap replications? Monte Carlo error against B
In class: Bootstrap a statistic on the book's data and compare the normal, pivotal and percentile intervals.
Advanced Lecture Notes · Parametric Inference (Chapter 9)
The method of moments, maximum likelihood, consistency, asymptotic normality and efficiency of the MLE, the delta method, sufficiency, exponential families, Newton-Raphson and EM.
Demos: Fisher information and the Wald interval: the log-likelihood, its quadratic approximation and the exact coverage · Asymptotic normality and efficiency of the MLE: simulation against the Cramer-Rao bound · Computing the MLE: Newton-Raphson against the EM algorithm, for censored data and a two-Normal mixture
In class: Compare Newton-Raphson and EM on the same likelihood, step by step.
Advanced Lecture Notes · Hypothesis Testing and p-values (Chapter 10)
The Wald, likelihood ratio, chi-squared and permutation tests, p-values, the Neyman-Pearson lemma, and multiple testing.
Demos: The power function of the Wald test: size, sample size and the approximation (10.6) · The Neyman-Pearson lemma: the most powerful test of two simple hypotheses · The permutation test is exact: all splits of small samples, and its size against the Wald and t-tests
In class: Change the sample size and the alternative, and read off the power of the Wald test.
Advanced Lecture Notes · Bayesian Inference (Chapter 11)
Priors and posteriors, conjugate models, posterior simulation, Bernstein-von Mises, Jeffreys' prior, Bayes factors, and the strengths and weaknesses of the Bayesian approach.
Demos: Beta-binomial updating and the frequentist coverage of a credible interval · The Bernstein-von Mises theorem: the posterior becomes Normal · Flat priors, Jeffreys' prior and reparametrisation
In class: Change the prior and the sample size and watch the posterior concentrate around the MLE.
Advanced Lecture Notes · Statistical Decision Theory (Chapter 12)
Loss and risk, Bayes rules, minimax rules, admissibility, and Stein's paradox with the James-Stein estimator.
Demos: Risk functions, maximum risk and Bayes risk for a binomial proportion · Bayes estimators under squared, absolute and zero-one loss for a skewed posterior · Stein's paradox: the James-Stein estimator against the sample mean as the dimension grows
In class: Plot the risk functions of competing estimators and pick out the Bayes and minimax rules.
Advanced Lecture Notes · Linear and Logistic Regression (Chapter 13)
Simple and multiple linear regression, least squares and its sampling theory, prediction intervals, model selection (Cp, AIC, BIC, cross-validation) and logistic regression.
Demos: Confidence interval or prediction interval? The Palm Beach question · Cp, AIC, BIC and cross-validation on every subset of covariates · Logistic regression on the CORIS data: Newton's method, the Fisher information and backward AIC
In class: Fit a regression on the book's data and choose the model by Cp, AIC, BIC and cross-validation.
Advanced Lecture Notes · Multivariate Models (Chapter 14)
Random vectors, the multivariate normal and its estimation, the sample correlation and Fisher's z, Hotelling's T-squared, and the multinomial.
Demos: The sample correlation and Fisher's z interval · Hotelling's T-squared test against separate t-tests · Conditioning a bivariate normal on a linear combination
In class: Test a mean vector with Hotelling's T-squared and compare it with separate t-tests.
Advanced Lecture Notes · Inference About Independence (Chapter 15)
Testing and measuring dependence: the odds ratio, chi-squared tests for tables, correlation tests and the two-sample Kolmogorov-Smirnov test.
Demos: The odds ratio of a 2 x 2 table and its two confidence intervals · The chi-squared test of independence and its null distribution by simulation · The two-sample Kolmogorov-Smirnov test: exact and asymptotic p-values
In class: Run the chi-squared test of independence on a two-way table and compare it with the likelihood ratio test.
Advanced Lecture Notes · Causal Inference (Chapter 16)
Potential outcomes, association versus causation, randomisation, confounding and adjustment, and Simpson's paradox.
Demos: Potential outcomes: association against causation under random and self-selected treatment · Adjusting for a confounder: naive, stratified and regression estimates of a causal effect · Simpson's paradox: better in every group, worse overall, and which comparison is causal
In class: Tilt the confounding in Simpson's paradox until the pooled and stratified effects disagree.
Advanced Lecture Notes · Directed Graphs and Conditional Independence (Chapter 17)
Conditional independence, directed acyclic graphs and their Markov properties, d-separation, Markov equivalence, and interventions.
Demos: Conditioning versus intervening in a three-node DAG · Markov equivalence of DAGs and what data can tell apart · d-separation by the reachability (Bayes ball) algorithm, step by step
In class: Read conditional independences off a DAG by d-separation, then check them by simulation.
Advanced Lecture Notes · Undirected Graphs (Chapter 18)
Undirected graphs, the pairwise, local and global Markov properties, cliques and potentials, Hammersley-Clifford, and Gaussian graphical models.
Demos: Pairwise versus global Markov properties: when a graph's missing edges imply separation statements · Cliques, potentials and interaction terms: the Hammersley-Clifford theorem in numbers · A graph from partial correlations: exact t tests of each missing edge on the coris data
In class: Change the clique potentials of an undirected graph and see which interaction terms the Hammersley-Clifford theorem allows.
Advanced Lecture Notes · Log-Linear Models (Chapter 19)
Log-linear models for contingency tables, graphical and hierarchical models, iterative proportional fitting, and model selection.
Demos: Iterative proportional fitting, step by step: the MLE of a log-linear model · Graphical versus hierarchical log-linear models: which terms does a graph allow? Interactive demo, TrungTin Nguyen · Choosing a log-linear model: deviance, AIC and BIC across the hierarchy
In class: Fit a log-linear model by iterative proportional fitting and compare nested models by deviance.
Advanced Lecture Notes · Nonparametric Curve Estimation (Chapter 20)
Histograms, kernel density estimation and nonparametric regression: bias, variance, optimal bandwidths and rates, cross-validation and confidence bands.
Demos: Choosing the number of bins by cross-validation · Kernel regression with a confidence band · Histogram or kernel? The rates n^(-2/3) and n^(-4/5)
In class: Choose the number of histogram bins by cross-validation, then compare the histogram and kernel rates.
Advanced Lecture Notes · Smoothing Using Orthogonal Functions (Chapter 21)
Orthogonal series: the cosine basis and Legendre polynomials, series density and regression estimators, confidence bands, and Haar wavelets with thresholding.
Demos: Orthogonal series density estimation: choosing the number of terms · Orthogonal series regression and its confidence band · Haar wavelets: the multiresolution ladder and the universal threshold
In class: Change the number of cosine terms in a series estimator and threshold Haar wavelet coefficients.
Advanced Lecture Notes · Classification (Chapter 22)
The Bayes rule, linear and quadratic discriminant analysis, logistic regression, naive Bayes, trees, error-rate estimation, VC theory, support vector machines and boosting.
Demos: The Bayes rule against LDA, QDA and logistic regression · How much does the training error flatter? Union and VC bounds · The hard-margin SVM through its dual: weak duality closing in
In class: Compare LDA, QDA and logistic regression with the Bayes rule, and see how much the training error flatters.
Advanced Lecture Notes · Probability Redux: Stochastic Processes (Chapter 23)
Markov chains (classification of states, stationary distributions, convergence, reversibility, inference) and Poisson processes.
Demos: A Markov chain converging to its stationary distribution, and when it does not · Recurrence and transience of random walks in one, two and three dimensions · The Poisson process: exponential gaps, uniform order statistics, thinning and a test of homogeneity
In class: Simulate a Markov chain and watch its empirical distribution converge to the stationary distribution.
Advanced Lecture Notes · Simulation Methods (Chapter 24)
Monte Carlo integration, importance sampling, the Metropolis-Hastings algorithm, the Gibbs sampler and convergence diagnostics.
Demos: Monte Carlo integration: the error shrinks like one over root N · Importance sampling: light versus heavy tails and the effective sample size · Tuning Metropolis-Hastings: acceptance rate, autocorrelation and effective sample size
In class: Tune the proposal of a Metropolis-Hastings sampler and watch the acceptance rate and the mixing change.
Intermediate Python Code · Figure Reproduction
One module per chapter and one function per figure, reading the book's own data sets, with readable implementations of the bootstrap, EM, smoothers, iterative proportional fitting and MCMC.
In class: Ask students to change one setting (a sample size, a prior, a bandwidth, a proposal), rerun a figure and explain what changed.
Lecture notes, demonstrations and code for an advanced graduate course in nonparametric statistics, following Chapters 1 to 10 of Wasserman, L. (2006), All of Nonparametric Statistics, Springer, as a sequel to the probability and statistical inference course. The notes prove the results the book quotes from the literature, every exercise has a worked solution, thirty-one demonstrations let students change a bandwidth, a threshold or a number of basis functions and see the effect, and Python code reproduces the book's figures. Start at the course home.
Advanced Course Home · Nonparametric Statistical Inference
All ten chapters with their demonstrations, the Python code, and how to use them in class.
Advanced Lecture Notes · Introduction (Chapter 1)
What nonparametric inference means, the modes of convergence, the delta method, pointwise, uniform and finite-sample confidence sets, and the inequalities of Hoeffding, Mill, Bernstein and Berry-Esseen.
Demos: Pointwise and uniform coverage of an interval for a proportion · Tail inequalities against exact tails · The interval for a mean is not uniform: contamination
In class: Move the true proportion towards 0 and watch the Wald interval lose coverage while Hoeffding's interval keeps it.
Advanced Lecture Notes · Estimating the cdf and Statistical Functionals (Chapter 2)
The empirical cdf, Glivenko-Cantelli and the DKW band, plug-in estimators of statistical functionals, influence functions and the nonparametric delta method, and the Vapnik-Chervonenkis inequality.
Demos: Confidence bands for a cdf: DKW against Vapnik-Chervonenkis · Influence functions and the nonparametric delta method · Shattering and the VC dimension
In class: Compare the DKW and Vapnik-Chervonenkis bands on the nerve data, then shatter point sets with different classes of sets.
Advanced Lecture Notes · The Bootstrap and the Jackknife (Chapter 3)
The jackknife estimates of bias and variance, the bootstrap and the parametric bootstrap, the normal, pivotal, percentile and studentized intervals, and Edgeworth arguments for their accuracy.
Demos: The jackknife bias correction: from O(1/n) to O(1/n²) · Four bootstrap confidence intervals, and the studentized pivot · First- and second-order accuracy of bootstrap confidence bounds
In class: Compare the normal, pivotal, percentile and studentized intervals on the nerve data, then measure how often each one-sided bound misses.
Advanced Lecture Notes · Smoothing: General Concepts (Chapter 4)
The bias-variance trade-off, kernels, the choice of loss, pointwise and simultaneous confidence sets, cross-validation, and the curse of dimensionality.
Demos: The bias-variance trade-off at a point · Regressograms and kernel local averages · The curse of dimensionality
In class: Slide the bandwidth of a local average on the LIDAR data and watch the cross-validation score find the balance between bias and variance.
Advanced Lecture Notes · Nonparametric Regression (Chapter 5)
Linear smoothers, choosing the smoothing parameter, local polynomial regression, smoothing and regression splines, variance estimation, confidence bands by the tube formula, local likelihood, and additive, tree and projection pursuit models.
Demos: Local polynomial regression and cross-validation · B-splines, regression splines and smoothing splines · Confidence bands and the tube formula
In class: Fit local polynomials of degree 0, 1 and 2 to the CMB data, choose the bandwidth by cross-validation, and add a tube-formula band.
Advanced Lecture Notes · Density Estimation (Chapter 6)
Histograms and kernel density estimators: risk, optimal bandwidths and rates, cross-validation, confidence bands, local polynomials, multivariate problems, and density estimation by regression.
Demos: Histograms: cross-validation and a confidence band · Kernel density estimation: bandwidth, cross-validation and a band · Density estimation as regression on root counts
In class: Choose the number of histogram bins and the kernel bandwidth by cross-validation on the galaxy data, and add a confidence band.
Advanced Lecture Notes · Normal Means and Minimax Theory (Chapter 7)
The normal means model, Sobolev spaces, Stein's unbiased risk estimate, Pinsker's minimax theorem, James-Stein shrinkage, adaptive estimation, confidence balls and the oracle inequalities behind sparsity.
Demos: SURE and thresholding in the Normal means model · James-Stein, the linear oracle and Pinsker's bound · Pinsker's theorem on a Sobolev ellipsoid · Confidence balls for many Normal means
In class: Compare SURE thresholding, James-Stein shrinkage and Pinsker's linear minimax estimator on the same Normal means.
Advanced Lecture Notes · Nonparametric Inference Using Orthogonal Functions (Chapter 8)
Orthogonal series for regression and density estimation: the cosine basis, risk estimation and modulators, confidence balls and bands, irregular designs, and tensor products.
Demos: React: orthogonal series regression with estimated risk · The cosine basis: bias, smoothness and the boundary · Orthogonal series density estimation with react
In class: Fit the cosine series to the Doppler and CMB data, choose the number of terms by estimated risk, and draw the confidence band.
Advanced Lecture Notes · Wavelets and Other Adaptive Methods (Chapter 9)
Haar and Daubechies wavelets, multiresolution analysis, wavelet regression, hard, soft and SURE thresholding, Besov spaces, confidence sets, and other adaptive methods such as intersecting confidence intervals.
Demos: Wavelet thresholding: VisuShrink, SureShrink and the blocks function · Sparsity: keeping the largest wavelet coefficients · Intersecting confidence intervals: a local bandwidth for every x
In class: Threshold the wavelet coefficients of the blocks and Doppler functions and compare VisuShrink with SureShrink.
Advanced Lecture Notes · Other Topics (Chapter 10)
Measurement error and SIMEX, deconvolution and inverse problems, the Dirichlet process, semiparametric inference, correlated errors, classification, sieves, shape-restricted inference, testing and computation.
Demos: SIMEX and attenuation bias · Deconvolving a density · Isotonic regression and pool-adjacent-violators
In class: Watch measurement error flatten a regression slope, then undo it by SIMEX, and fit a monotone curve by pool-adjacent-violators.
Advanced Python Code · Figure Reproduction
One module per chapter and one function per figure, reading the book's own data sets, with readable implementations of the bootstrap, smoothers, kernel density estimators, SURE and wavelet thresholding.
In class: Ask students to change one setting (a bandwidth, a number of basis functions, a threshold), rerun a figure and explain what changed.
Lecture notes, demonstrations and code for a graduate course in machine learning from a probabilistic point of view, following Chapters 1 to 23 of Murphy, K. P. (2022), Probabilistic Machine Learning: An Introduction, MIT Press: foundations, linear models, deep networks, kernels and trees, and learning beyond supervision. The notes fill in the derivations the book leaves out, every exercise has a worked solution, seventy-nine demonstrations let students change a prior, a learning rate, a kernel width or a number of clusters and see the effect, and Python code reproduces the book's figures. Start at the course home.
Intermediate Course Home · Probabilistic Machine Learning: An Introduction
All twenty-three chapters with their demonstrations, the Python code, and how to use them in class.
Intermediate Lecture Notes · Introduction (Chapter 1)
What machine learning is: supervised, unsupervised and reinforcement learning, overfitting and generalisation, the no-free-lunch theorem, and preprocessing of discrete, text and missing data.
Demos: Polynomial regression: under- and over-fitting · Iris decision trees: empirical risk and loss matrices · Missing data: MCAR, MAR, NMAR and imputation
In class: Raise the polynomial degree until the test error turns up, then add data and watch the turning point move.
Intermediate Lecture Notes · Probability: Univariate Models (Chapter 2)
Probability as a calculus of uncertainty: Bayes' rule, the Bernoulli, binomial, categorical, Gaussian, Student, Laplace, beta and gamma families, transformations of random variables and the central limit theorem.
Demos: Bayes' rule for a diagnostic test: prevalence, sensitivity and specificity · The Monty Hall problem: simulation against Bayes' rule · Sums of random variables: convolution and the central limit theorem · Heavy tails and robustness: Gaussian, Student and Laplace fits
In class: Ask the class to guess the posterior after a positive test, then reveal it and vary the base rate.
Intermediate Lecture Notes · Probability: Multivariate Models (Chapter 3)
Joint distributions, covariance and correlation, Simpson's paradox, the multivariate Gaussian with its conditionals and Bayes rule, mixture models, the exponential family and directed graphical models.
Demos: The bivariate Gaussian: marginals and conditionals · Bayes rule for Gaussians: noisy points and sensor fusion · The water sprinkler network: inference and explaining away · Correlation and Simpson's paradox on the iris data
In class: Condition a two-dimensional Gaussian on one coordinate and predict the new mean and variance before showing them.
Intermediate Lecture Notes · Statistics (Chapter 4)
Maximum likelihood, empirical risk minimisation, regularisation and cross-validation, Bayesian inference with conjugate priors, credible intervals, the Laplace approximation, and the frequentist view through the bootstrap and bias-variance trade-off.
Demos: The beta-binomial model: prior, posterior, predictive · Ridge regression and cross-validation · Bootstrap, posterior and confidence intervals for a proportion
In class: Compare a bootstrap distribution with a Bayesian posterior for the same data and discuss when they agree.
Intermediate Lecture Notes · Decision Theory (Chapter 5)
Bayesian decision theory, ROC and precision-recall curves, Bayesian model comparison with Bayes factors, BIC, AIC and WAIC, frequentist risk and admissibility, empirical risk minimisation and hypothesis testing.
Demos: Thresholds, costs, ROC and precision-recall curves · Risk functions of estimators: Bayes, minimax and Stein's paradox · Bayes factors, BIC and p-values for a coin
In class: Move the decision threshold on an ROC curve under different costs and find the Bayes-optimal point.
Intermediate Lecture Notes · Information Theory (Chapter 6)
Entropy, cross entropy, KL divergence and mutual information, their inequalities and chain rules, the data processing inequality, Fano's inequality, and the maximal information coefficient.
Demos: Entropy, cross entropy, KL divergence and perplexity · Forward versus reverse KL: mode covering and mode seeking · Joint, conditional entropy and mutual information of a table · Correlation versus binned mutual information
In class: Fit one Gaussian to a bimodal target by forward and by reverse KL and explain the two very different answers.
Advanced Lecture Notes · Linear Algebra (Chapter 7)
Vector spaces, norms, matrix properties, eigenvalue and singular value decompositions, the power method, whitening, LU, QR and Cholesky factorisations, least squares, and matrix calculus.
Demos: Eigenvectors, quadratic forms and the power method · Standardising and whitening data: PCA and ZCA · Truncated SVD: low-rank approximation of an image
In class: Compress an image with a truncated SVD and predict the error from the discarded singular values.
Advanced Lecture Notes · Optimization (Chapter 8)
First- and second-order optimisation: convexity, gradient descent and line search, momentum, Newton and quasi-Newton methods, stochastic gradient methods with variance reduction and Adam, constrained and proximal optimisation, and EM.
Demos: Line search, Newton, BFGS and trust regions · SGD, iterate averaging and variance reduction · KKT multipliers, projections and proximal steps
In class: Race gradient descent, momentum, Newton and BFGS on the same function from the same start.
Intermediate Lecture Notes · Linear Discriminant Analysis (Chapter 9)
Gaussian discriminant analysis, linear and quadratic decision boundaries, Fisher's linear discriminant, naive Bayes classifiers, and the generative versus discriminative comparison.
Demos: Gaussian discriminant analysis: LDA, QDA and naive Bayes boundaries · Fisher's linear discriminant against PCA · Naive Bayes on handwritten digits
In class: Switch between tied and separate covariances and watch the boundary change from a line to a curve.
Intermediate Lecture Notes · Logistic Regression (Chapter 10)
Binary and multinomial logistic regression, their convex losses, gradient, Newton and IRLS fitting, regularisation, robust variants, and Bayesian logistic regression with the Laplace approximation.
Demos: Fitting logistic regression: gradient descent, bound optimisation and Newton · Bayesian logistic regression: the Laplace approximation and the probit predictive · Robust logistic regression: mixture likelihood and the bi-tempered loss
In class: Fit logistic regression with gradient descent and with Newton steps and count the iterations each needs.
Intermediate Lecture Notes · Linear Regression (Chapter 11)
Least squares and its geometry, ridge, lasso, elastic net and group lasso, the lasso path and coordinate descent, splines and additive models, robust regression, and Bayesian linear regression.
Demos: Shrinkage and sparsity: ridge, lasso and subset selection · Regularisation paths on the prostate data: ridge, lasso and elastic net · Sequential Bayesian linear regression · Robust linear regression
In class: Trace the lasso path on the prostate data and name the order in which variables enter.
Intermediate Lecture Notes · Generalized Linear Models (Chapter 12)
Generalized linear models: the exponential dispersion family, canonical and non-canonical links, maximum likelihood by IRLS, deviance, and Poisson regression for claim counts.
Demos: Fitting a GLM: IRLS against gradient descent · Link functions for binary data · Predicting insurance claims: ridge against Poisson regression
In class: Fit the same binary data with logit, probit and complementary log-log links and compare the tails.
Advanced Lecture Notes · Neural Networks for Tabular Data (Chapter 13)
Multilayer perceptrons for tabular data: universal approximation, backpropagation and automatic differentiation, vanishing gradients, initialisation, regularisation, double descent, RBF networks and mixtures of experts.
Demos: A multilayer perceptron on two-dimensional data: depth, activations and weight decay · Vanishing and exploding gradients: depth, activation, initialisation and residual connections · Automatic differentiation on a computation graph: forward and reverse mode · Radial basis function networks: bandwidth, centres and ridge penalty
In class: Train a small network on the XOR data with one hidden layer, then make it wider and deeper.
Advanced Lecture Notes · Neural Networks for Images (Chapter 14)
Convolutional networks: convolution as a structured matrix, pooling, normalisation layers, classic architectures, residual and dense networks, segmentation, detection, and generating images by inverting a trained network.
Demos: Convolution as a matrix: padding, stride, dilation and the transposed layer · Batch, layer, instance and group normalisation: which activations share statistics · Inverting a CNN: images that a classifier believes, with Gaussian and total-variation priors
In class: Write a convolution as a matrix and check that it commutes with shifts but not with rotations.
Advanced Lecture Notes · Neural Networks for Sequences (Chapter 15)
Recurrent networks, backpropagation through time, gated units, decoding by greedy and beam search, one-dimensional convolutions, attention, transformers, positional encodings, efficient attention and pretrained language models.
Demos: Gradient flow in recurrent cells: vanishing, exploding and gated · Decoding a character-level GRU: greedy, temperature and beam search · Kernel regression as attention: bandwidth and the leave-one-out score · Positional encoding and attention scores
In class: Decode the same character model greedily and by beam search and compare likelihood and diversity.
Intermediate Lecture Notes · Exemplar-based Methods (Chapter 16)
Nearest-neighbour classification and its error, the curse of dimensionality, metric learning (LMNN, NCA, deep metric learning), and kernel density estimation and kernel regression.
Demos: K nearest neighbour decision regions and the choice of K · The curse of dimensionality for nearest neighbours · Learning a Mahalanobis metric by neighbourhood components analysis · Kernel density estimation and kernel regression
In class: Increase the dimension and watch nearest-neighbour distances concentrate.
Advanced Lecture Notes · Kernel Methods (Chapter 17)
Mercer kernels, Gaussian processes for regression and classification, marginal likelihood, scalable approximations and random features, support vector machines for classification and regression, and sparse vector machines.
Demos: Gaussian process regression: the marginal likelihood surface · Support vector machines: the kernel width and the regulariser C · Random Fourier features: approximating a kernel with a few random features
In class: Climb the marginal likelihood surface of a Gaussian process and compare the two local optima.
Intermediate Lecture Notes · Trees, Forests, Bagging, and Boosting (Chapter 18)
Classification and regression trees, ensembles, bagging and random forests, boosting from AdaBoost to gradient boosting and XGBoost, and interpreting tree ensembles.
Demos: Growing a classification tree greedily: splits, impurity and instability · Bagging and random forests on two moons: averaging unstable trees · AdaBoost with decision stumps: reweighting the data · Gradient boosting of regression trees: residuals, shrinkage, losses and XGBoost
In class: Grow one deep tree, then a bagged forest, and compare how much they change from sample to sample.
Advanced Lecture Notes · Learning with Fewer Labeled Examples (Chapter 19)
Data augmentation, transfer learning and adapters, contrastive pretraining, semi-supervised learning, active learning with information gain and BALD, meta-learning, few-shot learning and weak supervision.
Demos: Semi-supervised learning from a few labels · Active learning with BALD · Few-shot regression with MAML
In class: Add unlabelled points to a two-class problem and watch label propagation fill in the gaps.
Advanced Lecture Notes · Dimensionality Reduction (Chapter 20)
PCA and its probabilistic and factor-analysis versions, autoencoders and variational autoencoders, manifold learning (MDS, Isomap, kernel PCA, LLE, Laplacian eigenmaps, t-SNE), and word embeddings.
Demos: PCA reconstruction error, scree plot and profile likelihood · EM for PCA and probabilistic PCA: the rod and the springs · t-SNE: perplexity, early exaggeration and the crowding problem · Isomap on a Swiss roll: the neighbourhood size and short circuits
In class: Change the perplexity of t-SNE and discuss what the clusters on the screen do and do not mean.
Intermediate Lecture Notes · Clustering (Chapter 21)
Measuring cluster quality, hierarchical agglomerative clustering, K-means and K-means++, choosing the number of clusters, mixture-model clustering, spectral clustering and biclustering.
Demos: K-means, local minima and K-means++ seeding · Choosing the number of clusters: distortion, silhouette and BIC · Hierarchical clustering: single, complete and average link
In class: Run K-means from several starts and compare random and K-means++ initialisation.
Intermediate Lecture Notes · Recommender Systems (Chapter 22)
Explicit and implicit feedback, matrix factorisation by ALS and SGD, probabilistic matrix factorisation, Bayesian personalised ranking, factorisation machines, cold start, and bandit exploration.
Demos: Matrix factorisation for recommendation by alternating least squares · Bayesian personalised ranking from implicit feedback · The exploration-exploitation trade-off in a recommender
In class: Factorise a ratings matrix by alternating least squares and watch the test error as the rank grows.
Advanced Lecture Notes · Graph Embeddings (Chapter 23)
Shallow graph embeddings from distances, matrix factorisation and random walks, label propagation, graph neural networks and graph convolutions, hyperbolic embeddings and unsupervised graph learning.
Demos: Shallow graph embeddings of the karate-club network · Label propagation and label spreading on a nearest-neighbour graph · Graph convolution as feature smoothing, and over-smoothing · Embedding a tree in the Poincare disk and in the Euclidean plane
In class: Smooth node features with repeated graph convolutions until every node looks the same.
Intermediate Python Code · Figure Reproduction
One module per chapter and one function per figure, with readable implementations of EM, gradient and Newton methods, backpropagation, Gaussian processes, support vector machines, boosting, PCA, t-SNE and matrix factorisation.
In class: Ask students to change one setting (a learning rate, a regularisation strength, a kernel width, a number of clusters), rerun a figure and explain what changed.
Lecture notes, demonstrations and code for a research-level course in probabilistic machine learning, following Chapters 1 to 36 and the online supplement of Murphy, K. P. (2023), Probabilistic Machine Learning: Advanced Topics, MIT Press: foundations, exact and approximate inference, Bayesian prediction, deep generative models, discovery of latent structure, and decision making and causality. The notes fill in the derivations the book leaves out, every chapter has practice problems with worked solutions, every derivation and problem has graded hints, ninety-six demonstrations let students change a proposal, a number of particles, a noise schedule or a prior and see the effect, and Python code reproduces the book's figures. Start at the course home.
Advanced Course Home · Probabilistic Machine Learning: Advanced Topics
All thirty-six chapters with their demonstrations, the Python code, and how to use them in class.
Advanced Lecture Notes · Introduction (Chapter 1)
Why a model-based approach to machine learning, inference as inverting a generative process, and the four kinds of task (prediction, generation, discovery, action) that organise the book.
In class: Ask what it would mean to invert a simulator, then read the four kinds of task off one generative model.
Advanced Lecture Notes · Probability (Chapter 2)
The distributions the book relies on, Gaussian joint distributions and Gaussian conditioning, the exponential family and its moment and cumulant identities, change of variables, Markov chains, and divergence measures between distributions.
Demos: Sensor fusion with unknown noise: plug-in against exact posterior · Fitting a Gaussian by alpha divergence: mode seeking to mass covering · Markov chains, stationary distributions and PageRank
In class: Fuse two sensors with unknown noise and compare the plug-in answer with the exact posterior as data arrive.
Advanced Lecture Notes · Statistics (Chapter 3)
Bayesian and frequentist statistics side by side: conjugate, noninformative and hierarchical priors, empirical Bayes, model selection and checking, Bayesian hypothesis testing, and inference with missing data.
Demos: Hierarchical models and shrinkage: eight schools and rat tumours · Jeffreys priors and reparameterisation · Model selection for polynomial regression: evidence, BIC, AIC, LOO, WAIC
In class: Shrink the eight schools estimates towards the group mean and ask which schools move most, and why.
Advanced Lecture Notes · Graphical models (Chapter 4)
Directed and undirected graphical models, conditional independence and d-separation, Markov random fields and conditional random fields, the comparison of the two, and structural causal models.
Demos: Inference and d-separation in a Bayes net · Gaussian Bayes nets and Gaussian MRFs: sparse precision, dense covariance · Ising and Potts models: Gibbs sampling, phase transition and mean-field denoising
In class: Read off a conditional independence by d-separation, then confirm it by changing the evidence in the demo.
Advanced Lecture Notes · Information theory (Chapter 5)
KL divergence, entropy and mutual information, source coding and channel coding, the information bottleneck, and algorithmic information theory.
Demos: Diagonal Gaussian approximations of a correlated Gaussian · Variational bounds on mutual information · The information bottleneck on word-class counts
In class: Fit a diagonal Gaussian to a correlated one with each KL direction and ask which one underestimates the variance.
Advanced Lecture Notes · Optimization (Chapter 6)
Automatic differentiation, stochastic and natural gradient methods, the Bayesian learning rule, bound optimisation and EM, Bayesian optimisation, derivative-free search, conjugate duality, proximal methods, dynamic programming and optimal transport.
Demos: Natural gradient against steepest descent · Bayesian optimisation: surrogate and acquisition functions · Optimal transport and the Sinkhorn algorithm
In class: Race natural gradient against steepest descent on a badly scaled problem and explain the difference in paths.
Advanced Lecture Notes · Inference algorithms: an overview (Chapter 7)
A map of the inference algorithms in Part II: common inference patterns, exact versus approximate methods, and how to evaluate an approximate posterior.
Demos: Approximating a posterior: grid, Laplace, variational, MCMC
In class: Approximate one posterior four ways (grid, Laplace, variational, MCMC) and rank them before revealing the truth.
Advanced Lecture Notes · Gaussian filtering and smoothing (Chapter 8)
The Kalman filter and smoother, the extended and unscented Kalman filters, assumed density filtering and other Gaussian approximations for state-space models.
Demos: Kalman filter, RTS smoother and fixed-lag smoothing · Passing a Gaussian through a nonlinear map: Taylor, unscented and Gauss-Hermite · Online Bayesian logistic regression: assumed density filtering and the EKF
In class: Track a moving object with the Kalman filter, then smooth it and ask where the uncertainty band shrinks most.
Advanced Lecture Notes · Message passing algorithms (Chapter 9)
Belief propagation on chains and trees, loopy belief propagation, variable elimination, the junction tree algorithm, inference as optimisation, and MAP estimation for discrete graphical models.
Demos: Forwards-backwards and Viterbi in the dishonest casino · Loopy belief propagation on an Ising grid: damping and schedules · Variable elimination: orders, fill-in and junction trees
In class: Decode the dishonest casino with forwards-backwards and Viterbi and find a roll where the two disagree.
Advanced Lecture Notes · Variational inference (Chapter 10)
Variational inference: the evidence lower bound, gradient-based and coordinate ascent VI, richer variational families, tighter bounds, the wake-sleep algorithm and expectation propagation.
Demos: Mean-field Ising denoising · ELBO, IWAE bound and EUBO · Expectation propagation for a logistic model
In class: Compare the ELBO, IWAE and EUBO as the number of samples grows and ask which bound closes the gap.
Advanced Lecture Notes · Monte Carlo methods (Chapter 11)
Monte Carlo integration, sampling from simple distributions, rejection and importance sampling, and the main techniques for reducing Monte Carlo variance.
Demos: Rejection sampling: the gamma example and the curse of dimension · Importance sampling: weights, effective sample size and the choice of proposal · Variance reduction for Monte Carlo: control variates, antithetic draws, randomised QMC
In class: Push rejection sampling up in dimension and predict when the acceptance rate collapses.
Advanced Lecture Notes · Markov chain Monte Carlo (Chapter 12)
Markov chain Monte Carlo: Metropolis-Hastings, Gibbs sampling, auxiliary-variable methods, Hamiltonian Monte Carlo, convergence diagnostics, stochastic-gradient MCMC, reversible jump and annealing.
Demos: Metropolis-Hastings proposals, Gibbs sampling and convergence diagnostics · Hamiltonian Monte Carlo: step size, trajectory length and geometry · Gibbs sampling against Swendsen-Wang on the Ising model
In class: Tune the HMC step size and trajectory length until the acceptance rate and the effective sample size both look good.
Advanced Lecture Notes · Sequential Monte Carlo (Chapter 13)
Sequential Monte Carlo: particle filtering, resampling, proposal distributions, Rao-Blackwellised particle filters, SMC samplers and particle MCMC.
Demos: The bootstrap particle filter: weights, resampling and the evidence · SMC with adaptive tempering on a bimodal target · Resampling schemes: multinomial, stratified, systematic
In class: Run the particle filter with too few particles, watch the weights degenerate, then turn resampling on.
Advanced Lecture Notes · Predictive models: an overview (Chapter 14)
How predictive models are evaluated: proper scoring rules, calibration, and distribution-free uncertainty through conformal prediction.
In class: Wrap a weak regressor in split conformal prediction and check the coverage holds anyway.
Advanced Lecture Notes · Generalized linear models (Chapter 15)
Bayesian generalized linear models: linear, logistic and probit regression with conjugate, Laplace and variational posteriors, and multilevel (hierarchical) GLMs.
Demos: Priors on the logit scale · Bayesian logistic regression: Laplace posterior and predictive · Automatic relevancy determination against ridge and lasso
In class: Put a wide Gaussian prior on a logit and ask the class what it implies for the probability scale.
Advanced Lecture Notes · Deep neural networks (Chapter 16)
The building blocks of deep networks as differentiable circuits (layers, normalisation, attention) and the canonical architectures built from them.
Demos: Attention as soft kernel regression · A neural network with a mean head and a variance head · Message passing on graphs: receptive field and over-smoothing
In class: Read attention as kernel regression: shrink the temperature and watch the output snap to the nearest key.
Advanced Lecture Notes · Bayesian neural networks (Chapter 17)
Bayesian neural networks: priors over functions, posterior approximation by Laplace, variational, ensemble and MCMC methods, generalisation, online inference and hierarchical BNNs.
Demos: Priors over functions for a neural network · Approximate posteriors of a neural network against HMC · Bayesian model averaging under a shift the data never explored
In class: Compare approximate posteriors of a small network with HMC, then move the test input outside the data.
Advanced Lecture Notes · Gaussian processes (Chapter 18)
Gaussian processes: Mercer kernels, exact regression, non-Gaussian likelihoods, sparse and scalable approximations, kernel learning, the link with deep networks, and GPs for time series.
Demos: Building kernels: sums, products and random features · Sparse Gaussian processes with inducing points · Forecasting atmospheric CO2 with a sum of kernels
In class: Build a kernel from sums and products, predict what the samples will look like, then draw them.
Advanced Lecture Notes · Beyond the iid assumption (Chapter 19)
Learning when training and test data differ: covariate, label and concept shift, detecting and adapting to shift, multi-task and continual learning, and adversarial examples.
Demos: Covariate shift: importance weights and the choice of model · Label shift: blackbox shift estimation and the prior correction · Adversarial examples: why small perturbations suffice in high dimension
In class: Shift the inputs between training and test and decide whether importance weighting helps this model.
Advanced Lecture Notes · Generative models: an overview (Chapter 20)
A map of deep generative models: the main families, what generative modelling is for, and how sample quality and likelihood are evaluated.
Demos: Judging a generative model: likelihood, FID, precision and recall
In class: Score two generative models by likelihood, FID, precision and recall and ask why the rankings disagree.
Advanced Lecture Notes · Variational autoencoders (Chapter 21)
Variational autoencoders: the amortised ELBO and reparameterisation trick, generalisations, posterior collapse, hierarchical VAEs and vector-quantised VAEs.
Demos: Reverse water-filling in a linear beta-VAE · A two-dimensional VAE latent space on MNIST · The VQ-VAE codebook and its moving-average update
In class: Raise beta in a linear beta-VAE and predict which latent directions switch off first.
Advanced Lecture Notes · Autoregressive models (Chapter 22)
Autoregressive models: NADE and MADE, causal convolutions, transformers and large language models.
Demos: How much context does an autoregressive model need? · Masks of a MADE network · Receptive fields of causal convolutions and the PixelCNN blind spot
In class: Change the context length of an autoregressive model and find where extra context stops helping.
Advanced Lecture Notes · Normalizing flows (Chapter 23)
Normalizing flows: the change-of-variables formula, coupling, autoregressive, residual and continuous-time flows, and their applications.
Demos: Scalar bijections and the densities they induce · Autoregressive flows on a cross-shaped density · Planar flows and when they stop being invertible
In class: Compose scalar bijections, predict the density they induce, then check it against the histogram.
Advanced Lecture Notes · Energy-based models (Chapter 24)
Energy-based models: maximum likelihood with MCMC, contrastive divergence, score matching, noise contrastive estimation and related training methods.
Demos: Fitting an energy-based model without its partition function · Product of experts and Langevin sampling · Contrastive divergence on a restricted Boltzmann machine you can enumerate
In class: Sample from a product of experts with Langevin dynamics and vary the step size until the samples look right.
Advanced Lecture Notes · Diffusion models (Chapter 25)
Diffusion models: denoising diffusion, score-based models, the stochastic and probability-flow differential equations, faster samplers, guided conditional generation and discrete diffusion.
Demos: Reverse diffusion samplers with an exact score · Classifier-free guidance: quality against diversity · Discrete diffusion: the transition kernels of D3PM
In class: Run a reverse diffusion sampler with the exact score and compare the stochastic and deterministic samplers.
Advanced Lecture Notes · Generative adversarial networks (Chapter 26)
Generative adversarial networks: learning by comparing distributions, divergences and integral probability metrics, training dynamics and mode collapse, conditional GANs and inference with GANs.
Demos: Learning by comparison: divergences, distances and critics · DiracGAN: gradient descent on a two-player game · Training a GAN on sixteen Gaussians: mode collapse and its remedies
In class: Train the DiracGAN with simultaneous gradient steps, watch it spiral, then add regularisation.
Advanced Lecture Notes · Discovery methods: an overview (Chapter 27)
A map of Part V, discovery methods: latent variable models, structure learning and representation learning, and what it means to discover structure in data.
In class: Ask what counts as discovering structure, then map each later chapter to the kind of structure it finds.
Advanced Lecture Notes · Latent factor models (Chapter 28)
Latent factor models: mixtures, factor analysis and probabilistic PCA, sparse and non-Gaussian priors, topic models and independent component analysis.
Demos: Gaussian scale mixtures and their shrinkage rules · ICA and the rotation angle · Collapsed Gibbs sampling for LDA
In class: Rotate the ICA mixing angle and ask why a Gaussian source would make the angle unidentifiable.
Advanced Lecture Notes · State-space models (Chapter 29)
State-space models: hidden Markov models and their learning, linear dynamical systems, switching and nonlinear models, changepoint detection and structural time series.
Demos: Baum-Welch (EM) for a hidden Markov model · Bayesian online changepoint detection · Structural time series: trend, season and forecast
In class: Run Bayesian online changepoint detection on a series and ask what the hazard rate controls.
Advanced Lecture Notes · Graph learning (Chapter 30)
Graph learning: latent variable models for networks (block models, relational models), and learning graphical model structure from data, from Chow-Liu trees to the PC algorithm and NOTEARS.
Demos: The graphical lasso path · The PC algorithm and Markov equivalence · Which way does the arrow point?
In class: Run the PC algorithm on a small graph, then flip an edge and ask whether the data could tell.
Advanced Lecture Notes · Nonparametric Bayesian models (Chapter 31)
Nonparametric Bayes: the Dirichlet process and its mixtures, Pitman-Yor and hierarchical processes, the Indian buffet and beta processes, completely random measures, and point processes.
Demos: The Chinese restaurant and Pitman-Yor processes · DP-means clustering · Hawkes processes
In class: Seat customers in the Chinese restaurant, vary the concentration and discount, and predict the number of tables.
Advanced Lecture Notes · Representation learning (Chapter 32)
Representation learning: comparing representations with CKA and CCA, autoencoding and contrastive objectives, InfoNCE, non-contrastive methods, and identifiability theory.
Demos: Comparing two representations: CKA and CCA · The InfoNCE bound, negatives and temperature · Why BYOL and SimSiam need not collapse
In class: Compare two representations with CKA and CCA and ask why the two scores can disagree.
Advanced Lecture Notes · Interpretability (Chapter 33)
Interpretability: inherently interpretable models, local surrogates, attributions and Shapley values, sanity checks and evaluation of explanations, and user studies.
Demos: When two explanations disagree about the same model · A local linear explanation: fidelity against locality · Designing a user study of explanations: power, matching and multiple comparisons
In class: Explain the same model two ways, find a case where the explanations disagree, and ask which is right.
Advanced Lecture Notes · Decision making under uncertainty (Chapter 34)
Decision making under uncertainty: Bayesian decision theory, influence diagrams, A/B testing, contextual bandits, Markov decision processes and active learning.
Demos: A/B test: the optimal test size · Bandits: regret of greedy, UCB and Thompson sampling · MDPs: value iteration and policy iteration on a grid world
In class: Size an A/B test to maximise expected reward, then compare greedy, UCB and Thompson sampling on regret.
Advanced Lecture Notes · Reinforcement learning (Chapter 35)
Reinforcement learning: exploration, temporal-difference learning, Q-learning and maximisation bias, policy gradients with baselines, actor-critic and trust-region methods, model-based RL, off-policy evaluation and the deadly triad, and control as inference.
Demos: Q-learning and double Q-learning: the maximisation bias · REINFORCE with and without a baseline · Off-policy evaluation and the curse of horizon · Baird's counterexample and the deadly triad
In class: Show the maximisation bias of Q-learning, fix it with double Q-learning, then add a baseline to REINFORCE and watch the gradient variance fall.
Advanced Lecture Notes · Causality (Chapter 36)
Causality: potential outcomes and graph surgery, randomised trials, confounder adjustment with inverse weighting and double machine learning, instrumental variables and the LATE, difference in differences, sensitivity analysis with Austen plots, and the do-calculus.
Demos: Adjusting for confounders · Instruments and the local average treatment effect · Austen plots: how strong must a hidden confounder be?
In class: Estimate a treatment effect with and without adjusting for a confounder, then use an Austen plot to ask how strong an unobserved confounder would have to be to explain it away.
Advanced Python Code · Probabilistic Machine Learning: Advanced Topics
One module per chapter and one function per figure, with readable implementations of the inference algorithms and generative models in the book.
Lecture notes, demonstrations and code for an undergraduate course in mathematical statistics, following Chapters 1 to 14 of Larsen, R. J. and Marx, M. L. (2018), An Introduction to Mathematical Statistics and Its Applications, 6th edition, Pearson, built on the book's case studies with real data: the step between the first-year course and the graduate course in probability and statistical inference. The notes fill in the steps the book skips, a representative selection of its questions has worked solutions, every derivation and question has graded hints, twenty-eight demonstrations let students change a sample size, a parameter or a significance level and see the effect, and Python code reproduces the book's figures. Start at the course home.
Intermediate Course Home · Introduction to Mathematical Statistics
All fourteen chapters with their demonstrations, the Python code, and how to use them in class.
Intermediate Lecture Notes · Introduction: Lecture Notes (Chapter 1)
What statistics is for, through the book's motivating examples (full moons, earthquakes, estimating a fleet from serial numbers) and a short history from games of chance to modern inference.
Demos: The German tank problem: estimating a total from captured serial numbers
In class: Estimate the number of tanks from four serial numbers, then compare two estimators by repeating the experiment in the demo.
Intermediate Lecture Notes · Probability (Chapter 2)
Sample spaces and the algebra of sets, the axioms of probability, conditional probability and Bayes' rule, independence, counting, combinatorial probability and Monte Carlo.
Demos: The birthday problem: coincidences, exact and simulated · Combinatorial probability: poker hands and lottery prizes · Inclusion-exclusion and the matching problem: partial sums and Bonferroni bounds
In class: Ask the class to guess how many people make a shared birthday likely, then run the birthday demo.
Intermediate Lecture Notes · Random Variables: Lecture Notes (Chapter 3)
Discrete and continuous random variables, expectation and variance, joint and conditional densities, transformations, order statistics and moment-generating functions.
Demos: Sampling without and with replacement: hypergeometric against binomial · Joint, marginal and conditional densities: slicing a joint pdf · Order statistics: the density of the i-th smallest of n observations
In class: Predict the shape of the largest of five uniforms, then check it against the order-statistics demo.
Intermediate Lecture Notes · Special Distributions: Lecture Notes (Chapter 4)
The Poisson, normal, geometric, negative binomial and gamma distributions, the Poisson limit, the central limit theorem with a full proof, and simulation.
Demos: Rare events: the binomial law becomes the Poisson law · Normal approximation to the binomial and the continuity correction · Monte Carlo: should you buy the warranty?
In class: Watch the binomial turn into a Poisson as n grows and p shrinks, and ask when the approximation is good enough.
Intermediate Lecture Notes · Estimation: Lecture Notes (Chapter 5)
Maximum likelihood and the method of moments, confidence intervals, unbiasedness and efficiency, the Cramer-Rao bound, sufficiency, consistency and Bayesian estimation.
Demos: Which unbiased estimator? Variance, relative efficiency and the Cramer-Rao bound · What does a statistic remember? Sufficiency by conditioning · Prior plus data: conjugate updating and Bayes estimates
In class: Give two unbiased estimators of the same parameter and let the class decide which is better before simulating them.
Intermediate Lecture Notes · Hypothesis Testing: Lecture Notes (Chapter 6)
Decision rules, P-values, testing binomial data, Type I and II errors and power, the generalized likelihood ratio, and statistical versus practical significance.
Demos: The generalized likelihood ratio test for a uniform upper limit · Statistical versus practical significance: the gas-mileage test with any sample size
In class: Set a decision rule for a coin, then trade Type I against Type II error by moving the cut-off.
Intermediate Lecture Notes · Inferences Based on the Normal Distribution: Lecture Notes (Chapter 7)
Why S replaces sigma and the t distribution appears, the chi-squared and F laws, intervals and tests for a normal mean and variance, robustness, and power.
Demos: How robust is the t test? · Inference about a variance: cut-offs, width and power
In class: Run the t test on skewed data with small n and ask whether the 5% level still holds.
Intermediate Lecture Notes · Types of Data: A Brief Overview: Lecture Notes (Chapter 8)
A map of experimental designs (one, two and k samples, paired data, randomized blocks, regression, categorical data) and which analysis each calls for.
In class: Classify five case studies by design before analysing any of them, and argue about the borderline ones.
Intermediate Lecture Notes · Two-Sample Inferences: Lecture Notes (Chapter 9)
Comparing two groups: pooled and Welch t tests, the F test for variances and why it is fragile, two proportions, intervals for differences, and random assignment.
Demos: The F test for equal variances: sharp for normal data, fragile otherwise · Choosing samples: random assignment versus reaching in and grabbing
In class: Compare pooled and Welch tests when the variances differ, and see why testing the variances first is a bad idea.
Intermediate Lecture Notes · Goodness-of-Fit Tests: Lecture Notes (Chapter 10)
The multinomial distribution, Pearson's chi-squared test and why it has k - 1 degrees of freedom, estimated parameters, contingency tables and outliers.
Demos: Why Pearson's statistic has t − 1 degrees of freedom · Goodness of fit with estimated parameters: what each estimate costs
In class: Test Mendel's peas for goodness of fit, then ask whether data can fit a model too well.
Intermediate Lecture Notes · Regression: Lecture Notes (Chapter 11)
Least squares and residuals, the simple linear model with exact inference for slope, intercept, variance, means and predictions, correlation, and the bivariate normal.
Demos: Least squares, residuals and what r hides · The sampling distribution of the least squares estimates
In class: Fit a line by eye, then by least squares, and read the residual plot for what the line misses.
Intermediate Lecture Notes · The Analysis of Variance: Lecture Notes (Chapter 12)
One-way analysis of variance: the F test and its exact laws, noncentral F and power, Tukey's multiple comparisons, contrasts and Scheffe, and transformations.
Demos: The F test and its power: the central and the noncentral F law · Many tests, one error rate: Tukey's method for all pairwise comparisons
In class: Run all pairwise t tests on five equal groups and count the false alarms; then switch to Tukey.
Intermediate Lecture Notes · Randomized Block Designs: Lecture Notes (Chapter 13)
Randomized block designs: the block F test, the paired t test as its two-treatment case, contrasts, and when blocking or pairing pays off.
Demos: Blocking pays when blocks differ: a one-way F against a randomized block F
In class: Analyse the same data with and without blocks and watch the error mean square fall.
Intermediate Lecture Notes · Nonparametric Statistics: Lecture Notes (Chapter 14)
Distribution-free tests: the sign test, Wilcoxon signed-rank and rank-sum tests, Kruskal-Wallis, Friedman, runs, and their efficiency against the t test.
Demos: Exact null distributions of rank statistics · What a rank test costs: sign, signed rank or t, Kruskal-Wallis or F
In class: Replace the data by ranks, run the Wilcoxon test, and compare its power with the t test on heavy-tailed data.
Intermediate Python Code · Introduction to Mathematical Statistics
One module per chapter and one function per figure, using the book's data tables, written for this course with numpy, scipy and matplotlib.
Each of my papers becomes an interactive demonstration a first-year can run: 23 so far, grouped by theme as on the Software Demos page, each with a suggested use in class. Every demo is a standalone web page to open in a lecture; most can also be shared by QR code, embedded in a slide deck (add ?embed=1) or run in presenter mode, and come with a guided tour and a Try this exercise. The course design table in the teaching portfolio shows how they connect to the open courses.
How models decide their own complexity (how many experts, which components), why that is hard, and how large sparse models route and merge tokens.
Intermediate Universal Approximation · Mixtures and Mixtures of Experts
Drag one slider up and watch a mixture model's curve snap onto whatever target shape you pick.
In class: In Mixture density mode, drag Components K from 2 up to 64 and watch the shaded red error band collapse as the teal curve hugs the dashed target.
Intermediate Spectrum-Preserving Token Merging (PiToMe)
Watch a Vision Transformer merge redundant tokens layer by layer while an energy score shields the informative ones.
In class: Set the policy to Naive ToMe, press Merge one layer repeatedly, and watch the pink arrows mark informative tokens being merged as the ToMe spectral distance climbs.
Intermediate HyperRouter: Efficient Sparse Mixture of Experts via a Frozen HyperNetwork
Train two token routers side by side and watch the ordinary one collapse onto a few experts while the frozen-hypernetwork one stays balanced.
In class: Click Run, then toggle 'Load-balancing aux (standard)' mid-training and watch the standard router's load bars level out and its collapse meter drop.
Intermediate BSL with Mixtures of Experts: a surrogate likelihood that bends
Watch a single stretched ellipse fail to trace a crescent-shaped cloud while a mixture of little ellipses bends right around it.
In class: Set K experts to 1 and click 'Classic BSL': confirm the mixture collapses back to the single amber ellipse and the two log-likelihood readouts match.
Advanced Mixture of Experts & Dendrogram Merging
Fit one over-stuffed mixture of experts, then drag a cut down a dendrogram and watch redundant experts merge until the right number appears.
In class: Set epsilon-contam to 0.40, then drag it back to 0 and watch AIC/BIC/ICL fall back toward K0 as the Laplace outliers disappear.
Advanced Bayesian Nonparametric Mixture of Experts · Merge-Truncate-Merge
Drag one "merge radius" slider and watch a Bayesian model collapse dozens of redundant experts down to the true count.
In class: Set True K₀ to 5 and drag the merge radius ω until the posterior mode K̂ lands on 5, then note how wide the credible spread is.
Advanced Convergence Rates for Parameter Estimation in Mixtures of Experts
Simulate a mixture of experts and read its parameter-recovery speed off a log-log plot, then add one surplus expert and watch the rate collapse.
In class: Set the model to Softmax-gated and toggle K0+1 then K0+2: read the amber slope exponent in the readout and confirm it drops each time you add a surplus expert.
Advanced Variable Selection with Missing-Not-at-Random Data
Crank up how often data go missing and watch naive methods misclassify points (red rings) while the MNAR-aware model holds.
In class: Set MNAR strength to 80%, then click through Complete-case, Mean-impute, and MNAR (unified): watch the ARI bars and count red rings for each handler.
Advanced CompeteSMoE: Effective Training of Sparse Mixture of Experts via Competition
Train two mixture-of-experts side by side and watch one router learn who wins while the other collapses onto a couple of experts.
In class: Click Run, then drag ω down to about 0.07: does the distilled router still reach high agreement with competition on only a few steps?
Advanced Model selection for mixtures of experts via the slope heuristic
Slide the penalty constant and watch the chosen number of experts tumble down a staircase until the data itself marks the right spot.
In class: In well-specified mode, drag Penalty kappa (#msel-kappa) from low to high and note the kappa value where the staircase makes its biggest single drop; that is the dimension jump.
Advanced Multinomial Mixture of Experts: MM Training and Expert Selection
Train a mixture-of-experts classifier whose likelihood can never go down, then watch a spike of contaminated points fool AIC, BIC and ICL while a dendrogram criterion merges it back.
In class: In the second experiment, drag ε from 0.10 to 0 and watch AIC, BIC and ICL drop their extra expert until all four criteria agree; then restore ε and press New data a few times to see which criteria keep the spike.
Advanced Modifications of the BIC for order selection in finite mixture models
Slide the sample size up and watch each information criterion lock its minimum onto the true number of mixture components.
In class: Set the family to Laplace and slide n from 100 up to 10000: watch P(k-hat = k0) for BIC climb to 1 even though the components are non-differentiable at their location.
Advanced PSGaBloME: Penalized Model Selection for Softmax-Gated Mixture of Experts
Drag a penalty dial and watch a mixture-of-experts model shed complexity in a staircase, snapping to the best model.
In class: Set κ to 0, then drag it to 4 and watch the amber star fall down the staircase until it crosses the κ̂ = 2κmin line at the oracle.
Turning noisy, inconsistent data into calibrated uncertainty, and checking that the intervals are honest.
Intermediate Robust Bayesian Parameter Balancing
Drag noisy enzyme measurements and watch a Bayesian fit snap them into thermodynamically consistent parameters, then throw an outlier at it.
In class: Select Gaussian, click Add outlier a few times and read the Coverage number, then switch to Student-t and repeat: watch coverage recover.
Advanced GLLiM-ABC: Likelihood-Free Inference with Surrogate Posteriors
Click a map to place a hidden sound source, then watch four ways of matching simulations fight to recover its blurry, multi-armed posterior.
In class: Select Semi-auto (mean), then GLLiM-MW2, and compare where the amber posterior-mean square sits versus where the accepted dots land.
Advanced Revisiting concentration results for approximate Bayesian computation
Shrink the ABC tolerance toward zero and watch the posterior mass collapse: onto a point, two spikes, or a diamond it can never resolve.
In class: Switch to Finitely unident. and drag ε tolerance toward 0: watch the two spikes at ±θ₀ sharpen but never collapse into one.
Advanced On the large-sample limits of Bayesian model-evaluation statistics
Watch Bayesian criteria slide down a log-scale plot and lock onto a single limit line, unless the tempering schedule breaks the rule.
In class: Pick the 1/n schedule and slide n (bmel-n) up to 10^5: watch the gap-to-limit readout stay positive instead of closing, showing n*beta_n to infinity cannot be dropped.
Advanced The Asymptotic Law of the Minimum Empirical Risk
Reshape a risk valley from a sharp point to a flat plateau and watch the histogram of the best-fit error morph from a clean bell curve into a skewed one.
In class: In MER limit-law mode, set Plateau width w to 0 and hit Run to accumulate draws: confirm the histogram hugs the teal Gaussian, then drag w up to 0.4 and watch it detach and skew left.
Advanced Risk Bounds via the h-Lifted KL Divergence
Sharpen a fitted mixture until it dips to zero and watch the standard KL loss spike to infinity while the h-lifted loss stays finite.
In class: Push Sharpness to its maximum and Lift h to its minimum, then read the right panel: the standard KL risk reports infinity while KLh stays a finite number.
Token merging that keeps vision models fast without losing structure, and deep learning for molecules and medical images.
Intermediate StructSAM: Structure- and Spectrum-Preserving Token Merging for Segment Anything
Watch a patch grid collapse redundant cells while amber edges and the prompt box stay protected, keeping boundaries crisp.
In class: Switch to Naive ToMe, click Merge one layer repeatedly, and watch the amber boundary tokens get absorbed as the structure distance climbs; then switch back to StructSAM and repeat to see the boundaries survive.
Advanced Conformer Aggregation by Fused Gromov-Wasserstein Barycenter
Spin one 3D pose of a molecule: the naive coordinate average lurches, but the optimal-transport aggregate never moves.
In class: Drag Rotate from 0 to 360 and watch the naive-mean drift readout climb while the FGW barycenter drift stays 0.00.
Advanced Fragment-Aware, Fast Conformer Ensemble Transformer
Shuffle a molecule's 3D shapes and watch the averaged fingerprint hold still while the expensive all-pairs alignment vanishes.
In class: Drag Conformers (#facet-n) from 3 to 30 and compare the N(N-1)/2 pairwise FGW solves against the N+1 encode-plus-mean operations in the cost bars.
Advanced Extended Context Graph Alignment for Medical Vision-Language Models
Watch three views of a medical batch snap into agreement with one shared hub, and see crossed red matches turn green.
In class: Toggle #exgra-order from first to second order and watch how many red crossed matches turn green in the panel.
A teaching portfolio should persuade with artefacts rather than adjectives. Here each principle of my teaching philosophy is linked to the materials above that put it into practice, followed by a course designed backward from its learning outcomes and one module taught end to end.
Research-led. Each of my papers becomes a classroom demonstration: 23 so far, in the research pack, with one running on the right.
Learning by doing. In the eleven open courses each topic opens with a demonstration to predict and explore before the formulas, 566 in all, such as the central limit theorem on trial.
Hints before solutions. 1,851 derivations and problems carry graded hints, from a first-year proof of the central limit theorem to the evidence lower bound.
The lesson arc. Every concept moves from an intuition demo to the derivation, a notebook and an authentic assessment; the module below runs the whole arc.
A one-semester course, Mathematical Statistics for AI in Science, assembled from the open materials above and designed backward from its learning outcomes. Each module aligns one outcome with the lesson arc (explore a course demonstration, then the research demonstration where the idea reappears, then derive the key result with graded hints) and with an authentic assessment.
| Module | Students can ... | Explore: course demo → research | Derive, with graded hints | Assessed by |
|---|---|---|---|---|
| Sampling and estimation | derive maximum likelihood estimators, find their sampling distributions and judge them against the Cramér–Rao bound | Maximum likelihood → convergence rates of mixtures of experts | the central limit theorem, the Cramér–Rao bound | derive two estimators for a new model and compare them by simulation |
| Intervals and calibration | build an interval and test whether a 95% interval really covers 95% | Confidence intervals → coverage in parameter balancing | exact coverage of the t interval, conformal coverage | a leave-one-source-out coverage study (worked in full below) |
| Testing | design a test with a given size and power, and separate statistical from practical significance | Power and sample size → when Gaussian inference fails | the Neyman–Pearson lemma | plan the sample size of a real study and defend it |
| Goodness of fit and model choice | test whether a model fits, and choose a model order with BIC or the slope heuristic | Pearson’s degrees of freedom → BIC order selection, slope heuristic | Pearson’s test is a likelihood ratio test | select the order on real data and defend it |
| Regression and mixtures of experts | fit and diagnose a regression, and explain why mixtures of experts can approximate any regression function | Least squares and residuals → universal approximation | the regression curve is the best predictor | extend a demo to a new target function |
| Mixtures and EM in AI | fit a mixture by EM, justify its number of components, and read expert routing in large models as a mixture | K-means and EM → dendrogram merging, competition routing | EM never decreases the likelihood | cluster a dataset and justify the component count |
| Bayesian computation | update a prior with data, and run approximate Bayesian computation when the likelihood is intractable | Prior plus data → GLLiM-ABC, ABC concentration | why ABC targets the posterior | apply ABC to a new simulator |
| Capstone (research-led) | reproduce a result from a live paper and explain it to a first-year | any of the 23 research demos | write the graded hints for one key step of the paper | a reproduced figure, a three-minute explainer and the hints |
Module 2 above, "does a 95% interval actually cover 95%?", taught end to end: the lesson arc at the resolution of a single class, built on the real leave-one-source-out coverage result (Figure 5) from my parameter-balancing paper.
Students open the coverage demo: a fixed-effects Gaussian's 95% interval covers only about 69% of held-out measurements once data sources disagree. The gap is visible, not asserted.
Open the coverage demoStarting from the hinted proof of exact t coverage, we derive the equal-tailed predictive interval and show that ignoring the between-source variance τ² makes it too tight. Leave-one-source-out cross-validation turns that omission into a measurable miscoverage.
On a small multi-source dataset, students fit fixed effects, then add source-level random effects, and watch empirical coverage move from about 0.69 back toward the nominal 0.95, family by family.
They reproduce the paper's Figure 5 coverage curves and write a short argument for when a fixed-effects interval can, and cannot, be trusted. Research-led assessment, not recall.
The courses and demonstrations above are the primary artefacts. Errors are reported and corrected in the open: see the errata and thanks of the first-year, mathematical statistics, probability and statistical inference and advanced probabilistic machine learning courses. Course history is in Teaching experience below; detailed student evaluation summaries and peer-teaching feedback are available on request.