Simple Algorithm
Machine Learning · Initialization · 17 min

Probabilistic Machine Learning

Models that say how sure they are.

A spam filter that says "spam" is useful. One that says "92% spam" is more useful, because it tells you how far to trust it. Probabilistic machine learning builds models that answer with probabilities, fits them to data with the rules of probability (Bayes' rule above all), and keeps track of what it does not yet know.

What you’ll learn

  • Explain what it means for a model to output a probability distribution, and why a stated uncertainty is useful.
  • Estimate a coin's probability of heads by maximum likelihood, and explain why that estimate is overconfident on little data.
  • Update a belief with Bayes' rule, and relate the prior, the posterior, the MAP estimate and the maximum likelihood estimate.
  • Describe how latent variables and mixture models explain data through hidden causes, and what the EM algorithm does.
  • Explain why exact inference is often impossible, and what sampling (MCMC) and approximation do instead.

Answers with error bars

Most models you meet first give one answer: a price, a class, a cluster. A probabilistic model gives a whole distribution over answers. Two loan models can both predict "will repay", one with 51% confidence and one with 99%; only the second deserves to be trusted without a human check. A demand forecast of "120 units, give or take 15" lets a shop decide how much spare stock to hold, which "120 units" alone cannot.

The language for this is probability. It describes two kinds of uncertainty with the same rules: randomness in the world (a coin flip, noise in a sensor), which no amount of data removes, and ignorance about the model itself (which parameter values are right), which shrinks as data arrive.

TaskA plain model outputsA probabilistic model outputs
Classificationone labela probability for every class
Regressionone numbera distribution: a mean and a spread
Clusteringone cluster per pointa probability for each cluster, per point
Fitting parametersone best valuea distribution over plausible values
The last row is the deepest change: the model is unsure about itself, and says so.
Predict before you look

A weather model says "30% chance of rain" on 200 different days. If its probabilities mean what they say, on about how many of those days should it rain?

Show the answer

60 days

0.3×200=600.3\times200=60, give or take about 6 from chance. A model whose stated probabilities match long-run frequencies like this is calibrated (calibration). Probabilities are only useful if they are honest, which is why later lessons check them against data.

The coin: maximum likelihood

Take a coin that lands heads with an unknown probability pp. You flip it 10 times and see 7 heads and 3 tails. Treat the flips as independent, each heads with probability pp (a Bernoulli trial). The probability of exactly this sequence, read as a function of pp, is the likelihood:

L(p)=p7 (1−p)3L(p) = p^{7}\,(1-p)^{3}
One factor pp per head, one factor 1−p1-p per tail. The data are fixed; pp varies.
Predict before you look

How many times more probable is this exact sequence if p=0.7p = 0.7 than if the coin is fair (p=0.5p = 0.5)?

Show the answer

2.28 ×

L(0.7)=0.77×0.33≈0.00222L(0.7) = 0.7^7\times0.3^3 \approx 0.00222 and L(0.5)=0.510≈0.000977L(0.5) = 0.5^{10} \approx 0.000977, a ratio of about 2.282.28. Both numbers are tiny, because any particular sequence of 10 flips is unlikely. Only the comparison between values of pp matters.

The value of pp that makes the observed data most probable is the maximum likelihood estimate (MLE). For a coin it is simply the fraction of heads, p^=h/n\hat p = h/n: here 0.70.7. (The Descent lesson derives it with one line of calculus.) Try it on a coin whose true probability is hidden from you.

Bayes' rule: updating a belief

Bayes' rule says how a belief in a hypothesis HH should change after seeing evidence EE:

P(H∣E)=P(E∣H) P(H)P(E).P(H \mid E) = \frac{P(E \mid H)\,P(H)}{P(E)}.

P(H)P(H) is the belief before the evidence, P(E∣H)P(E \mid H) is how likely the evidence is if HH is true, and P(E)P(E) is the overall chance of the evidence, which makes the answer sum to one. In words: posterior ∝ likelihood × prior.

A classic case: a disease affects 1% of people. A test detects 90% of real cases, and it also comes back positive for 9% of healthy people.

Check your understanding

You test positive. Roughly how likely is it that you have the disease?

  1. About 90%
  2. About 50%
  3. About 9%
  4. About 1%, the same as before the test
Show the answer

C. About 9%

Picture 1,000 people: 10 are sick and 9 of them test positive; of the 990 healthy people, about 89 also test positive. Only 9 of the 98 positives are sick, about 9.2%. The disease is so rare that false alarms among the many healthy people outnumber the true cases.

A prior over the coin

Now apply Bayes' rule to the coin's unknown pp itself. The prior is a curve over [0,1][0, 1] saying which values you find plausible before flipping. The posterior is that curve multiplied by the likelihood and rescaled to area one. A convenient family of priors is the Beta distribution Beta(a,b)\mathrm{Beta}(a, b), which behaves like aa imaginary heads and bb imaginary tails seen before you start. After hh real heads and tt real tails you simply add the counts:

prior Beta(a, b) → h heads, t tails  posterior Beta(a+h, b+t),posterior mean=a+ha+b+n\text{prior } \mathrm{Beta}(a,\,b)\ \xrightarrow{\ h \text{ heads},\ t \text{ tails}\ }\ \text{posterior } \mathrm{Beta}(a+h,\ b+t),\qquad \text{posterior mean} = \frac{a+h}{a+b+n}
n=h+tn = h + t. With the flat prior Beta(1,1)\mathrm{Beta}(1, 1), three heads in three flips give a posterior mean of 4/5=0.84/5 = 0.8 instead of the MLE's 1: Laplace's rule of succession.

Two single numbers summarize the posterior: its mean, and its peak, the MAP estimate (maximum a posteriori). With a flat prior the MAP equals the MLE; a prior pulls both toward the values it favors. The posterior also gives a range: a 95% credible interval contains pp with probability 95%, given the data and the prior.

Think first Two people start from very different priors, "Heads" and "Tails", and watch the same 1,000 flips. Do they end up agreeing?

Almost exactly. "Heads" is Beta(30,10)\mathrm{Beta}(30, 10) and "Tails" is Beta(10,30)\mathrm{Beta}(10, 30), each worth 40 imaginary flips, which 1,000 real flips swamp: whatever the count of heads hh, the posterior means (h+30)/1040(h+30)/1040 and (h+10)/1040(h+10)/1040 differ by only 20/1040≈0.0220/1040\approx0.02, and the gap keeps shrinking as flips accumulate. There is one exception: a prior that gives some value of pp zero probability can never be argued back into it, whatever the data say. Never rule out what you cannot exclude.

Hidden causes: latent variables and mixtures

Many datasets are mixtures of groups whose labels nobody recorded: flower measurements from several species, purchases from different kinds of customers, sensor readings from a machine that is sometimes healthy and sometimes not. The unrecorded group is a latent variable, a hidden cause behind each data point.

A Gaussian mixture model says each point was made in two moves: pick one of KK clusters at random (cluster kk with probability πk\pi_k), then draw the point from that cluster's bell-shaped Gaussian distribution. Fitting it means finding the clusters without knowing which point came from which. Bayes' rule does the inverse step: given the current clusters, the probability that a point came from cluster kk is its responsibility for that cluster.

The EM algorithm alternates two steps:

  1. E-step: compute every point's responsibilities from the current clusters.
  2. M-step: refit each cluster's weight, center and shape to all the points, each counted in proportion to its responsibility.

Each round never lowers the likelihood of the data, so EM always settles down, though not always on the best fit. It is a soft version of k-means, which forces every point to belong to exactly one cluster.

Check your understanding

After EM has converged, a point has responsibilities 0.55 for cluster 1, 0.40 for cluster 2 and 0.05 for cluster 3. What does this mean?

  1. 55% of the point belongs to cluster 1 and 40% to cluster 2
  2. Cluster 1 contains 55% of all the data
  3. Under the fitted model, the point came from cluster 1 with probability 0.55 and from cluster 2 with probability 0.40
  4. The point is an outlier that fits no cluster
Show the answer

C. Under the fitted model, the point came from cluster 1 with probability 0.55 and from cluster 2 with probability 0.40

Responsibilities are posterior probabilities of the hidden label, computed by Bayes' rule from the cluster weights and how well each Gaussian explains the point. The point came from exactly one cluster; the model is simply unsure which.

When exact answers run out: sampling

For the coin, the posterior has a formula. For most models it does not. Bayes' rule needs the normalizing constant p(D)p(\data), an integral of likelihood × prior over every possible parameter setting. A model with 1,000 parameters would need that integral over a 1,000-dimensional space: even a crude grid of 10 values per parameter has 10100010^{1000} points.

Markov chain Monte Carlo (MCMC) sidesteps the integral. It runs a random walk through parameter space, a Markov chain, built so that in the long run the share of time it spends in each region matches that region's posterior probability. Each move is accepted or rejected using only a ratio of posterior values, and in a ratio the unknown constant cancels. Averages over the visited points then estimate anything you want, such as the posterior mean or a credible interval: that is the Monte Carlo part.

Where to go next

The four ideas of this lesson, likelihoods, priors and posteriors, hidden variables, and approximate inference, run through modern machine learning. Training a classifier with cross-entropy is maximum likelihood; weight decay is a prior in disguise; and many generative models, such as variational autoencoders and diffusion models, are latent-variable models trained with the tools of approximate inference.

Descent lessonWhat you will do there
Maximum Likelihood & MAPDerive maximum likelihood estimates for coins and Gaussians, see that least squares and cross-entropy are likelihoods in disguise, and recover ridge and lasso as MAP estimates.
Bayesian InferenceWork with full posteriors, make predictions that average over parameters, use conjugate priors, and tell credible intervals from confidence intervals.
Latent Variables & EMFit Gaussian mixtures, compute responsibilities, and prove that EM never decreases the likelihood.
Approximate InferenceEstimate integrals by Monte Carlo, build Metropolis–Hastings and Gibbs samplers, and turn inference into optimization with variational methods.
In the Descent lessons each idea gets its math and its algorithms. The Convergence lessons go further: the asymptotic theory of maximum likelihood, exponential families, misspecified models, model selection, the theory of EM, and Hamiltonian Monte Carlo.

Key takeaways

  • Probabilistic models output distributions, not single answers, and so say how sure they are. Calibrated probabilities can be acted on: a 30% forecast should come true 30% of the time.
  • The likelihood scores each parameter value by how probable it makes the data. Maximizing it gives the MLE (the fraction of heads for a coin), which can be badly overconfident on small samples.
  • Bayes' rule turns a prior into a posterior, posterior ∝ likelihood × prior. A Beta(a,b)\mathrm{Beta}(a, b) prior on a coin becomes Beta(a+h,b+t)\mathrm{Beta}(a+h, b+t); as data grow the posterior narrows and the prior washes out.
  • Latent-variable models explain data through hidden causes. EM alternates soft assignments (responsibilities, by Bayes' rule) with refitting, and never lowers the likelihood.
  • Exact posteriors are rare. MCMC samples from a posterior using only ratios of densities; variational inference approximates it by optimization, trading exactness for speed.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You flip a new coin 4 times and get 4 heads. What is the maximum likelihood estimate of P(heads)P(\text{heads}), and what is wrong with it?

  1. 0.50.5, because most coins are fair
  2. 11, which declares tails impossible after only 4 flips
  3. 0.80.8, because 4 of 5 imaginary flips are heads
  4. It does not exist until both outcomes have been seen
Show the answer

B. 11, which declares tails impossible after only 4 flips

The MLE is the fraction of heads, 4/4=14/4 = 1. It trusts a tiny sample completely. A flat Beta(1,1)\mathrm{Beta}(1,1) prior gives the posterior mean (4+1)/(4+2)≈0.83(4+1)/(4+2)\approx0.83 instead, which still leans toward heads but leaves room for tails.

Question 2

A condition affects 1 person in 1,000. A test catches 99% of cases and gives a false positive for 1% of healthy people. After one positive result, the probability of having the condition is closest to:

  1. 99%
  2. 50%
  3. 9%
  4. 0.1%
Show the answer

C. 9%

Out of 100,000 people, 100 have it and 99 test positive; of the 99,900 healthy, 999 test positive. So 99/(99+999)≈9%99/(99+999)\approx9\%. A rare condition needs a test with a far smaller false-positive rate, or a second test.

Question 3

Two analysts with different (but not dogmatic) Beta priors observe the same 10,000 flips of a coin. What do their posteriors look like?

  1. Nearly identical and narrow, centered close to the observed fraction of heads
  2. Still far apart, because priors never wash out
  3. Identical to their priors, because data cannot change a belief
  4. Both flat, because more data means more uncertainty
Show the answer

A. Nearly identical and narrow, centered close to the observed fraction of heads

Each Beta prior is worth a fixed number of imaginary flips, which 10,000 real flips swamp. Both posteriors concentrate within about a percentage point of the observed frequency. Only a prior that assigns zero probability to the truth resists any amount of data.

Question 4

Which describes one iteration of EM for a Gaussian mixture?

  1. Assign every point permanently to its nearest center, then delete empty clusters
  2. Add one more cluster, then keep it if the likelihood rises
  3. Draw random cluster labels and average the results over many draws
  4. Compute each point's responsibilities from the current clusters, then refit every cluster using those responsibilities as weights
Show the answer

D. Compute each point's responsibilities from the current clusters, then refit every cluster using those responsibilities as weights

The E-step uses Bayes' rule to get soft assignments; the M-step refits weights, means and covariances to the weighted points. Repeating the pair never lowers the likelihood, so EM settles down, usually at a local optimum that need not be the best fit.

Question 5

Why can MCMC sample from a posterior without ever computing its normalizing constant p(D)p(\data)?

  1. Because p(D)p(\data) is always equal to 1
  2. Because each accept-or-reject decision uses a ratio of posterior densities, in which p(D)p(\data) cancels
  3. Because MCMC first computes p(D)p(\data) by numerical integration on a grid
  4. Because MCMC only works with flat priors
Show the answer

B. Because each accept-or-reject decision uses a ratio of posterior densities, in which p(D)p(\data) cancels

The posterior is likelihood × prior divided by p(D)p(\data). A ratio of two posterior values divides p(D)p(\data) by itself, so the sampler needs only likelihood × prior, which is easy to evaluate.

Go deeper

Further reading

  • K. P. Murphy, Probabilistic Machine Learning: An Introduction (MIT Press, 2022), chapter 4.
  • D. J. C. MacKay, Information Theory, Inference, and Learning Algorithms (Cambridge University Press, 2003).