Module 14

Probabilistic Models and Bayesian Learning

How can we build models that predict outcomes and explicitly represent uncertainty in those predictions?

lessons
27
duration
48 h 30 min
concepts
137
available in English
27 / 27
completed by you
0 of 27

Where it fits

Overview

Graphical models (Bayesian networks, Markov random fields and factor graphs) with exact inference by elimination and message passing; Bayesian regression, Laplace approximation and model comparison; latent-variable models (LDA and mixtures of experts) and EM learning on graphs; HMMs, Kalman filtering, smoothing, nonlinear filtering and particle filters; Gaussian processes and Bayesian optimization; variational inference, expectation propagation and MCMC (Metropolis-Hastings, Gibbs and HMC); hierarchical models, Bayesian workflow and frontier topics including Bayesian deep learning and simulation-based inference. Each algorithm is implemented from scratch in NumPy and compared with PyMC, NumPyro, Pyro, GPyTorch, BoTorch or statsmodels.

Why it matters

This module teaches you to quantify uncertainty and decide accordingly. Quantitative work gains Kalman and particle filters, regime-switching models and stochastic volatility; robotics gains EKF, UKF and Monte Carlo localization; GPT and generative models gain the ELBO, reparameterization and amortized inference underlying VAEs and diffusion. Research gains Bayesian hyperparameter optimization, the Bayesian workflow and the ability to write and validate your own samplers.

