-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathText_Classifier.py
274 lines (221 loc) · 8.13 KB
/
Text_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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import pandas as pd
import json
from helpers import customArgmax, shuffleArray, splitDataframe, splitArr
from Pre_Processor import PreProcess
import sys
from custom_exceptions import RequiredFieldsNotFoundError
class TextClassifier:
"""
Class to classify text using Naive Bayes algorithm
Attributes
----------
dataset: pandas.DataFrame
"""
def __init__(self):
self.dataset = pd.DataFrame()
self.summaryByClass = dict()
self.noOfSamples = 0
self.DEFAULT_PROBABILITY = 1
self.preProcessor = PreProcess()
def loadDatasetJson(self, jsonFile):
"""
Loads the data from a json file into a pandas DataFrame
Parameters
----------
jsonFile: str
Json file containing the dataset, an array of data-samples with the following structure:
{
"sentence": "some sentence",
"category": "positive/negative"
}
Returns
-------
None
if the dataset is loaded successfully.
Error: Exception
if error occurs.
"""
try:
data = json.load(open(jsonFile))
data = self.preProcessor.preProcess(data)
train, test = splitArr(data, 4/5)
self.testing = test
self.training = train
data = shuffleArray(train)
self.dataset = pd.DataFrame(data)
self.noOfSamples = self.dataset.shape[0]
except Exception as e:
raise e
def loadDatasetCsv(self, csvFile):
"""
Loads the data from a json file into a pandas DataFrame
Parameters
----------
jsonFile: str
Json file containing the dataset, an array of data-samples with the following structure:
{
"sentence": "some sentence",
"category": "positive/negative"
}
Returns
-------
None
if the dataset is loaded successfully.
Error: Exception
if error occurs.
"""
try:
data = pd.read_csv(csvFile, encoding="ISO-8859-1")
if ("sentence" not in data.columns) or ("category" not in data.columns):
raise RequiredFieldsNotFoundError
processedData = self.preProcessor.preProcess(data)
self.dataset = processedData
self.training, self.testing = splitDataframe(self.dataset, 3/4)
self.noOfSamples = self.training.shape[0]
except Exception as e:
raise e
def _describeByClass(self, dataset: pd.DataFrame):
"""
Separates data by classname and computes the mean and std of each feature in each class.
Parameters
----------
dataset: pd.DataFrame
Dataframe of features and class values
Returns
-------
summary: Dict[str: List[mean, std]]
Map from class to a list of mean and std values of each feature.
"""
categories = set(dataset["category"])
summary = dict()
for category in categories:
samples = dataset[dataset["category"] == category]
# print(samples)
samplesCount = samples.shape[0]
tokenProbabilities = dict()
for tokenList in samples["tokens"]:
# print(tokenList)
for token in tokenList:
if token not in tokenProbabilities:
tokenProbabilities[token] = 0
else:
tokenProbabilities[token] += 1
for token in tokenProbabilities:
tokenProbabilities[token] /= samplesCount
summary[category] = tokenProbabilities
for category in categories:
s = summary[category]
for token in s:
s[token] += self.DEFAULT_PROBABILITY
# print()
# print(summary)
return summary
def train(self):
"""
Computes the mean and std of each feature in each class and stores the results in self.summaryByClass
"""
self.summaryByClass = self._describeByClass(self.training)
print(f"Trained {self.training.shape[0]} samples")
def computeProbabilities(self, tokens: list):
"""
Computes the probability that the given tokens belong to each class.
Attributes
----------
tokens: list
List of processed tokens
Returns
-------
probabilities: Dict[str, float]
probability of each class/category.
"""
if len(tokens) == 0:
return None
categories = set(self.training["category"])
probabilities = dict()
for category in categories:
samples = self.training[self.training["category"] == category]
samplesCount = samples.shape[0]
priorProbability = samplesCount/self.noOfSamples
likelihood = 1
for token in tokens:
if token in self.summaryByClass[category]:
p = self.summaryByClass[category][token]
else:
p = 1
# print(category, token, p, priorProbability)
likelihood *= p
probabilities[category] = p * priorProbability
# print(probabilities[category])
return probabilities
def predict(self, sentence: str):
"""
Predicts the category of the given sentence.
Attributes
----------
sentence: str
Returns
-------
Tuple[str, Dict[str, float]]
Tuple containing the predicted category and probabilities of all categories.
"""
tokens = self.preProcessor.processString(sentence)
# print(self.summaryByClass)
probabilities = self.computeProbabilities(tokens)
# print(probabilities)
if probabilities == None:
return None
return customArgmax(probabilities), probabilities
def predictByTokens(self, tokens):
"""
Predicts the category of the given tokens of a sentence.
Attributes
----------
tokens: List[str]
Returns
-------
Tuple[str, Dict[str, float]]
Tuple containing the predicted category and probabilities of all categories.
"""
probabilities = self.computeProbabilities(tokens)
# print(probabilities)
return customArgmax(probabilities), probabilities
def Test(self):
"""
Tests the model agaist the part of a dataset and compute the accuracy.
Attributes
----------
Returns
-------
accuracy: float
"""
correct = 0
total = 0
total = self.testing.shape[0]
if total <= 0:
return
testingProgress = 0
testedSamples = 0
nonEmptyTokens = 0
tokensColumn = self.testing["tokens"]
# print(self.testing.head(10))
# print(self.testing.index.values)
for i in self.testing.index.values:
testingProgress = (testedSamples*100)/total
print(
f"Testing {round(testingProgress, 3)}% done {'.-'*(int(testingProgress/5)+1)}", end='\r')
sys.stdout.flush()
tokens = tokensColumn[i]
# print(tokens)
if len(tokens) == 0:
continue
prediction = self.predictByTokens(tokens)
if prediction[0] == self.testing["category"][i]:
correct += 1
nonEmptyTokens += 1
testedSamples += 1
print()
print(f"Tested: {total} samples.")
# print(correct, total, nonEmptyTokens)
accuracy = max(correct*100/total, correct*100/nonEmptyTokens)
print(f"Accuracy: {accuracy}")
return accuracy