-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnaivebayes.py
96 lines (79 loc) · 2.74 KB
/
naivebayes.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
"""
Author: Alex Lederer
Adapted from: logreg.py by Colin Swan
Description: Multinomial or Guassian Naive Bayes based classification of Yelp Reviews,
categorizing reviews into seasons.
"""
import json
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.feature_selection import RFE
from sklearn import metrics
import warnings
class NaiveBayes:
def __init__(self, reviews, basis):
corpus = []
labels = []
for review in reviews:
corpus += [(review[1]["text"])]
labels += [(review[0])]
# setting variables for the object.
self.corpus = corpus
self.labels = labels
self.reviews = reviews
self.basis = basis
#print self.corpus[0]
#print self.labels[0]
self.train() # calling this object's train method.
def train(self):
self.vectorizer = TfidfVectorizer(min_df = 1)
X = self.vectorizer.fit_transform(self.corpus)
#print "created x"
x_names = self.vectorizer.get_feature_names()
#print "created x names"
y = self.labels
#print "created y"
if (self.basis == "multinomial"):
model = MultinomialNB()
elif (self.basis == "gaussian"):
model = GaussianNB()
# Training the model
# supresses log(0) warnings (which occur when some of the classes are not represented at all--i.e. they have a count of zero).
with warnings.catch_warnings():
warnings.simplefilter("ignore")
#print "about to fit model"
model.fit(X, y)
#print "model fitted"
self.model = model
#Classify collection of sentences in parsed_review_sentences (which should be
#a list of parsed/tokenized sentences for a single review). Return the
#predicted season for the collection of sentences.
def classify(self, parsed_review_sentences):
test_corpus = []
for sentence in parsed_review_sentences:
test_corpus += [("", sentence)]
self.classify_all(test_corpus)
def classify_all(self, all_test_data):
test_corpus = []
y = []
for review in all_test_data:
test_corpus += [review[1]['text']]
y += [review[0]]
#Used transform instead of fit_transform
#for test data so number of features will match
X = self.vectorizer.transform(test_corpus)
results = self.model.predict(X)
return results
#Work in progress, may be able to use RFE
#to determine most useful words for classifcation
def vocabulary(self, all_test_data):
test_corpus = []
y = []
for review in all_test_data:
test_corpus += [review[1]['text']]
y += [review[0]]
X = self.vectorizer.transform(test_corpus)
results = self.model.predict(X)
selector = RFE(self.model, 100, 1)
sel_result = selector.fit(X, y)
print(selector.transform(X))