Skip to content

Commit

Permalink
Create Exercise 10: Naive Bayes classifier.py
Browse files Browse the repository at this point in the history
  • Loading branch information
alkhdaniel authored Apr 15, 2022
1 parent c4762ed commit 6215f08
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions chapter-2/Exercise 10: Naive Bayes classifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import numpy as np

p1 = [1/6, 1/6, 1/6, 1/6, 1/6, 1/6] # normal
p2 = [0.1, 0.1, 0.1, 0.1, 0.1, 0.5] # loaded

def roll(loaded):
if loaded:
print("rolling a loaded die")
p = p2
else:
print("rolling a normal die")
p = p1

# roll the dice 10 times
# add 1 to get dice rolls from 1 to 6 instead of 0 to 5
sequence = np.random.choice(6, size=10, p=p) + 1
for roll in sequence:
print("rolled %d" % roll)

return sequence

def bayes(sequence):
odds = 1.0 # start with odds 1:1
for roll in sequence:
r = p2[roll-1] / p1[roll-1] #remember that r = P(loaded ∣ roll)÷P(normal ∣ roll), roll-1 because index starts at 0
odds = odds*r #update the odds (multiply the old odds with r)
if odds > 1:
return True
else:
return False

sequence = roll(True)
if bayes(sequence):
print("I think loaded")
else:
print("I think normal")

0 comments on commit 6215f08

Please sign in to comment.