forked from ivanhk/fastText_java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastText.java
More file actions
555 lines (499 loc) · 17.3 KB
/
Copy pathFastText.java
File metadata and controls
555 lines (499 loc) · 17.3 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
package fasttext;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import com.google.gson.JsonObject;
import org.apache.commons.math3.distribution.UniformIntegerDistribution;
import org.apache.commons.math3.distribution.UniformRealDistribution;
import org.apache.log4j.Logger;
import fasttext.Args.model_name;
import fasttext.Dictionary.entry_type;
public class FastText {
private static Logger logger = Logger.getLogger(FastText.class);
private static int SUPERVISED_LABEL_SIZE = 10;
public Args args = new Args();
public Dictionary dict = new Dictionary(args);
public Matrix input = new Matrix();
public Matrix output = new Matrix();
class Info {
long start = 0;
AtomicLong allWords = new AtomicLong(0l);
AtomicLong allN = new AtomicLong(0l);
double allLoss = 0.0;
}
public class MutableDouble {
private double value;
public MutableDouble(double value) {
this.value = value;
}
public void set(double value) {
this.value = value;
}
public double doubleValue() {
return value;
}
public void incrementDouble(double value) {
this.value += value;
}
}
Info info = new Info();
public void loadModel(String filename, Dictionary dict, Matrix input, Matrix output) throws IOException {
DataInputStream dis = null;
BufferedInputStream bis = null;
try {
File file = new File(filename);
if (!(file.exists() && file.isFile() && file.canRead())) {
throw new IOException("Model file cannot be opened for loading!");
}
bis = new BufferedInputStream(new FileInputStream(file));
dis = new DataInputStream(bis);
args.load(dis);
dict.load(dis);
input.load(dis);
output.load(dis);
logger.info("loadModel done!");
} finally {
bis.close();
dis.close();
}
}
public void getVector(Dictionary dict, Matrix input, Vector vec, String word) {
final java.util.Vector<Integer> ngrams = dict.getNgrams(word);
vec.zero();
for (Integer it : ngrams) {
vec.addRow(input, it);
}
if (ngrams.size() > 0) {
vec.mul((float) (1.0 / ngrams.size()));
}
}
public void printVectors(Dictionary dict, Matrix input) {
Vector vec = new Vector(args.dim);
@SuppressWarnings("resource")
java.util.Scanner scanner = new java.util.Scanner(System.in);
String word = scanner.nextLine();
while (!Utils.isEmpty(word)) {
getVector(dict, input, vec, word);
System.out.println(word + " " + vec);
word = scanner.nextLine();
}
}
public void printInfo(Model model, float progress) {
float loss = (float) (info.allLoss / info.allN.get());
float t = (float) ((System.currentTimeMillis() - info.start) / 1000);
float wst = (float) (info.allWords.get() / t);
int eta = (int) (t / progress * (1 - progress) / args.thread);
int etah = eta / 3600;
int etam = (eta - etah * 3600) / 60;
System.out.printf("\rProgress: %.1f%% words/sec/thread: %d lr: %.6f loss: %.6f eta: %d h %d m", 100 * progress,
(int) wst, model.getLearningRate(), loss, etah, etam);
}
public int supervised(Model model, final java.util.Vector<Integer> line, final java.util.Vector<Integer> labels,
MutableDouble loss, UniformIntegerDistribution uid) {
if (labels.size() == 0 || line.size() == 0)
return 0;
int i = uid.sample();
loss.incrementDouble(model.update(line, labels.get(i)));
return 1;
}
public int cbow(Dictionary dict, Model model, final java.util.Vector<Integer> line, MutableDouble loss,
UniformIntegerDistribution uid) {
java.util.Vector<Integer> bow = new java.util.Vector<Integer>();
int nexamples = 0;
for (int w = 0; w < line.size(); w++) {
int boundary = uid.sample();
bow.clear();
for (int c = -boundary; c <= boundary; c++) {
if (c != 0 && w + c >= 0 && w + c < line.size()) {
final java.util.Vector<Integer> ngrams = dict.getNgrams(line.get(w + c));
bow.addAll(ngrams);
}
}
loss.incrementDouble(model.update(bow, line.get(w)));
nexamples++;
}
return nexamples;
}
public int skipgram(Dictionary dict, Model model, final java.util.Vector<Integer> line, MutableDouble loss,
UniformIntegerDistribution uid) {
int nexamples = 0;
for (int w = 0; w < line.size(); w++) {
int boundary = uid.sample();
final java.util.Vector<Integer> ngrams = dict.getNgrams(line.get(w));
for (int c = -boundary; c <= boundary; c++) {
if (c != 0 && w + c >= 0 && w + c < line.size()) {
loss.incrementDouble(model.update(ngrams, line.get(w + c)));
nexamples++;
}
}
}
return nexamples;
}
public void test(Dictionary dict, Model model, String filename) throws IOException {
int nexamples = 0;
double precision = 0.0f;
java.util.Vector<Integer> line = new java.util.Vector<Integer>();
java.util.Vector<Integer> labels = new java.util.Vector<Integer>();
File file = new File(filename);
if (!(file.exists() && file.isFile() && file.canRead())) {
throw new IOException("Test file cannot be opened!");
}
UniformRealDistribution urd = new UniformRealDistribution(model.rng, 0, 1);
FileInputStream fis = new FileInputStream(file);
BufferedReader dis = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
try {
String lineString;
while ((lineString = dis.readLine()) != null) {
dict.getLine(lineString, line, labels, urd);
dict.addNgrams(line, args.wordNgrams);
if (labels.size() > 0 && line.size() > 0) {
System.out.print("Test line: " + lineString);
JsonObject detail = new JsonObject();
int i = model.predict(line, detail);
logger.info(detail.toString());
if (labels.contains(i)) {
precision += 1.0;
System.out.println(" [HIT]: " + dict.getLabel(i));
} else {
System.out.println(" [MISSED]: " + dict.getLabel(i));
}
nexamples++;
//logger.info("Line = " + lineString + "\t" + "predict label = " + dict.getLabel(i) + "\t" +
// "Score = " + score.toString());
} else {
System.out.println("FAIL Test line: " + lineString + "labels: " + labels + " line: " + line);
}
}
} finally {
dis.close();
fis.close();
}
System.out.printf("P@1: %.3f%n", precision / nexamples);
System.out.println("Number of examples: " + nexamples);
}
public void predict(Dictionary dict, Model model, String filename) throws IOException {
// int nexamples = 0;
// double precision = 0.0;
java.util.Vector<Integer> line = new java.util.Vector<Integer>();
java.util.Vector<Integer> labels = new java.util.Vector<Integer>();
File file = new File(filename);
if (!(file.exists() && file.isFile() && file.canRead())) {
throw new IOException("Test file cannot be opened!");
}
UniformRealDistribution urd = new UniformRealDistribution(model.rng, 0, 1);
FileInputStream fis = new FileInputStream(file);
BufferedReader dis = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
try {
String lineString;
while ((lineString = dis.readLine()) != null) {
dict.getLine(lineString, line, labels, urd);
dict.addNgrams(line, args.wordNgrams);
if (line.size() > 0) {
int i = model.predict(line);
System.out.println(lineString + "\t" + dict.getLabel(i));
} else {
System.out.println(lineString + "\tn/a");
}
}
} finally {
dis.close();
fis.close();
}
}
public void test(String binFile, String testFile) throws IOException {
loadModel(binFile, dict, input, output);
Model model = new Model(args, input, output, args.dim, (float) args.lr, 1);
model.setTargetCounts(dict.getCounts(entry_type.label));
test(dict, model, testFile);
}
public void predict(String binFile, String predictFile) throws IOException {
loadModel(binFile, dict, input, output);
Model model = new Model(args, input, output, args.dim, (float) args.lr, 1);
model.setTargetCounts(dict.getCounts(entry_type.label));
predict(dict, model, predictFile);
}
public void printVectors(String binFile) throws IOException {
loadModel(binFile, dict, input, output);
printVectors(dict, input);
}
int threadCount;
public void train(String[] args_) throws IOException {
args.parseArgs(args_);
File file = new File(args.input);
if (!(file.exists() && file.isFile() && file.canRead())) {
throw new IOException("Input file cannot be opened! " + args.input);
}
dict.readFromFile(args.input);
input = new Matrix(dict.nwords() + args.bucket, args.dim);
if (args.model == model_name.sup) {
output = new Matrix(dict.nlabels(), args.dim);
} else {
output = new Matrix(dict.nwords(), args.dim);
}
input.uniform((float) (1.0 / args.dim));
output.zero();
info.start = System.currentTimeMillis();
long t0 = System.currentTimeMillis();
threadCount = args.thread;
long fileSize = Utils.sizeLine(args.input);
for (int i = 0; i < args.thread; i++) {
new TrainThread(this, dict, input, output, i, fileSize).start();
}
synchronized (this) {
while (threadCount > 0) {
try {
wait();
} catch (InterruptedException ignored) {
}
}
}
long trainTime = (System.currentTimeMillis() - t0) / 1000;
System.out.printf("Train time: %d sec\n", trainTime);
if (!Utils.isEmpty(args.output)) {
saveModel(dict, input, output);
saveVectors(dict, input, output);
}
}
public class TrainThread extends Thread {
final FastText ft;
Dictionary dict;
Matrix input;
Matrix output;
int threadId;
long fileSize;
public TrainThread(FastText ft, Dictionary dict, Matrix input, Matrix output, int threadId, long fileSize) {
this.ft = ft;
this.dict = dict;
this.input = input;
this.output = output;
this.threadId = threadId;
this.fileSize = fileSize;
}
public void run() {
if (logger.isDebugEnabled()) {
logger.debug("thread: " + threadId + " RUNNING!");
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(args.input));
Utils.seek(br, threadId * fileSize / args.thread);
Model model = new Model(args, input, output, args.dim, (float) args.lr, threadId);
if (args.model == model_name.sup) {
model.setTargetCounts(dict.getCounts(entry_type.label));
} else {
model.setTargetCounts(dict.getCounts(entry_type.word));
}
float progress;
final long ntokens = dict.ntokens();
long tokenCount = 0, /** printCount = 0, */
deltaCount = 0;
MutableDouble loss = new MutableDouble(0.0);
long nexamples = 0;
java.util.Vector<Integer> line = new java.util.Vector<Integer>();
java.util.Vector<Integer> labels = new java.util.Vector<Integer>();
UniformRealDistribution urd = new UniformRealDistribution(model.rng, 0, 1);
List<UniformIntegerDistribution> learnUid0 = new ArrayList<UniformIntegerDistribution>();
UniformIntegerDistribution learnUid = null;
if (args.model == model_name.sup) {
for (int i = 0; i <= SUPERVISED_LABEL_SIZE; i++) {
learnUid0.add(new UniformIntegerDistribution(model.rng, 0, i));
}
} else if (args.model == model_name.cbow) {
learnUid = new UniformIntegerDistribution(model.rng, 1, args.ws);
} else if (args.model == model_name.sg) {
learnUid = new UniformIntegerDistribution(model.rng, 1, args.ws);
}
String lineString;
while (info.allWords.get() < args.epoch * ntokens) {
lineString = br.readLine();
if (lineString == null) {
try {
br.close();
br = new BufferedReader(new FileReader(args.input));
if (logger.isDebugEnabled()) {
logger.debug("Input file reloaded!");
}
} catch (Exception e) {
e.printStackTrace();
}
lineString = br.readLine();
}
while (Utils.isEmpty(lineString) || lineString.startsWith("#")) {
lineString = br.readLine();
}
deltaCount = dict.getLine(lineString, line, labels, urd);
tokenCount += deltaCount;
// printCount += deltaCount;
if (args.model == model_name.sup) {
dict.addNgrams(line, args.wordNgrams);
if (labels.size() == 0 || line.size() == 0) {
continue;
}
learnUid = learnUid0.get(labels.size() - 1);
nexamples += supervised(model, line, labels, loss, learnUid);
} else if (args.model == model_name.cbow) {
nexamples += cbow(dict, model, line, loss, learnUid);
} else if (args.model == model_name.sg) {
nexamples += skipgram(dict, model, line, loss, learnUid);
}
if (tokenCount > args.lrUpdateRate) {
info.allWords.addAndGet(tokenCount);
info.allLoss += loss.doubleValue();
info.allN.addAndGet(nexamples);
tokenCount = 0;
loss.set(0.0);
nexamples = 0;
progress = (float) (info.allWords.get()) / (args.epoch * ntokens);
model.setLearningRate((float) (args.lr * (1.0 - progress)));
if (threadId == 0) {
printInfo(model, progress);
}
}
}
if (threadId == 0) {
printInfo(model, 1.0f);
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// exit from thread
synchronized (ft) {
if (logger.isDebugEnabled()) {
logger.debug("thread: " + threadId + " EXIT!");
}
ft.threadCount--;
ft.notify();
}
}
}
public void saveModel(Dictionary dict, Matrix input, Matrix output) throws IOException {
File file = new File(args.output + ".bin");
if (file.exists()) {
file.delete();
}
logger.info("Saving model to " + file.getAbsolutePath().toString());
FileOutputStream fos = new FileOutputStream(file);
OutputStream ofs = new DataOutputStream(fos);
try {
logger.debug("writing args");
args.save(ofs);
logger.debug("writing dict");
dict.save(ofs);
logger.debug("writing input");
input.save(ofs);
logger.debug("writing output");
output.save(ofs);
} finally {
ofs.flush();
ofs.close();
}
}
public void saveVectors(Dictionary dict, Matrix input, Matrix output) throws IOException {
File file = new File(args.output + ".vec");
if (file.exists()) {
file.delete();
}
logger.info("Saving Vectors to " + file.getAbsolutePath().toString());
Writer writer = new FileWriter(file);
try {
writer.write(dict.nwords());
writer.write(" ");
writer.write(args.dim);
writer.write("\n");
Vector vec = new Vector(args.dim);
DecimalFormat df = new DecimalFormat("0.#####");
for (int i = 0; i < dict.nwords(); i++) {
String word = dict.getWord(i);
getVector(dict, input, vec, word);
writer.write(word);
writer.write(" ");
writer.write(" ");
for (int j = 0; i < vec.m_; i++) {
writer.write(df.format(vec.data_[j]));
writer.write(" ");
}
writer.write("\n");
}
} finally {
writer.flush();
writer.close();
}
}
public static void printUsage() {
System.out.print(
"usage: java -jar fasttext.jar <command> <args>\n\n" + "The commands supported by fasttext are:\n\n"
+ " supervised train a supervised classifier\n" + " test evaluate a supervised classifier\n"
+ " predict predict most likely label\n" + " skipgram train a skipgram model\n"
+ " cbow train a cbow model\n" + " print-vectors print vectors given a trained model\n");
}
public static void printTestUsage() {
System.out.print("usage: java -jar fasttext.jar test <model> <test-data>\n\n" + " <model> model filename\n"
+ " <test-data> test data filename\n");
}
public static void printPredictUsage() {
System.out.print("usage: java -jar fasttext.jar predict <model> <test-data>\n\n" + " <model> model filename\n"
+ " <test-data> test data filename\n");
}
public static void printPrintVectorsUsage() {
System.out.print("usage: java -jar fasttext.jar print-vectors <model>\n\n" + " <model> model filename\n");
}
public static void main(String[] args) {
org.apache.log4j.PropertyConfigurator.configure("log4j.properties");
FastText op = new FastText();
if (args.length == 0) {
printUsage();
System.exit(1);
}
try {
String command = args[0];
if ("skipgram".equalsIgnoreCase(command) || "cbow".equalsIgnoreCase(command)
|| "supervised".equalsIgnoreCase(command)) {
op.train(args);
} else if ("test".equalsIgnoreCase(command)) {
if (args.length != 3) {
printTestUsage();
System.exit(1);
}
op.test(args[1], args[2]);
} else if ("print-vectors".equalsIgnoreCase(command)) {
op.printVectors(args[1]);
} else if ("predict".equalsIgnoreCase(command)) {
if (args.length != 3) {
printPredictUsage();
System.exit(1);
}
op.predict(args[1], args[2]);
} else {
printUsage();
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
}