-
Notifications
You must be signed in to change notification settings - Fork 0
/
librarian-farmer-example.py
executable file
·45 lines (37 loc) · 1.66 KB
/
librarian-farmer-example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
# coding: utf-8
# I watched 3Blue1Brown's Bayes theorem video:
# https://youtu.be/HZGCoVF3YvM
#
# I wrote this to go along with it:
import nbayes
class Person(nbayes.Instance):
pass
people = list()
for i in range(10):
if i<4:
people.append(Person('librarian', 'meek and tidy'))
else:
people.append(Person('librarian'))
for i in range(200):
if i<20:
people.append(Person('farmer', 'meek and tidy'))
else:
people.append(Person('farmer'))
c = nbayes.Classifier(*people)
print('prior P(H): {:f}'.format( c.prior('librarian') ))
print('(1/21): {:f}'.format( 1/21.0 ))
print('likelyhood P(E|H): {:f}'.format( c.likelyhood('meek and tidy', 'librarian') ))
print('P(¬H) (is farmer): {:f}'.format( c.prior('farmer') ))
print('P(¬H) (!librarian): {:f}'.format( c.prior('librarian', inverse=True) )) # same
print('P(E|¬H): {:f}'.format( c.likelyhood('meek and tidy', 'farmer') ))
print('a) P(H)P(E|H): {:f}'.format( c.prior('librarian') * c.likelyhood('meek and tidy', 'librarian') ))
print('b) P(¬H)P(E|¬H): {:f}'.format( c.prior('farmer') * c.likelyhood('meek and tidy', 'farmer') ))
print('a+b: {:f}'.format(
c.prior('librarian') * c.likelyhood('meek and tidy', 'librarian') +
c.prior('farmer') * c.likelyhood('meek and tidy', 'farmer') ))
print('c) P(E): {:f}'.format( c.prior('meek and tidy') ))
print('a/c: {:f}'.format(
c.prior('librarian') * c.likelyhood('meek and tidy', 'librarian') /
c.prior('meek and tidy') ))
print('posterior P(H|E): {:f}'.format( c.posterior('librarian', 'meek and tidy') ))