-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnb.py
executable file
·140 lines (113 loc) · 4.29 KB
/
nb.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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import sys
import math
import numpy
class NaiveBayes:
def __init__(self):
print '__init__'
def readInput(self, file_name):
vocabulary = set()
dataset = {}
self.classes = {}
prior = {}
docs = 0
f = open(file_name, 'r')
while True:
line = f.readline()
if line.strip() == '':
break
docs += 1
term = line.split(' ')
lclass = term[0]
if not self.classes.get(lclass):
dataset[lclass]={}
self.classes[lclass]=1
else:
self.classes[lclass] += 1
for wordc in term[1:]:
word, count = wordc.split(':')
count = int(count)
if not word in dataset[lclass].keys():
dataset[lclass][word] = count
else:
dataset[lclass][word] += count
vocabulary.add(word)
for cl,nc in self.classes.iteritems():
prior[cl] = (nc+0.0)/docs
print 'vocab len: ', len(vocabulary)
print 'number of documents: ', docs
print 'classes: ', self.classes
print 'prior: ', prior, '\n\n'
for i,j in dataset.iteritems():
#print i, j
pass
return vocabulary, dataset, prior, docs
def trainClassifier(self, file_name):
vocab, dataset, prior, N = self.readInput(file_name)
print len(vocab), len(dataset), prior, N
condProb = {}
for classes in dataset.keys():
condProb[classes] = {}
for cl, words in dataset.iteritems():
denom = 0.0
for t in vocab:
if words.get(t):
denom += words[t] + 1
else:
denom += 1
for t in vocab:
if words.get(t):
condProb[cl][t] = (words[t] + 1.0) / denom
else:
condProb[cl][t] = 1.0 / denom
#print cl
#for cl, cprob in condProb.iteritems():
#print word, freq
return vocab, prior, condProb
def runClassifier(self, v,p,cp,file_name):
with open(file_name,'r') as f:
testWords = {}
classified = {}
for document in f:
document = document.strip()
classified[document] = {'actual': 0, 'predicted': 0}
terms = document.split()
classified[document]['actual'] = int(terms[0])
score = {}
for cl, ignore in self.classes.iteritems():
intCl = int(cl)
score[intCl] = math.log(p[cl])
for term in terms[1:]:
word, freq = term.split(':')
if word in v:
score[intCl] += math.log(cp[cl][word])*int(freq)
argmax = 0
temp = -float('inf')
for key in score:
if (score[key] > temp):
temp = score[key]
argmax = key
#argmax = score.index(max(score))
classified[document]['predicted'] = argmax
#print classified[document]
correct = 0.0
false = 0.0
for document in classified:
if classified[document]['actual'] == classified[document]['predicted']:
correct += 1
else:
false += 1
print correct
print false
cf = numpy.zeroes(len(self.classes),len(self.classes))
for doc in classified:
if __name__ == '__main__':
#if len(sys.argv) != 2:
# print("Format:python NaiveBayes.py")
# sys.exit()
#name = sys.argv[1]
training_file= "train_email.txt"
testing_file = "test_email.txt"
nb = NaiveBayes()
v,p,cp = nb.trainClassifier(training_file) #Train the classifier
nb.runClassifier(v,p,cp,testing_file) # Run the classifier
nb.findMLW(v,p,cp,training_file)