-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Exercise 10: Naive Bayes classifier.py
- Loading branch information
1 parent
c4762ed
commit 6215f08
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |