-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPerceptronModel.java
More file actions
334 lines (303 loc) · 8.99 KB
/
PerceptronModel.java
File metadata and controls
334 lines (303 loc) · 8.99 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map.Entry;
/**
* @author Ambar
*
*/
public class PerceptronModel {
private static final String SPAM_CLASS = "spam";
private static final String HAM_CLASS = "ham";
private static final int SPAM = -1;
private static final int HAM = -2;
private static final double HAM_OUTPUT = -1;
private static final double SPAM_OUTPUT = 1;
private static final String CLASS = "CLASS";
private static final String SEPERATOR = " ";
/* bias weight w0*/
private double biasWeight = 0.0;
public static int iterations; /* Iterations for convergence */
public static double eta; /* This is the learning rate for perceptron */
/* Weights will be of size of vocab. */
HashMap<String, Double> weights = new HashMap<String, Double>();
/* If we are using the stop words list for optimization */
boolean usingStopWords = false;
LinkedHashSet<String> stopWords = new LinkedHashSet<String>();
LinkedHashSet<String> vocab = new LinkedHashSet<String>();
/* Holds the entire example and feature matrix. */
ArrayList<HashMap<String, Integer>> data = new ArrayList<HashMap<String, Integer>>();
/**
* Constructor when not using stopwords
*
* @throws IOException
*/
public PerceptronModel(String trainingHamDir, String trainingSpamDir)
throws IOException {
createVocab(trainingHamDir, trainingSpamDir);
readHamDir(trainingHamDir);
readSpamDir(trainingSpamDir);
}
/**
* Constructor when not using stopwords
*
* @throws IOException
*/
public PerceptronModel(String trainingHamDir, String trainingSpamDir,
String stopWords) throws IOException {
this.usingStopWords = true;
readStopWords(stopWords);
createVocab(trainingHamDir, trainingSpamDir);
readHamDir(trainingHamDir);
readSpamDir(trainingSpamDir);
}
/**
* Reads the stop words
*
* @param stopWords
* @throws IOException
*/
private void readStopWords(String stopWords) throws IOException {
File file = new File(stopWords);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
this.stopWords.add(line);
}
br.close();
}
/**
* Reads the SPAM Directory.
*
* @throws IOException
*/
private void readSpamDir(String trainingSpamDir) throws IOException {
File spamDir = new File(trainingSpamDir);
String line = null;
for (File sFile : spamDir.listFiles()) {
HashMap<String, Integer> example = new HashMap<String, Integer>();
FileReader fr = new FileReader(sFile);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String list[] = line.split(SEPERATOR);
for (String word : list) {
if (usingStopWords && (stopWords.contains(word))) {
// Do Nothing
} else {
if (!example.containsKey(word)) {
example.put(word, 1);
} else {
example.put(word, example.get(word) + 1);
}
}
}
}
br.close();
example.put(CLASS, SPAM);
data.add(example);
}
}
/**
* Reads the HAM Directory.
*
* @throws IOException
*/
private void readHamDir(String trainingHamDir) throws IOException {
File hamDir = new File(trainingHamDir);
String line = null;
for (File hFile : hamDir.listFiles()) {
HashMap<String, Integer> example = new HashMap<String, Integer>();
FileReader fr = new FileReader(hFile);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String list[] = line.split(SEPERATOR);
for (String word : list) {
if (usingStopWords && stopWords.contains(word)) {
// Do Nothing
} else {
if (!example.containsKey(word)) {
example.put(word, 1);
} else {
example.put(word, example.get(word) + 1);
}
}
}
}
br.close();
example.put(CLASS, HAM);
data.add(example);
}
}
/**
* Creates the vocabulary for entire model
*
* @param trainingHamDir
* @param trainingSpamDir
* @throws IOException
*/
private void createVocab(String trainingHamDir, String trainingSpamDir)
throws IOException {
File hamDir = new File(trainingHamDir);
String line = null;
for (File hFile : hamDir.listFiles()) {
FileReader fr = new FileReader(hFile);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String list[] = line.split(SEPERATOR);
for (String word : list) {
if (usingStopWords && stopWords.contains(word)) {
// Do Nothing
} else {
this.vocab.add(word);
}
}
}
br.close();
}
File spamDir = new File(trainingSpamDir);
for (File sFile : spamDir.listFiles()) {
FileReader fr = new FileReader(sFile);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String list[] = line.split(SEPERATOR);
for (String word : list) {
if (usingStopWords && (stopWords.contains(word))) {
// Do Nothing
} else {
vocab.add(word);
}
}
}
br.close();
}
}
/**
* This Method trains the Perceptron Model
*/
public void trainPerceptron() {
double actualOutput = 0, predictedOutput = 0;
for (String word : vocab) {
weights.put(word, (2*Math.random()) - 1);
}
for (int j = 0; j < iterations; j++) {
for (int i = 0; i < data.size(); i++) {
HashMap<String, Integer> example = data.get(i);
actualOutput = example.get(CLASS) == HAM ? HAM_OUTPUT : SPAM_OUTPUT;
predictedOutput = predictOutput(example);
double error = (actualOutput - predictedOutput);
if (error != 0) {
for (Entry<String, Integer> entry : example.entrySet()) {
if (!entry.getKey().equalsIgnoreCase(CLASS)) {
double oldWeight = weights.get(entry.getKey());
double newWeight = oldWeight
+ (eta * error * entry.getValue());
weights.put(entry.getKey(), newWeight);
}
}
biasWeight = biasWeight + eta * error;
}
}
}
}
/**
* This method predicts the output
*
* @param example
* @return
*/
private double predictOutput(HashMap<String, Integer> example) {
double sumOfWeights = biasWeight;
for (Entry<String, Integer> entry : example.entrySet()) {
String feature = entry.getKey();
int occerence = entry.getValue();
// System.out.println(feature);
if (weights.get(entry.getKey()) != null)
sumOfWeights = sumOfWeights + weights.get(feature) * occerence;
}
return sumOfWeights > 0 ? SPAM_OUTPUT : HAM_OUTPUT;
}
/**
* Calculate the accuracy of the Model
*
* @throws IOException
*/
public double calculateAccuracy(String testingHamDir, String testingSpamDir)
throws IOException {
File hamDir = new File(testingHamDir);
double hamAccuracy = 0, hamTotal = 0;
double spamAccuracy = 0, spamTotal = 0;
for (File doc : hamDir.listFiles()) {
String result = applyPerceptron(doc, HAM_CLASS);
if (result.equals(HAM_CLASS)) {
hamAccuracy++;
}
hamTotal++;
}
System.out.println("\tAccuracy for Ham Class="
+ (hamAccuracy / hamTotal * 100) + "%");
File spamDir = new File(testingSpamDir);
for (File doc : spamDir.listFiles()) {
String result = applyPerceptron(doc, SPAM_CLASS);
if (result.equals(SPAM_CLASS)) {
spamAccuracy++;
}
spamTotal++;
}
System.out.println("\tAccuracy for Spam Class="
+ (spamAccuracy / spamTotal * 100) + "%");
return ((hamAccuracy + spamAccuracy) / (spamTotal + hamTotal) * 100);
}
/**
* For given document it predicts the output
*
* @throws IOException
*/
private String applyPerceptron(File doc, String spamClass)
throws IOException {
String line = null;
HashMap<String, Integer> example = new HashMap<String, Integer>();
FileReader fr = new FileReader(doc);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String list[] = line.split(SEPERATOR);
for (String word : list) {
if (usingStopWords && (stopWords.contains(word))) {
// Do Nothing
} else {
if (example.containsKey(word)) {
example.put(word, example.get(word) + 1);
} else {
example.put(word, 1);
}
}
}
}
br.close();
return ((predictOutput(example) == SPAM_OUTPUT) ? SPAM_CLASS : HAM_CLASS);
}
/**
* For debugging purpose to print the weights
*
* @param name
*/
@SuppressWarnings("unused")
private void printWeights(String name) {
System.out.println(name + "\n");
try {
PrintWriter writer;
writer = new PrintWriter(name, "UTF-8");
for (Entry<String, Double> entry : weights.entrySet()) {
writer.println(entry.getValue());
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}