Lessons 27

  1. 01Operational review: Gaussian algebra, multivariate conjugacy and exponential familiesA dense review of the module's prerequisites, including priors, posteriors and predictive distributions (m05), Gaussian conditioning, information form and the linear Gaussian model (m04), and stable Cholesky computation (m09). Two frequently used tools build on this foundation: multivariate conjugate priors (Normal-gamma and Normal-Wishart, with Student t predictive distributions) and moment-matching projection onto an exponential family, the engine of ADF and expectation propagation.Review90 min
  2. 02Bayesian networks: factorizing the joint with a directed graphA Bayesian network encodes a joint distribution as a product of local conditionals on a DAG. Study the independences implied by its graph, including d-separation and Markov blankets, how to draw models with plates, sample in topological order and learn probability tables from complete data. GPUCore100 min
  3. 03Markov random fields and factor graphsUndirected models represent symmetric interactions with clique potentials. Prove the relationship between Markov properties and factorization (Hammersley-Clifford), introduce the partition function as a major computational obstacle, unify the representations with factor graphs, and learn an Ising model using pseudolikelihood.Core100 min
  4. 04Exact inference: variable elimination and treewidthExact inference in graphical models reduces to summing products of factors in a clever order. Implement variable elimination, see how cost depends on the chosen order's induced width, prove that the general problem is NP-hard, and distinguish marginal, MPE and marginal MAP queries.Core90 min
  5. 05Message passing: sum-product, max-product and loopy belief propagationOn a tree, variable elimination for all queries can be organized as two-pass message passing. Derive sum-product and max-product on factor graphs, outline junction trees for cyclic graphs, and study loopy belief propagation as an approximation applied to LDPC decoding.Core110 min
  6. 06Bayesian linear regression and the evidence approximationLinear regression with basis functions is an ideal laboratory where everything is Gaussian and closed form. Derive posterior, predictive distribution and marginal likelihood, including unknown noise through a Normal-gamma prior; fit hyperparameters by maximizing evidence with MacKay updates; introduce automatic relevance determination; and discover the equivalent kernel leading to Gaussian processes.Core110 min
  7. 07The Laplace approximation and Bayesian logistic regressionWhen the likelihood is no longer Gaussian, the posterior loses its closed form. The Laplace approximation replaces it with a Gaussian centered on the MAP, using the curvature of the log posterior. We apply it to Bayesian logistic regression, obtain the moderated predictive distribution using the probit approximation, and estimate the evidence.Core90 min
  8. 08Bayesian model comparison and structure learningEvidence (m05) compares models with different numbers of parameters without a validation set; here we learn to approximate and use it. We study the Occam factor, the derivation of BIC from Laplace and its limits in singular models, and Bayesian model averaging, applying these ideas to Bayesian network structure learning with BIC and BDeu scores, local search and Chow-Liu trees. GPUCore110 min
  9. 09Latent variable models: mixed membership, mixtures of experts and EM on graphsBuilding on EM and Gaussian mixtures from m12, this lesson broadens the repertoire of latent-variable models and trains them on graphical models. It distinguishes global and local latent variables, formulates LDA and mixtures of experts, treats the E-step in Bayesian networks as inference and the M-step as re-estimation from expected counts, and studies symmetries that make these models non-identifiable.Core110 min
  10. 10Hidden Markov models: filtering, smoothing and decodingThe hidden Markov model is a foundational sequential latent-variable model and the discrete case of a state-space model. We derive forward filtering and likelihood, forward-backward smoothing, Viterbi decoding and backward sampling from the graph structure, all with numerical stability. GPUCore110 min
  11. 11Learning HMMs with Baum-Welch, and from HMMs to linear-chain CRFsBaum-Welch is EM with forward-backward as its E-step. We implement it for multiple sequences, study local optima and non-identifiability, extend it to explicit durations in HSMMs, and contrast the generative HMM with the discriminative linear-chain CRF, which reuses these recursions to calculate its partition function and gradient.Core100 min
  12. 12The Kalman filterA linear Gaussian state-space model is a continuous HMM whose calculations have closed forms. We derive the Kalman filter through repeated linear Gaussian Bayes updates, implement it with numerical stability, obtain likelihood through prediction errors, and study steady state and consistency tests.Core110 min
  13. 13RTS smoothing and learning state-space modelsA filter uses the past; a smoother uses the full series. We derive the Rauch-Tung-Striebel smoother and learn linear Gaussian model parameters both by directly maximizing innovation likelihood with gradients and by EM with smoothed statistics (Shumway-Stoffer).Advanced100 min
  14. 14Nonlinear Gaussian filtering: EKF and UKFWhen dynamics or observations are nonlinear, an approximate Gaussian is maintained. We derive the extended Kalman filter (linearization), its iterated version (Gauss-Newton), the unscented transform and UKF, and present them as cases of moment-matching assumed-density filtering, which returns in expectation propagation. GPUAdvanced100 min
  15. 15Particle filters and sequential Monte CarloMultimodal or strongly non-Gaussian posteriors can be represented by weighted particles. Starting with self-normalized importance sampling for densities known up to a constant, we build sequential importance sampling, diagnose weight degeneracy with effective sample size, compare resampling schemes and implement the bootstrap filter, whose unbiased likelihood estimate combines SMC with MCMC. GPUAdvanced110 min
  16. 16Gaussian processes for regressionA Gaussian process is a prior directly on functions, specified by a mean function and kernel. We derive GP regression by Gaussian conditioning, design priors by choosing and combining kernels, learn hyperparameters by maximizing marginal likelihood with its gradient, and prove equivalence with Bayesian linear regression in feature space. GPUCore120 min
  17. 17Bayesian optimizationTo optimize an expensive gradient-free function, use a GP surrogate and an acquisition function to select evaluations. We derive PI, EI and GP-UCB, examine information-based acquisitions, batches and high dimensions, and apply them to neural-network hyperparameters on a local GPU. GPUCore110 min
  18. 18Variational inference I: the ELBO, mean field and CAVIVariational inference turns integration into optimization: it seeks the distribution closest to the posterior in a tractable family by maximizing the ELBO, the same EM bound from m12 with q restricted to a family. We study mean field and its consequences, coordinate ascent (CAVI), closed updates in conjugate-exponential models and variational EM, with Bayesian Gaussian mixtures and LDA as complete examples.Core110 min
  19. 19Variational inference II: stochastic, black-box and amortizedTo scale to large datasets and nonconjugate models, variational inference becomes stochastic. We study SVI with natural gradients, score-function and reparameterization Monte Carlo estimators and their variance reduction, ADVI transformations to unconstrained space, expressive variational families and amortized inference underlying VAEs. GPUAdvanced110 min
  20. 20Advanced Gaussian processes: classification, EP and scalabilityWe extend GPs beyond Gaussian regression on small datasets. GP classification requires approximate inference: Laplace and expectation propagation, presented generally as iterative moment matching. For scale we study inducing points with the Titsias variational bound and minibatch SVGP, and for long series a state-space formulation solving a Matérn GP in linear time with Kalman. GPUAdvanced120 min
  21. 21MCMC I: Metropolis-Hastings and how to know it worksMCMC constructs a Markov chain whose stationary distribution is the posterior. We prove detailed balance suffices, construct Metropolis-Hastings, study optimal random-walk scaling and implement modern diagnostics: autocorrelation, effective sample size, Monte Carlo standard error and rank-normalized R-hat. GPUCore120 min
  22. 22MCMC II: Gibbs sampling, data augmentation and slice samplingSampling each variable conditional on the rest is often straightforward thanks to graph structure and conjugacy. We study Gibbs and its blocked and collapsed versions, data augmentation with auxiliary variables (Albert-Chib probit and Pólya-Gamma), slice sampling and Dirichlet-process mixtures with the Chinese restaurant process.Core110 min
  23. 23Hamiltonian Monte Carlo, NUTS and Langevin dynamicsRandom walks scale poorly with dimension; gradients offer another approach. We interpret the posterior as a potential-energy landscape, simulate Hamiltonian dynamics with the symplectic, reversible leapfrog integrator and correct error with Metropolis. We outline NUTS, diagnose divergences and finish with Langevin methods (ULA, MALA and SGLD). GPUAdvanced120 min
  24. 24Bayesian hierarchical modelsHierarchical models learn how much to pool across groups by sharing a distribution over group-level parameters. Study de Finetti’s theorem, partial pooling, priors for scales, the funnel geometry and noncentered parameterization, multilevel regression, and horseshoe and spike-and-slab priors for sparse regression. GPUCore120 min
  25. 25Bayesian workflow and probabilistic programmingBuild a small probabilistic programming language with effect handlers to understand the machinery behind PyMC, NumPyro and Pyro. Integrate predictive checks, validate the algorithm with simulation-based calibration, compare models with Pareto-smoothed importance-sampling leave-one-out, and estimate evidence with bridge sampling or thermodynamic integration. GPUCore120 min
  26. 26Uncertainty quantification and Bayesian deep learningSeparate predictive uncertainty into aleatoric and epistemic components, use epistemic uncertainty for active learning with BALD, and apply Bayesian inference to neural networks. Compare reference HMC posteriors with scalable approximations such as last-layer Laplace, MC dropout, SWAG, and deep ensembles. Use the NNGP from lesson 16 as a function-space prior and examine the cold posterior effect. GPUResearch110 min
  27. 27Frontier: simulation-based inference, amortized inference and neural samplersWhen a simulator supplies samples but no tractable likelihood, or inference must be repeated thousands of times, a network can learn to do the inference. This lesson goes from ABC to neural posterior, likelihood, and ratio estimation (NPE, NLE, NRE), checks calibration with expected coverage, trains a prior-data fitted network to approximate the Bayesian predictive distribution, and introduces neural samplers for unnormalized densities. GPUResearch100 min

