-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassifier.py
186 lines (131 loc) · 6.54 KB
/
classifier.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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import numpy as np
import re
import nltk.sentiment.vader as vd
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from feature_selection import feature_selection
class classifier:
def __init__(self, features):
self.features = features
self.feature_ops = feature_selection()
"""
Preprocesses sentences within the df by:
- lowercasing
- removing punctuation
- replacing some words
- removing stop words
- stemming
Returns: dataframe
"""
def pre_process_sentences(self, df):
for sentence in df["Phrase"]:
# lowercase all phrases
lower_sentence = sentence.lower()
# remove punctuation
rm_punc_sentence = re.sub(r'[^\w\s]','',lower_sentence)
# remove numbers
rm_num_sentence = re.sub(r'[0-9]', '', rm_punc_sentence)
# replace some remainders of words with the full word
repl_sentence = rm_num_sentence.replace("nt", "not")
repl_sentence = rm_num_sentence.replace("s", "is")
repl_sentence = rm_num_sentence.replace("re", "are")
repl_sentence = rm_num_sentence.replace("ve", "have")
repl_sentence = rm_num_sentence.replace("wo", "will")
repl_sentence = rm_num_sentence.replace("ca", "can")
# tokenize sentences
sentence_tokens = word_tokenize(repl_sentence)
# remove stop words
# Reference: https://stackoverflow.com/questions/5486337/how-to-remove-stop-words-using-nltk-or-python
sentence_tokens = [word for word in sentence_tokens if (word not in stopwords.words('english')) or (word in vd.VaderConstants.NEGATE) or (word in vd.VaderConstants.BOOSTER_DICT)]
if self.features == 'features_word_type':
sentence_tokens = self.feature_ops.tag(sentence_tokens)
# stemming
ps = PorterStemmer()
stemmed_sentence_tokens = [ps.stem(word) for word in sentence_tokens if (word not in vd.VaderConstants.NEGATE) or (word not in vd.VaderConstants.BOOSTER_DICT)]
rep_sentence = ' '.join(stemmed_sentence_tokens)
df['Phrase'] = df['Phrase'].replace([sentence], rep_sentence)
print("Preprocessed sentences.")
return df
"""
Create a bag of words model
Returns: dictionary of each unique word and the count for that
word in each sentiment class.
"""
def create_bag_of_words(self, df, number_classes):
print("Creating bag of words.")
# Create a bag of words with counts for each class
all_words_and_counts = dict()
for sentence in df["Phrase"]:
# # Reference: https://stackabuse.com/python-for-nlp-creating-bag-of-words-model-from-scratch/
# tokenize sentences
sentence_tokens = word_tokenize(sentence)
for token in sentence_tokens:
# get sentiment value of word
sent_value = df[df['Phrase']==sentence]['Sentiment'].values[0]
# Reference: https://thispointer.com/python-dictionary-with-multiple-values-per-key/
if token not in all_words_and_counts.keys(): # create a key with token if it doesn't exist in bag of words
all_words_and_counts[token] = list()
# initialise list with values 0
all_words_and_counts[token] = [0] * number_classes # -> [neg, sw_neg, neu, sw_pos, pos]
all_words_and_counts[token][sent_value] = 1
else:
# increment the count value
all_words_and_counts[token][sent_value] += 1
print("Created bag of words.")
return all_words_and_counts
def compute_total_sent_counts(self, df, number_classes):
# get count of sentiments
count_list = list()
for class_no in range(number_classes):
count = len(df.loc[df['Sentiment'] == class_no, ['Phrase']])
count_list.append(count)
return count_list
"""
Returns: prior probability list for each class
"""
def compute_prior_probability(self, total_sentence_no, count_list, number_classes):
class_prior_probs = list()
for class_no in range(number_classes):
prior_prob = count_list[class_no] / total_sentence_no
class_prior_probs.append(prior_prob)
return class_prior_probs
"""
Compute likelihood for 5 sentiment values for a token
Returns: likelihood list of the word for each class
"""
def compute_likelihood_for_feature(self, token, sent_count_list, all_words_and_counts_dict, number_classes):
# list --> [neg, sw_neg, neu, sw_pos, pos] if 5 class
# list --> [neg, neu, pos] if 3 class
token_dict_vals = all_words_and_counts_dict[token]
likelihood_list = list()
for class_no in range(number_classes):
count = token_dict_vals[class_no]
class_likelihood = count / sent_count_list[class_no]
likelihood_list.append(class_likelihood)
return likelihood_list
"""
Returns: index of sentiment class with the highest value
"""
def compute_posterior_probability(self, sentence, sentence_lh_dict, class_prior_prob_list, number_classes):
all_post_probs = list()
for class_no in range(number_classes):
class_lh_product = np.prod(np.array(sentence_lh_dict[class_no]), where=np.array(sentence_lh_dict[class_no])>0)
class_prior_prob = class_prior_prob_list[class_no]
all_post_probs.append(class_lh_product * class_prior_prob)
if self.features == 'features_word_type' or self.features == 'features_tfidf':
neg_add_val = self.feature_ops.negation(sentence)
intense_add_val = self.feature_ops.intensifier(sentence)
if neg_add_val != None:
all_post_probs[0] += neg_add_val
if number_classes == 5:
if neg_add_val != None:
all_post_probs[1] += neg_add_val
if intense_add_val != None:
all_post_probs[3] += intense_add_val
all_post_probs[4] += intense_add_val
if number_classes == 3:
if intense_add_val != None:
all_post_probs[2] += intense_add_val
highest_prob_index = np.argmax(all_post_probs) # returns index of highest probability score
return highest_prob_index