-
Notifications
You must be signed in to change notification settings - Fork 0
/
subjectivity_NB.py
168 lines (92 loc) · 3.39 KB
/
subjectivity_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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env python
# coding: utf-8
# ### Welcome to your notebook
#
# Learn how to write your own cells containing Markdown text and Python code.
# In[1]:
# If you want to plot graphics in your notebook, keep this %matplotlib command here before your imports
# %matplotlib notebook
# Import some necessary modules
import time
from collections import Counter, defaultdict
from random import shuffle
import nltk
import numpy as np
from nltk.corpus import stopwords
from nltk.corpus import subjectivity as sub
from nltk.stem import WordNetLemmatizer
# In[ ]:
# In[46]:
def divide_sets(labeled_sents):
shuffle(labeled_sents)
ratio = int(len(labeled_sents) * 0.8)
train, test = labeled_sents[:ratio], labeled_sents[ratio:]
return train, test
# In[91]:
labeled_sents = [(sent, label) for label in sub.categories() for sent in sub.sents(categories=label)]
trainset, testset = divide_sets(labeled_sents)
# In[92]:
print(trainset[0])
print(testset[0])
# In[93]:
lemtzer = WordNetLemmatizer()
stopws = stopwords.words('english')
fd = nltk.FreqDist(lemtzer.lemmatize(w) for sent, label in trainset for w in sent
if w.isalnum() and w not in stopws)
ftwords = list(fd)[:500]
def sent2ft(sent):
features = {}
lemmasent = [lemtzer.lemmatize(w.lower()) for w in sent]
for w in ftwords:
features['contains({})'.format(w)] = (w in lemmasent)
return features
def data2ftset(sentset):
return [(sent2ft(sent), label) for sent, label in sentset]
# In[94]:
print(ftwords[:10])
# In[95]:
train_ftset, test_ftset = data2ftset(trainset), data2ftset(testset)
# Transform the data (the tokenized sentences) into classifier recognizable formats, i.e. the features.
#
# The feature here is whether the sentence contains each of the featured words (parameter ``ftwords``), which are picked from the 500 most frequent non-stop words in the training set.
# In[96]:
train_ftset[0]
# In[ ]:
# In[75]:
# In[131]:
clfNB = nltk.NaiveBayesClassifier.train(train_ftset)
print('NB Accuracy: {:4.2f}'.format(nltk.classify.accuracy(clfNB, test_ftset)))
clfNB.show_most_informative_features(20)
# NBResults()
# In[132]:
def show_errcases(n_errcases, classifier, test_set):
errlst, i = [], 0
while len(errlst) <= n_errcases: # Get 10 wrongly classified sentences
sent, goldlabel = test_set[i]
sentft = sent2ft(sent)
testlabel = classifier.classify(sentft)
if testlabel != goldlabel:
errlst.append([testlabel, sent, sentft])
i += 1
print('%s wrongly classified instances:' % n_errcases)
print()
for wronglabel, sent, sentft in errlst:
print(sent)
print('Wrongly classified as: %s' % wronglabel)
informative_fts = [(ft, sentft[ft]) for ft in sentft if sentft[ft] == True]
print('Informative features:', informative_fts)
print()
show_errcases(10, clfNB, testset)
# In[133]:
def classifier_label_list(classifier, test_ftset):
testlst, goldlst = [], []
for ft, lb in test_ftset:
testlst.append(classifier.classify(ft))
goldlst.append(lb)
return testlst, goldlst
def show_cm(classifier, test_ftset):
gold, test = classifier_label_list(classifier, test_ftset)
cm = nltk.ConfusionMatrix(gold, test)
print(cm.pretty_format(sort_by_count=True, show_percents=True))
show_cm(clfNB, test_ftset)
# In[ ]: