-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogisticRegression.java
343 lines (307 loc) · 8.97 KB
/
LogisticRegression.java
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
335
336
337
338
339
340
341
342
343
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;
/**
* @author Ambar
*
*/
public class LogisticRegression {
public static final String SPAM_CLASS = "spam";
public static final String HAM_CLASS = "ham";
public static final String CLASS = "CLASS";
public static final String SEPERATOR = " ";
private static final int SPAM = -1;
private static final int HAM = -2;
public static double eta;
public static double lambda;
public static int iterations;
private int total; /* Total number of documents */
private int nHam; /* Number of HAM documents */
private int nSpam; /* Number of SPAM documents */
ArrayList<String> classes = new ArrayList<String>();
// Prob will be of size of total examples
ArrayList<Double> prob = new ArrayList<Double>();
// Weights will be of size of vocab.
ArrayList<Double> weights = new ArrayList<Double>();
/* If we are using the stop words list for optimization */
boolean usingStopWords = false;
/* DS to hold the data */
LinkedHashSet<String> stopWords = new LinkedHashSet<String>();
LinkedHashSet<String> vocab = new LinkedHashSet<String>();
ArrayList<HashMap<String, Integer>> data = new ArrayList<HashMap<String, Integer>>();
/**
* Constructor when not using stopwords
*
* @throws IOException
*/
public LogisticRegression(String trainingHamDir, String trainingSpamDir)
throws IOException {
createVocab(trainingHamDir, trainingSpamDir);
this.nHam = readHamDir(trainingHamDir);
this.nSpam = readSpamDir(trainingSpamDir);
this.total = nHam + nSpam;
classes.add(HAM_CLASS);
classes.add(SPAM_CLASS);
}
/**
* Constructor when not using stopwords
*
* @throws IOException
*/
public LogisticRegression(String trainingHamDir, String trainingSpamDir,
String stopWords) throws IOException {
this.usingStopWords = true;
readStopWords(stopWords);
createVocab(trainingHamDir, trainingSpamDir);
this.nHam = readHamDir(trainingHamDir);
this.nSpam = readSpamDir(trainingSpamDir);
this.total = nHam + nSpam;
classes.add(HAM_CLASS);
classes.add(SPAM_CLASS);
}
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();
}
}
/**
* 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();
}
/**
* This method trains the model according to the data.
*/
public void trainLR() {
for (int i = 0; i < vocab.size(); i++) {
weights.add(0.0);
}
for (int iter = 0; iter < iterations; iter++) {
for (int i = 0; i < total; i++) {
HashMap<String, Integer> example = data.get(i);
String computedClass = example.get(CLASS) == HAM ? HAM_CLASS
: SPAM_CLASS;
prob.add(compute(example, computedClass));
}
for (int i = 0; i < total; i++) {
HashMap<String, Integer> example = data.get(i);
for (String word : vocab) {
double rowClass = (example.get(CLASS) == HAM) ? 1 : 0;
double delta;
delta = weights.get(i) + example.get(word)
* (rowClass - prob.get(i));
// L2 regularization
double val = weights.get(i)
+ eta
* (-delta - (lambda * weights.get(i) * weights
.get(i)));
weights.set(i, val);
}
}
}
data = null;
}
private Double compute(HashMap<String, Integer> row, String computedClass) {
double prob = weights.get(0);
int i = 0;
for (String word : vocab) {
prob = prob + (weights.get(i++) * ((double) row.get(word)));
}
double result = 1 / ((double) 1 + Math.exp(prob));
if (computedClass.equalsIgnoreCase(SPAM_CLASS)) {
return result;
} else
return (1 - result);
}
/**
* Prints the individual accuracy for HAM and SPAM
*
* @return The overall accuracy.
* @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 = applyLR(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 = applyLR(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);
}
/**
* Predict the class for the given document.
*
* @param hamClass
* @return The predicted class
* @throws IOException
*/
private String applyLR(File doc, String hamClass) throws IOException {
HashMap<String, Integer> row = new HashMap<String, Integer>();
// Adding vocab in row.
for (String word : vocab) {
row.put(word, 0);
}
FileReader fr = new FileReader(doc);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
String[] list = line.split(SEPERATOR);
for (String dw : list) {
if (vocab.contains(dw))
row.put(dw, row.get(dw) + 1);
}
}
br.close();
return (compute(row, HAM_CLASS) > compute(row, SPAM_CLASS)) ? HAM_CLASS
: SPAM_CLASS;
}
/**
* Reads the SPAM Directory.
*
* @throws IOException
*/
private int readSpamDir(String trainingSpamDir) throws IOException {
File spamDir = new File(trainingSpamDir);
int nSpam = 0;
String line = null;
for (File sFile : spamDir.listFiles()) {
HashMap<String, Integer> row = new HashMap<String, Integer>();
// Adding vocab in row.
for (String word : vocab) {
row.put(word, 0);
}
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 {
row.put(word, row.get(word) + 1);
}
}
}
br.close();
row.put(CLASS, SPAM);
data.add(row);
nSpam++;
}
return nSpam;
}
/**
* Reads the HAM Directory.
*
* @throws IOException
*/
private int readHamDir(String trainingHamDir) throws IOException {
File hamDir = new File(trainingHamDir);
int nHam = 0;
String line = null;
for (File hFile : hamDir.listFiles()) {
HashMap<String, Integer> row = new HashMap<String, Integer>();
FileReader fr = new FileReader(hFile);
BufferedReader br = new BufferedReader(fr);
// Adding vocab in row.
for (String word : vocab) {
row.put(word, 0);
}
while ((line = br.readLine()) != null) {
String list[] = line.split(SEPERATOR);
for (String word : list) {
if (usingStopWords && stopWords.contains(word)) {
// Do Nothing
} else {
row.put(word, row.get(word) + 1);
}
}
}
br.close();
row.put(CLASS, HAM);
data.add(row);
nHam++;
}
return nHam;
}
/**
* 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 (int i = 0; i < weights.size(); i++) {
writer.println(weights.get(i));
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}