Bayesian Inference

File: Bayes.lean

A test for a disease is right 95 times in 100. One person in 100 has the disease. You test positive. What is the chance you have the disease? Most people say 95 in 100. The answer is about 16 in 100, because healthy people far outnumber sick people and some of them test positive too.

Bayes’ rule gives the new probability of each hypothesis Code Test after evidence Code Test:

math

The Code

 1 -- lean --run Bayes.lean   (Bayesian inference)
 2 
 3 abbrev Dist (α : Type) := List (α × Float)
 4 
 5 def normalize (dist : Dist α) : Dist α :=
 6   let sum := dist.foldl (fun acc p => acc + p.2) 0.0
 7   dist.map fun (h, p) => (h, p / sum)
 8 
 9 def update (dist : Dist α) (evidence : ε)
10     (likelihood : α → ε → Float) : Dist α :=
11   normalize (dist.map fun (h, p) => (h, p * likelihood h evidence))
12 
13 -- Maximum a posteriori hypothesis
14 def mapHypothesis [Inhabited α] (dist : Dist α) : α :=
15   match dist with
16   | [] => default
17   | first :: rest =>
18     (rest.foldl (fun a b => if a.2 > b.2 then a else b) first).1
19 
20 def fixed (x : Float) (d : Nat := 4) : String :=
21   let n := (x.abs * (10 ^ d).toFloat).round.toUInt64.toNat
22   let frac := toString (n % 10 ^ d)
23   let pad := "".pushn '0' (d - frac.length)
24   s!"{if x < 0 then "-" else ""}{n / 10 ^ d}.{pad}{frac}"
25 
26 -- Demo: medical screening base-rate fallacy.
27 -- Disease prevalence: 1%. Test: 95% sensitivity, 5% false positives.
28 inductive Hypothesis where
29   | hasDisease | healthy
30   deriving Inhabited
31 
32 instance : ToString Hypothesis where
33   toString
34     | .hasDisease => "has-disease"
35     | .healthy => "healthy"
36 
37 inductive TestResult where
38   | positive | negative
39 
40 def likelihood : Hypothesis → TestResult → Float
41   | .hasDisease, .positive => 0.95
42   | .hasDisease, .negative => 0.05
43   | .healthy,    .positive => 0.05
44   | .healthy,    .negative => 0.95
45 
46 def showDist [ToString α] (dist : Dist α) : String :=
47   ", ".intercalate (dist.map fun (h, p) => s!"{h}: {fixed p}")
48 
49 def main : IO Unit := do
50   let prior : Dist Hypothesis := [(.hasDisease, 0.01), (.healthy, 0.99)]
51   let post1 := update prior TestResult.positive likelihood
52   let post2 := update post1 TestResult.positive likelihood
53   let best (d : Dist Hypothesis) := mapHypothesis d
54   IO.println s!"Prior:         {showDist prior}"
55   IO.println s!"After 1st (+): {showDist post1}  -> MAP: {best post1}"
56   IO.println s!"After 2nd (+): {showDist post2}  -> MAP: {best post2}"

How It Works

  • abbrev Dist (α : Type) := List (α × Float) names a type: a list of pairs, each a hypothesis of any type α with its probability. × builds a pair type.
  • normalize and update use α and ε without declaring them. Lean adds them as type parameters. update works for any hypothesis type and any evidence type.
  • fun (h, p) => ... is a function that takes a pair apart in its parameter list.
  • update multiplies each prior by the likelihood of the evidence, then normalize divides by the sum. Those two steps are the numerator and the denominator of Bayes’ rule.
  • mapHypothesis returns the most probable hypothesis. An empty list has none, so the function needs some value of type α to return. [Inhabited α] asks for a type that has a default value, and deriving Inhabited makes Lean supply one for Hypothesis.
  • Hypothesis and TestResult are inductive types. The Common Lisp version uses symbols here. With inductive types, Lean checks that likelihood has a case for each of the four pairs.
  • instance : ToString Hypothesis tells Lean how to print a hypothesis. String interpolation calls it.

mapHypothesis scans with >, so on an exact tie it keeps the earlier hypothesis, which is the first in the list. Ties are rare with real likelihoods but common with hand-set priors. fixed rounds for display only; it does not change the inference.

Checking the Numbers

After one positive test, the numerator for hasDisease is 0.01 * 0.95 = 0.0095. The numerator for healthy is 0.99 * 0.05 = 0.0495. Their sum is 0.0590, so the posterior is 0.0095 / 0.0590 = 0.1610. The low base rate makes the numerator for the sick group small.

The second test applies the same rule to the first posterior. Before normalization the weights are 0.1610 * 0.95 = 0.1530 and 0.8390 * 0.05 = 0.0420. Their sum is 0.1950, so the result is 0.7848. Two positive tests are enough to change the MAP.

update applies one test at a time, but two calls give the same posterior as one call that multiplies both likelihoods, because each step multiplies and then divides by the total. The program uses that identity but does not state it.

Prior P(hasDisease) Posterior after one positive test
1% 0.1610
10% 0.6786
50% 0.9500

Predict each row before you run the program, then check it. A common disease needs less evidence to reach a high posterior; a rare one needs a second test. Try this: change the prior to 10% and confirm the first row of the table.

Lean 4 Notes

Implicit type parameters. The signature of normalize mentions α but never declares it. Lean declares it for you. #check prints the full type:

1 #check @normalize
2 -- @normalize : {α : Type} → Dist α → Dist α

The braces mark α as an implicit argument. You do not pass it. Lean works it out from the argument: in normalize prior, prior has type Dist Hypothesis, so α is Hypothesis. This is how you write generic functions in Lean.

Type classes. Square brackets mark a third kind of argument. [Inhabited α] and [ToString α] ask for an instance of a type class. A type class names a set of operations that a type may support. ToString has one operation, toString. An instance declaration supplies the operations for one type. When you call showDist post1, Lean searches the instances it knows, finds the one for Hypothesis, and passes it. If no instance exists, the call does not compile.

deriving Inhabited asks Lean to write an instance for you. Lean can derive several classes this way. The Autograd chapter uses it again.

Matching on two arguments. likelihood has the type Hypothesis → TestResult → Float and no named parameters. Each line after it gives one pattern per argument, with a comma between them. This form is short for a function that takes two arguments and matches on both.

Leading dots. .hasDisease is short for Hypothesis.hasDisease. Lean fills in the namespace from the type it expects at that position. That is why main gives prior a type: let prior : Dist Hypothesis := .... Without it, Lean could not tell which type .hasDisease belongs to.

Lists. [] is the empty list and first :: rest is a list with a first element and a remaining list. mapHypothesis matches on those two forms. They are the two constructors of List, so the match is complete.

Pairs. (h, p) builds a pair and p.1 and p.2 read its parts. In a fun or a for you can write the pattern (h, p) in place of a name, and Lean takes the pair apart.

Running It

1 $ lean --run Bayes.lean
2 Prior:         has-disease: 0.0100, healthy: 0.9900
3 After 1st (+): has-disease: 0.1610, healthy: 0.8390  -> MAP: healthy
4 After 2nd (+): has-disease: 0.7848, healthy: 0.2152  -> MAP: has-disease

After one positive test the most probable hypothesis is still healthy. After a second positive test it changes to has-disease.

Using It

Add a third hypothesis to Hypothesis. Lean then reports an error in likelihood until you add its cases. Change the prior to see how a rare disease differs from a common one. Because update is generic, you can reuse it with your own types, for example a list of spam and not-spam hypotheses with words as evidence.