Module capstone

minippl: your own Bayesian inference engine validated on three real cases

Build a small probabilistic programming library on PyTorch with CPU or GPU automatic differentiation, effect handlers and several inference engines: exact enumeration for discrete variables, Kalman and RTS for linear Gaussian models, a particle filter, HMC with dual-averaged step size and ADVI. Validate each engine with simulation-based calibration. Apply it to three cases: (1) the eight schools and radon hierarchical models, compared with PyMC or NumPyro; (2) regime-switching stochastic volatility on daily returns, estimated with particle MCMC; and (3) Bayesian optimization using your own GP for the hyperparameters of an m11 or m15 model. Deliver code with tests, a report with diagnostics (R-hat, ESS, divergences and PSIS k̂), and an honest comparison of accuracy and cost against professional libraries.

Check what you already know

  • Condition Gaussians with Cholesky, update a Normal-Wishart prior and project a distribution onto a Gaussian by moment matching.
  • Use d-separation to decide whether two variables are independent given an observed set in a Bayesian network.
  • Run sum-product and max-product on a tree-shaped factor graph.
  • Calculate the predictive distribution and log evidence of Bayesian linear regression and fit its hyperparameters.
  • Derive BIC from Laplace evidence and learn a Chow-Liu tree.
  • Derive the EM E-step in a Bayesian network with hidden nodes as a calculation of family marginals, and classify a model's latents as global or local.
  • Implement forward-backward and Viterbi in log space.
  • Derive and implement the Kalman filter with Joseph form and innovations log-likelihood.
  • Implement a bootstrap particle filter with adaptive systematic resampling.
  • Fit a Gaussian process by maximizing marginal likelihood using its gradient.
  • Derive CAVI updates for a conjugate-exponential model.
  • Implement Metropolis-Hastings and diagnose it with ESS and rank-normalized R-hat.
  • Implement HMC with leapfrog and dual averaging of step size, and interpret divergences.
  • Reparameterize a hierarchical model in non-centered form to eliminate divergences.
  • Compare models with PSIS-LOO and validate your own sampler using simulation-based calibration.

References