-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassifier.py
More file actions
59 lines (45 loc) · 1.68 KB
/
Classifier.py
File metadata and controls
59 lines (45 loc) · 1.68 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
#Implementation of Email spam Classifier Using Naive Bayes
import os
import io
#import tkinter as tk
from pandas import DataFrame
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
#root=tk.Tk()
def readFiles(path):
for root, dirnames, filenames in os.walk(path):
for filename in filenames:
path = os.path.join(root, filename)
inBody = False
lines = []
f = io.open(path, 'r', encoding='latin1')
for line in f:
if inBody:
lines.append(line)
elif line == '\n':
inBody = True
f.close()
message = '\n'.join(lines)
yield path, message
def dataFrameFromDirectory(path, classification):
rows = []
index = []
for filename, message in readFiles(path):
rows.append({'message': message, 'class': classification})
index.append(filename)
return DataFrame(rows, index=index)
def checkingmail(example):
example_counts = vectorizer.transform(example)
predictions = classifier.predict(example_counts)
return predictions
data = DataFrame({'message': [], 'class': []})
data = data.append(dataFrameFromDirectory('F:/project/emails/spam', 'spam'))
data = data.append(dataFrameFromDirectory('F:/project/emails/ham', 'ham'))
#print(data.describe())
vectorizer = CountVectorizer()
counts = vectorizer.fit_transform(data['message'].values)
#print(vectorizer.get_feature_names())
print(counts.toarray())
classifier = MultinomialNB()
targets = data['class'].values
classifier.fit(counts, targets)