-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbayesnet.py
More file actions
82 lines (61 loc) · 2.15 KB
/
Copy pathbayesnet.py
File metadata and controls
82 lines (61 loc) · 2.15 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Bayes Net
import pandas as pd
import json
OBS = 'data/hmm.csv'
class BayesNet():
def __init__(self):
self.init_obs(OBS)
def init_obs(self, OBS):
obs = pd.read_csv(OBS)
symptoms = list(obs.Symptom.unique())
self.obs = {}
for i, symptom in enumerate(symptoms):
if symptom != 'nan':
count_dis_sym = obs[obs['Symptom'] == str(symptom)]
count_dis_sym = count_dis_sym['Occurance']
probs = self.normalise(count_dis_sym)
diseases = obs[obs['Symptom'] == str(symptom)]
diseases = diseases['Disease']
self.obs[symptom] = dict(
zip(diseases, probs))
def normalise(self, table):
total = float(sum([i for i in table]))
return [float(i) / total for i in table]
def probability(self, symptom):
try:
return self.obs[symptom]
except KeyError:
return None
def prob_symptoms(self, symptoms):
prev = set([])
prob = {}
for symptom in symptoms:
if self.probability(symptom):
prob[symptom] = self.probability(symptom)
prev = set(prob[symptom].keys())
psym = {}
expected = list(prev)
for i in range(0, len(symptoms)):
try:
set1 = set(prob[symptoms[i]].keys())
prev = set1.intersection(prev)
expected = list(set(prev))
except KeyError:
pass
expected_probs = []
for dis in list(set(expected)):
p = sum([prob[symptom][dis]
for symptom in symptoms if symptom in prob.keys()])
expected_probs.append(p)
psym['_'.join(symptoms)] = dict(
zip(expected, self.normalise(expected_probs)))
if psym['_'.join(symptoms)] == {}:
return None
return psym
if __name__ == '__main__':
net = BayesNet()
print "Probability of influenza given syncope is: "
net.probability('syncope')
net.probability('rale')
net.probability('snore')
print net.prob_symptoms(['worry'])