-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN_Gram.py
More file actions
172 lines (124 loc) · 5.47 KB
/
Copy pathN_Gram.py
File metadata and controls
172 lines (124 loc) · 5.47 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
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
from nltk.tokenize import word_tokenize
import readData as rd
import numpy as np
import csv
class N_Gram(object):
def __init__(self, traindata, obj_ui):
self.tweets, self.labels = traindata['tweet'], traindata['Sentiment']
self.pos_tweets, self.neg_tweets = self.labels.value_counts()[4], self.labels.value_counts()[0]
self.total_tweets = self.pos_tweets + self.neg_tweets
self.PBA_pos = dict()
self.PBA_neg = dict()
self.PA_pos = self.pos_tweets / self.total_tweets
self.PA_neg = self.neg_tweets / self.total_tweets
self.ui = obj_ui
# ========================================================================================
def train(self):
print('POSITIVE: ', self.pos_tweets, ' NEGATIVE: ', self.neg_tweets)
self.calc_PBA()
return self.PBA_pos, self.PBA_neg, self.pos_tweets, self.neg_tweets
# ========================================================================================
def calc_PBA(self):
for i in range(self.total_tweets):
words = word_tokenize(self.tweets[i])
n2gram = list()
for j in range(len(words) - 1):
n2gram.append((words[j] + words[j + 1]))
for word in n2gram:
if self.labels[i] == 4:
self.PBA_pos[word] = self.PBA_pos.get(word, 1) + 1
else:
self.PBA_neg[word] = self.PBA_neg.get(word, 1) + 1
for word in self.PBA_pos:
self.PBA_pos[word] = self.PBA_pos[word] / self.pos_tweets
for word in self.PBA_neg:
self.PBA_neg[word] = self.PBA_neg[word] / self.neg_tweets
# ========================================================================================
def classify(self, tweet):
p_pos = 1
p_neg = 1
words = word_tokenize(tweet)
n2gram = list()
for i in range(len(words) - 1):
n2gram.append((words[i] + words[i + 1]))
for word in n2gram:
p_pos *= self.PBA_pos.get(word, 1 / self.pos_tweets)
p_neg *= self.PBA_neg.get(word, 1 / self.neg_tweets)
p_pos *= self.PA_pos
p_neg *= self.PA_neg
# messsage = 'Tweet:' + tweet + '====> pos/neg: ' + str(p_pos / p_neg) + '\t--->' + str(p_pos >= p_neg)
# self.ui.insert_msg_box(messsage)
if p_pos >= p_neg:
messsage = 'Tweet:' + tweet + '====> pos/neg: ' + str(p_pos / p_neg) + '\t--->' + 'Positive'
self.ui.insert_msg_box(messsage)
return 4
else:
messsage = 'Tweet:' + tweet + '====> pos/neg: ' + str(p_pos / p_neg) + '\t--->' + 'Negative'
self.ui.insert_msg_box(messsage)
return 0
# ========================================================================================
def predict(self, test_data):
result = dict()
for (i, tweet) in enumerate(test_data):
result[i] = int(self.classify(tweet))
return result
# ========================================================================================
def metrics(labels, predictions, obj_ui):
true_pos, true_neg, false_pos, false_neg = 0, 0, 0, 0
for i in range(len(labels)):
true_pos += int(labels[i] == 4 and predictions[i] == 4)
true_neg += int(labels[i] == 0 and predictions[i] == 0)
false_pos += int(labels[i] == 0 and predictions[i] == 4)
false_neg += int(labels[i] == 4 and predictions[i] == 0)
print(true_pos)
print(true_neg)
print(false_pos)
print(false_neg)
try:
precision = true_pos / (true_pos + false_pos)
recall = true_pos / (true_pos + false_neg)
print('Precall')
print(precision, ',', recall)
fscore = 2 * precision * recall / (precision + recall)
accuracy = (true_pos + true_neg) / (true_pos + true_neg + false_pos + false_neg)
except ZeroDivisionError:
print('Zero Division Error')
print("Precision: ", precision)
print("Recall: ", recall)
print("F-score: ", fscore)
print("Accuracy: ", accuracy)
obj_ui.clean_msg_box()
obj_ui.insert_msg_box('\nPrecision: ' + str(precision))
obj_ui.insert_msg_box("\nRecall: " + str(recall))
obj_ui.insert_msg_box("\nF-Score: " + str(fscore))
obj_ui.insert_msg_box("\nAccuracy: " + str(accuracy))
def train_ngram(filename, outputfilename, obj_ui):
filename = filename + '.csv'
count_txt = outputfilename + '.txt'
model_csv = outputfilename + '.csv'
data = rd.read_and_clean_data(filename)
total_tweets = data.shape[0]
trainIndex, testIndex = list(), list()
for i in range(total_tweets):
if np.random.uniform(0, 1) < 0.9:
trainIndex += [i]
else:
testIndex += [i]
trainData = data.loc[trainIndex]
testData = data.loc[testIndex]
trainData.reset_index(inplace=True)
trainData.drop(['index'], axis=1, inplace=True)
testData.reset_index(inplace=True)
testData.drop(['index'], axis=1, inplace=True)
ngram = N_Gram(data, obj_ui)
PBA_pos, PBA_neg, pos_tweets, neg_tweets = ngram.train()
tweets_file = open(count_txt, 'w')
tweets_file.write((str(pos_tweets) + '\n'))
tweets_file.write((str(neg_tweets) + '\n'))
with open(model_csv, 'w') as PBA_file:
w = csv.writer(PBA_file, lineterminator='\n')
w.writerows(PBA_pos.items())
w.writerow('$')
w.writerows(PBA_neg.items())
preds = ngram.predict(testData['tweet'])
metrics(testData['Sentiment'], preds, obj_ui)