-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNaiveBayes.js
215 lines (178 loc) · 6.21 KB
/
NaiveBayes.js
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
class NaiveBayes {
constructor() {
this.total_samples = 0;
this.total_tokens = 0;
this.subjects = {};
this.tokens = {};
this.stopWords = null;
this.loading(true);
if (!localStorage.getItem('model')) {
fetch('./dataset/stopWords.json')
.then(res => res.json())
.then(data => {
this.stopWords = data;
this.cache();
this.loading(false);
});
} else {
this.loading(false);
}
}
loading(show) {
const loadingElement = document.getElementById('loading');
if (show) {
loadingElement.classList.remove('d-none');
loadingElement.classList.add('d-flex');
} else {
loadingElement.classList.remove('d-flex');
loadingElement.classList.add('d-none');
}
}
cache() {
const json = {
total_samples: this.total_samples,
total_tokens: this.total_tokens,
subjects: this.subjects,
tokens: this.tokens,
stopWords: this.stopWords
};
localStorage.setItem('model', JSON.stringify(json));
}
classify(str) {
if (this.total_samples === 0) {
return {};
}
const tokens = this.tokenize(str);
const scores = {};
let total_score = 0;
for (const subject in this.subjects) {
const subject_data = this.subjects[subject];
subject_data.prior_value = Math.log(subject_data.count_samples / this.total_samples);
this.subjects[subject] = subject_data;
scores[subject] = 0;
for (const token of tokens) {
const count = this.tokens[token]?.[subject] || 0;
scores[subject] += Math.log((count + 1) / (subject_data.count_tokens + this.total_tokens));
}
scores[subject] = subject_data.prior_value + scores[subject];
total_score += scores[subject];
}
const min = Math.min(...Object.values(scores));
let sum = 0;
for (const subject in scores) {
scores[subject] = Math.exp(scores[subject] - min);
sum += scores[subject];
}
if (sum > 0) {
for (const subject in scores) {
scores[subject] = scores[subject] / sum;
}
} else {
const numCategories = Object.keys(scores).length;
const defaultProbability = 1 / numCategories;
const totalDefaultProbability = defaultProbability * numCategories;
for (const subject in scores) {
scores[subject] = defaultProbability;
}
const remainingProbability = 1 - totalDefaultProbability;
const additionalProbability = remainingProbability / numCategories;
for (const subject in scores) {
scores[subject] += additionalProbability;
}
}
// Sort scores in descending order
const sortedScores = Object.entries(scores).sort((a, b) => b[1] - a[1]);
const result = {};
for (const [subject, score] of sortedScores) {
result[subject] = score;
}
return result;
}
tokenize(str) {
str = this.removeStopWords(str);
str = this.clean(str);
const matches = str.match(/\w+/g);
return matches ? matches : [];
}
static async loadModel(filename) {
if (localStorage.getItem("model")) {
const modelData = JSON.parse(localStorage.getItem("model"));
const naiveBayes = new NaiveBayes();
naiveBayes.total_samples = modelData.total_samples;
naiveBayes.total_tokens = modelData.total_tokens;
naiveBayes.subjects = modelData.subjects;
naiveBayes.tokens = modelData.tokens;
naiveBayes.stopWords = modelData.stopWords;
return naiveBayes;
}
try {
const response = await fetch(filename);
if (!response.ok) {
throw new Error('Failed to fetch the model data');
}
const modelData = await response.json();
if (modelData) {
const naiveBayes = new NaiveBayes();
naiveBayes.total_samples = modelData.total_samples;
naiveBayes.total_tokens = modelData.total_tokens;
naiveBayes.subjects = modelData.subjects;
naiveBayes.tokens = modelData.tokens;
return naiveBayes;
} else {
throw new Error('Failed to load the model from JSON.');
}
} catch (error) {
console.error(error);
}
}
removeStopWords(str) {
str = ' ' + str + ' ';
const words = str.split(' ');
for (let c = 0; c < words.length; c++) {
for (let i = 0; i < this.stopWords.length; i++) {
if (words[c].toLowerCase() === this.stopWords[i]) {
str = str.replace(' ' + words[c] + ' ', ' ');
break;
}
}
}
return str.trim();
}
clean(str) {
str = str.toLowerCase();
// Remove accents
str = this.removeAcentos(str);
// Remove emojis
str = str.replace(/[\u{1F600}-\u{1F64F}]/gu, '');
// Remove links
str = str.replace(/https?:\/\/\S+/g, '');
// Remove mentions with "#" or "@"
str = str.replace(/[#@]\S+/g, '');
// Remove punctuation
str = str.replace(/[^\w\s]/gu, '');
return str;
}
removeAcentos(str) {
const acentos = {
'á': 'a',
'à': 'a',
'ã': 'a',
'â': 'a',
'é': 'e',
'è': 'e',
'ê': 'e',
'í': 'i',
'ì': 'i',
'î': 'i',
'ó': 'o',
'ò': 'o',
'õ': 'o',
'ô': 'o',
'ú': 'u',
'ù': 'u',
'û': 'u',
'ç': 'c'
};
return str.replace(/[áàãâéèêíìîóòõôúùûç]/g, match => acentos[match] || match);
}
}