Skip to content

Instantly share code, notes, and snippets.

@cstrelioff
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cstrelioff/d0d424510c6d467173d4 to your computer and use it in GitHub Desktop.
Save cstrelioff/d0d424510c6d467173d4 to your computer and use it in GitHub Desktop.
python + lea: revisiting the medical tests example

A script that replicates all examples in my blog post on revisiting the Bayesian medical tests example-- using Python and Lea to do some probabilistic programming: Medical test/Lea post

Run all the examples

    $ python lea_ex02.py

Or,

    $ chmod u+x lea_ex02.py
    $ ./lea_ex02.py

That's it, give it a try!

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 Christopher C. Strelioff <chris.strelioff@gmail.com>
#
# Distributed under terms of the MIT license.
"""
Revisiting the Bayesian medical tests example, a second example of probabilistic programming using Lea.
Blog post: http://chrisstrelioff.ws/sandbox/2015/05/27/revisiting_the_medical_tests_example_with_python_and_lea.html
"""
from __future__ import division, print_function
from lea import Lea
# define cancer dist
cancer = Lea.fromValFreqs(('yes', 1),
('no', 99))
print('\nCancer Distribution',
'P(C)',
cancer.asPct(),
sep='\n')
# prob for mamm given cancer == yes
mamm_g_cancer = Lea.fromValFreqs(('pos', 80),
('neg', 20))
print('\nProb for mammogram given cancer',
'P(M|C=yes)',
mamm_g_cancer.asPct(),
sep='\n')
# prob for mamm given cancer == no
mamm_g_no_cancer = Lea.fromValFreqs(('pos', 96),
('neg', 1000-96))
print('\nProb for mammogram given NO cancer',
'P(M|C=no)',
mamm_g_no_cancer.asPct(),
sep='\n')
# conditional probability table
mammograms = Lea.buildCPT((cancer == 'yes', mamm_g_cancer),
(cancer == 'no', mamm_g_no_cancer))
print('\nMammograms',
'P(M)',
mammograms.asPct(),
sep='\n')
# get joint probs for all events
joint_probs = Lea.cprod(mammograms, cancer)
print('\nJoint Probabilities',
'P(M, C)',
joint_probs.asPct(),
sep='\n')
# prob cancer GIVEN mammogram==pos
print('\nThe Answer',
'P(C|M=pos)',
cancer.given(mammograms == 'pos').asPct(),
sep='\n')
# prob cancer GIVEN mammogram==neg
print('\nExtra Info',
'P(C|M=neg)',
cancer.given(mammograms == 'neg').asPct(),
sep='\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment