Bayesian inference

File: bayes.lisp

Fourteen lines of Lisp implement Bayes’ theorem as a reusable update function, and the demo reproduces the well-known medical “base-rate fallacy” result.

Bayes’ theorem computes the posterior probability of a hypothesis given evidence:

math

The program works with whole distributions: a distribution is an alist of (hypothesis . probability) pairs, and normalizing after each update takes care of the denominator Code Test.

The code

 1 ;; sbcl --script bayes.lisp (Bayesian inference)
 2 
 3 (defun bayes-normalize (dist)
 4   (let ((sum (reduce #'+ dist :key #'cdr)))
 5     (when (zerop sum)
 6       (error "The evidence has zero probability under every hypothesis"))
 7     (mapcar (lambda (p) (cons (car p) (/ (cdr p) sum))) dist)))
 8 
 9 (defun bayes-update (dist evidence likelihood-fn)
10   (bayes-normalize
11    (mapcar (lambda (p)
12              (cons (car p)
13                    (* (cdr p)
14                       (funcall likelihood-fn (car p) evidence))))
15            dist)))
16 
17 (defun map-hypothesis (dist)
18   (reduce (lambda (a b) (if (> (cdr a) (cdr b)) a b)) dist))
19 
20 ;; Demo: Medical screening base-rate fallacy
21 ;; Disease prevalence: 1%. Test: 95% sensitivity (true +), 5% false +
22 (let* ((prior '((has-disease . 0.01) (healthy . 0.99)))
23        (likelihood (lambda (hyp test-result)
24                      (case hyp
25                        (has-disease (if (eq test-result '+) 0.95 0.05))
26                        (healthy
27                         (if (eq test-result '+) 0.05 0.95)))))
28        (post1 (bayes-update prior '+ likelihood))
29        (post2 (bayes-update post1 '+ likelihood)))
30   (format t "Prior:         ~{~a: ~,4f~^, ~}~%"
31           (mapcan (lambda (p) (list (car p) (cdr p))) prior))
32   (format t "After 1st (+): ~{~a: ~,4f~^, ~}  -> MAP: ~a~%"
33           (mapcan (lambda (p) (list (car p) (cdr p))) post1)
34           (car (map-hypothesis post1)))
35   (format t "After 2nd (+): ~{~a: ~,4f~^, ~}  -> MAP: ~a~%"
36           (mapcan (lambda (p) (list (car p) (cdr p))) post2)
37           (car (map-hypothesis post2))))

How it works

  • bayes-update multiplies each prior probability by the likelihood of the evidence under that hypothesis, then bayes-normalize divides by the total so the probabilities sum to one again. That multiply-then-normalize pair is Bayes’ theorem. If the total is zero (evidence that every hypothesis rules out), no posterior exists, so bayes-normalize signals an error instead of dividing by zero.
  • The caller passes the likelihood as a function, so the same updater works for any hypothesis and evidence types.
  • map-hypothesis returns the most probable pair, the maximum a posteriori (MAP) estimate.
  • reduce with :key #'cdr sums the probabilities without a loop; the ~{...~^, ~} format directive prints the alist as a comma-separated list.

Running it

1 $ sbcl --script bayes.lisp

Actual output:

1 Prior:         HAS-DISEASE: 0.0100, HEALTHY: 0.9900
2 After 1st (+): HAS-DISEASE: 0.1610, HEALTHY: 0.8390  -> MAP: HEALTHY
3 After 2nd (+): HAS-DISEASE: 0.7848, HEALTHY: 0.2152  -> MAP: HAS-DISEASE

The second line shows the fallacy: even after a positive result from a “95% accurate” test, a patient with a disease that affects 1% of people probably does not have it, because the posterior is only about 16%:

math

Using that posterior as the prior for a second, independent positive test (post2) raises the probability to about 78%.

Using it

Swap in your own hypotheses and likelihoods: spam classification, sensor fusion, diagnosis with more than two hypotheses. One caveat: sequential bayes-update calls assume each piece of evidence is conditionally independent given the hypothesis, so correlated evidence (say, the same test run twice) makes the posterior overconfident.