/
Word2Vec.java
640 lines (504 loc) · 19.6 KB
/
Word2Vec.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
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/**
* Created by will on 02/09/15.
*/
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import akka.actor.ActorSystem;
import com.google.common.base.Function;
import com.google.common.util.concurrent.AtomicDouble;
import org.apache.commons.math3.random.RandomGenerator;
import org.deeplearning4j.bagofwords.vectorizer.TextVectorizer;
import org.deeplearning4j.bagofwords.vectorizer.TfidfVectorizer;
import org.deeplearning4j.models.embeddings.WeightLookupTable;
//import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable;
import org.deeplearning4j.models.embeddings.wordvectors.WordVectorsImpl;
import org.deeplearning4j.models.word2vec.Huffman;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.models.word2vec.wordstore.inmemory.InMemoryLookupCache;
import org.deeplearning4j.parallel.Parallelization;
import org.deeplearning4j.text.invertedindex.InvertedIndex;
import org.deeplearning4j.text.invertedindex.LuceneInvertedIndex;
import org.deeplearning4j.text.documentiterator.DocumentIterator;
import org.deeplearning4j.text.stopwords.StopWords;
import org.deeplearning4j.text.tokenization.tokenizerfactory.UimaTokenizerFactory;
import org.deeplearning4j.text.sentenceiterator.SentenceIterator;
import org.deeplearning4j.text.tokenization.tokenizerfactory.DefaultTokenizerFactory;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Word2Vec extends WordVectorsImpl {
protected transient TokenizerFactory tokenizerFactory = new DefaultTokenizerFactory();
protected transient SentenceIterator sentenceIter;
protected transient DocumentIterator docIter;
protected int batchSize = 1000;
protected double sample = 0;
protected long totalWords = 1;
//learning rate
protected AtomicDouble alpha = new AtomicDouble(0.025);
private InMemoryLookupTable lookupTable;
//context to use for gathering word frequencies
protected int window = 5;
protected transient RandomGenerator g;
protected static final Logger log = LoggerFactory.getLogger(Word2Vec.class);
protected boolean shouldReset = true;
//number of iterations to run
protected int numIterations = 1;
public final static String UNK = "UNK";
protected long seed = 123;
protected boolean saveVocab = false;
protected double minLearningRate = 0;
protected transient TextVectorizer vectorizer;
protected int learningRateDecayWords = 10000;
protected InvertedIndex invertedIndex;
protected boolean useAdaGrad = false;
protected int workers = Runtime.getRuntime().availableProcessors();
public Word2Vec() {}
public TextVectorizer getVectorizer() {
return vectorizer;
}
public void setVectorizer(TextVectorizer vectorizer) {
this.vectorizer = vectorizer;
}
/**
* Train the model
*/
public void fit() throws IOException {
boolean loaded = buildVocab();
//save vocab after building
if (!loaded && saveVocab)
vocab().saveVocab();
if (stopWords == null)
readStopWords();
log.info("Training word2vec multithreaded");
if (sentenceIter != null)
sentenceIter.reset();
if (docIter != null)
docIter.reset();
int[] docs = vectorizer.index().allDocs();
if(docs.length < 1) {
vectorizer.fit();
}
docs = vectorizer.index().allDocs();
if(docs.length < 1) {
throw new IllegalStateException("No documents found");
}
totalWords = vectorizer.numWordsEncountered();
if(totalWords < 1)
throw new IllegalStateException("Unable to train, total words less than 1");
totalWords *= numIterations;
log.info("Processing sentences...");
AtomicLong numWordsSoFar = new AtomicLong(0);
final AtomicLong nextRandom = new AtomicLong(5);
ExecutorService exec = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
Runtime.getRuntime().availableProcessors(),
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(), new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
executor.submit(r);
}
});
final Queue<List<VocabWord>> batch2 = new ConcurrentLinkedDeque();
vectorizer.index().eachDoc(new Function<List<VocabWord>, Void>() {
@Override
public Void apply(List<VocabWord> input) {
List<VocabWord> batch = new ArrayList();
addWords(input, nextRandom, batch);
if(!batch.isEmpty()) {
batch2.add(batch);
}
return null;
}
},exec);
exec.shutdown();
try {
exec.awaitTermination(1,TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
ActorSystem actorSystem = ActorSystem.create();
/*FileWriter writer=new FileWriter("tmp1.txt");
Iterator<VocabWord> tmp = lookupTable.getVocab().tokens().iterator();
while (tmp.hasNext())
writer.write(tmp.next().getWord()+"\n");
writer.close();
writer=new FileWriter("tmp2.txt");
tmp = lookupTable.getVocab().vocabWords().iterator();
while (tmp.hasNext())
writer.write(tmp.next().getWord()+"\n");
writer.close();*/
for(int i = 0; i < numIterations; i++)
doIteration(batch2,numWordsSoFar,nextRandom,actorSystem);
actorSystem.shutdown();
lookupTable.fit();
super.lookupTable = this.lookupTable;
System.out.println(lookupTable.syn0);
}
private void doIteration(Collection<List<VocabWord>> batch2,final AtomicLong numWordsSoFar,final AtomicLong nextRandom,ActorSystem actorSystem) {
final AtomicLong lastReported = new AtomicLong(System.currentTimeMillis());
Parallelization.iterateInParallel(batch2, new Parallelization.RunnableWithParams<List<VocabWord>>() {
@Override
public void run(List<VocabWord> sentence, Object[] args) {
double alpha = Math.max(minLearningRate, Word2Vec.this.alpha.get() *
(1 - (1.0 * numWordsSoFar.get() / (double) totalWords)));
long now = System.currentTimeMillis();
long diff = Math.abs(now - lastReported.get());
if (numWordsSoFar.get() > 0 && diff > 1000) {
lastReported.set(now);
log.info("Words so far " + numWordsSoFar.get() + " with alpha at " + alpha);
}
trainSentence(sentence, nextRandom, alpha);
numWordsSoFar.set(numWordsSoFar.get() + sentence.size());
}
},actorSystem);
}
protected void addWords(List<VocabWord> sentence,AtomicLong nextRandom,List<VocabWord> currMiniBatch) {
for (VocabWord word : sentence) {
if(word == null)
continue;
// The subsampling randomly discards frequent words while keeping the ranking same
if (sample > 0) {
double numDocs = vectorizer.index().numDocuments();
double ran = (Math.sqrt(word.getWordFrequency() / (sample * numDocs)) + 1)
* (sample * numDocs) / word.getWordFrequency();
if (ran < (nextRandom.get() & 0xFFFF) / (double) 65536) {
continue;
}
currMiniBatch.add(word);
}
else
currMiniBatch.add(word);
}
}
/**
* Build the binary tree
* Reset the weights
*/
public void setup() {
log.info("Building binary tree");
buildBinaryTree();
log.info("Resetting weights");
if(shouldReset)
resetWeights();
}
/**
* Builds the vocabulary for training
*/
public boolean buildVocab() {
readStopWords();
if(vocab().vocabExists()) {
log.info("Loading vocab...");
vocab().loadVocab();
lookupTable.resetWeights();
return true;
}
if(invertedIndex == null)
invertedIndex = new LuceneInvertedIndex.Builder()
.cache(vocab()).stopWords(stopWords)
.build();
//vectorizer will handle setting up vocab meta data
if(vectorizer == null) {
vectorizer = new TfidfVectorizer.Builder().index(invertedIndex)
.cache(vocab()).iterate(docIter).iterate(sentenceIter).batchSize(batchSize)
.minWords(minWordFrequency).stopWords(stopWords)
.tokenize(tokenizerFactory).build();
vectorizer.fit();
}
//includes unk
else if(vocab().numWords() < 2)
vectorizer.fit();
setup();
return false;
}
/**
* Train on a list of vocab words
* @param sentence the list of vocab words to train on
*/
public void trainSentence(final List<VocabWord> sentence,AtomicLong nextRandom,double alpha) {
if(sentence == null || sentence.isEmpty())
return;
for(int i = 0; i < sentence.size(); i++) {
nextRandom.set(nextRandom.get() * 25214903917L + 11);
skipGram(i, sentence, (int) nextRandom.get() % window,nextRandom,alpha);
}
}
/**
* Train via skip gram
* @param i
* @param sentence
*/
public void skipGram(int i,List<VocabWord> sentence, int b,AtomicLong nextRandom,double alpha) {
final VocabWord word = sentence.get(i);
if(word == null || sentence.isEmpty())
return;
int end = window * 2 + 1 - b;
for(int a = b; a < end; a++) {
if(a != window) {
int c = i - window + a;
if(c >= 0 && c < sentence.size()) {
VocabWord lastWord = sentence.get(c);
iterate(word,lastWord,nextRandom,alpha);
}
}
}
}
/**
* Train the word vector
* on the given words
* @param w1 the first word to fit
*/
public void iterate(VocabWord w1, VocabWord w2,AtomicLong nextRandom,double alpha) {
lookupTable.iterateSample(w1,w2,nextRandom,alpha);
}
/* Builds the binary tree for the word relationships */
protected void buildBinaryTree() {
log.info("Constructing priority queue");
Huffman huffman = new Huffman(vocab().vocabWords());
huffman.build();
log.info("Built tree");
}
/* reinit weights */
protected void resetWeights() {
lookupTable.resetWeights();
}
@SuppressWarnings("unchecked")
protected void readStopWords() {
if(this.stopWords != null)
return;
this.stopWords = StopWords.getStopWords();
}
/**
* Note that calling a setter on this
* means assumes that this is a training continuation
* and therefore weights should not be reset.
* @param sentenceIter
*/
public void setSentenceIter(SentenceIterator sentenceIter) {
this.sentenceIter = sentenceIter;
this.shouldReset = false;
}
/**
* restart training on next fit().
* Use when sentence iterator is set for new training.
*/
public void resetWeightsOnSetup() {
this.shouldReset = true;
}
public int getWindow() {
return window;
}
public List<String> getStopWords() {
return stopWords;
}
public synchronized SentenceIterator getSentenceIter() {
return sentenceIter;
}
public TokenizerFactory getTokenizerFactory() {
return tokenizerFactory;
}
public void setTokenizerFactory(TokenizerFactory tokenizerFactory) {
this.tokenizerFactory = tokenizerFactory;
}
public static class Builder {
protected int minWordFrequency = 1;
protected int layerSize = 50;
protected SentenceIterator iter;
protected List<String> stopWords = StopWords.getStopWords();
protected int window = 5;
protected TokenizerFactory tokenizerFactory;
protected VocabCache vocabCache;
protected DocumentIterator docIter;
protected double lr = 2.5e-2;
protected int iterations = 1;
protected long seed = 123;
protected boolean saveVocab = false;
protected int batchSize = 1000;
protected int learningRateDecayWords = 10000;
protected boolean useAdaGrad = false;
protected TextVectorizer textVectorizer;
protected double minLearningRate = 1e-2;
protected double negative = 0;
protected double sampling = 1e-5;
protected int workers = Runtime.getRuntime().availableProcessors();
protected InvertedIndex index;
protected InMemoryLookupTable lookupTable;
public Builder lookupTable(InMemoryLookupTable lookupTable) {
this.lookupTable = lookupTable;
return this;
}
public Builder index(InvertedIndex index) {
this.index = index;
return this;
}
public Builder workers(int workers) {
this.workers = workers;
return this;
}
public Builder sampling(double sample) {
this.sampling = sample;
return this;
}
public Builder negativeSample(double negative) {
this.negative = negative;
return this;
}
public Builder minLearningRate(double minLearningRate) {
this.minLearningRate = minLearningRate;
return this;
}
public Builder useAdaGrad(boolean useAdaGrad) {
this.useAdaGrad = useAdaGrad;
return this;
}
public Builder vectorizer(TextVectorizer textVectorizer) {
this.textVectorizer = textVectorizer;
return this;
}
public Builder learningRateDecayWords(int learningRateDecayWords) {
this.learningRateDecayWords = learningRateDecayWords;
return this;
}
public Builder batchSize(int batchSize) {
this.batchSize = batchSize;
return this;
}
public Builder saveVocab(boolean saveVocab){
this.saveVocab = saveVocab;
return this;
}
public Builder seed(long seed) {
this.seed = seed;
return this;
}
public Builder iterations(int iterations) {
this.iterations = iterations;
return this;
}
public Builder learningRate(double lr) {
this.lr = lr;
return this;
}
public Builder iterate(DocumentIterator iter) {
this.docIter = iter;
return this;
}
public Builder vocabCache(VocabCache cache) {
this.vocabCache = cache;
return this;
}
public Builder minWordFrequency(int minWordFrequency) {
this.minWordFrequency = minWordFrequency;
return this;
}
public Builder tokenizerFactory(TokenizerFactory tokenizerFactory) {
this.tokenizerFactory = tokenizerFactory;
return this;
}
public Builder layerSize(int layerSize) {
this.layerSize = layerSize;
return this;
}
public Builder stopWords(List<String> stopWords) {
this.stopWords = stopWords;
return this;
}
public Builder windowSize(int window) {
this.window = window;
return this;
}
public Builder iterate(SentenceIterator iter) {
this.iter = iter;
return this;
}
public Word2Vec build() {
if(iter == null) {
Word2Vec ret = new Word2Vec();
ret.window = window;
ret.alpha.set(lr);
ret.vectorizer = textVectorizer;
ret.stopWords = stopWords;
ret.setVocab(vocabCache);
ret.numIterations = iterations;
ret.minWordFrequency = minWordFrequency;
ret.seed = seed;
ret.saveVocab = saveVocab;
ret.batchSize = batchSize;
ret.useAdaGrad = useAdaGrad;
ret.minLearningRate = minLearningRate;
ret.sample = sampling;
ret.workers = workers;
ret.invertedIndex = index;
ret.lookupTable = lookupTable;
try {
if (tokenizerFactory == null)
tokenizerFactory = new UimaTokenizerFactory();
}catch(Exception e) {
throw new RuntimeException(e);
}
if(vocabCache == null) {
vocabCache = new InMemoryLookupCache();
ret.setVocab(vocabCache);
}
if(lookupTable == null) {
lookupTable = new InMemoryLookupTable.Builder().negative(negative)
.useAdaGrad(useAdaGrad).lr(lr).cache(vocabCache)
.vectorLength(layerSize).build();
}
ret.docIter = docIter;
ret.lookupTable = lookupTable;
ret.tokenizerFactory = tokenizerFactory;
return ret;
}
else {
Word2Vec ret = new Word2Vec();
ret.alpha.set(lr);
ret.sentenceIter = iter;
ret.window = window;
ret.useAdaGrad = useAdaGrad;
ret.minLearningRate = minLearningRate;
ret.vectorizer = textVectorizer;
ret.stopWords = stopWords;
ret.minWordFrequency = minWordFrequency;
ret.setVocab(vocabCache);
ret.docIter = docIter;
ret.minWordFrequency = minWordFrequency;
ret.numIterations = iterations;
ret.seed = seed;
ret.numIterations = iterations;
ret.saveVocab = saveVocab;
ret.batchSize = batchSize;
ret.sample = sampling;
ret.workers = workers;
ret.invertedIndex = index;
ret.lookupTable = lookupTable;
try {
if (tokenizerFactory == null)
tokenizerFactory = new UimaTokenizerFactory();
}catch(Exception e) {
throw new RuntimeException(e);
}
if(vocabCache == null) {
vocabCache = new InMemoryLookupCache();
ret.setVocab(vocabCache);
}
if(lookupTable == null) {
lookupTable = new InMemoryLookupTable.Builder().negative(negative)
.useAdaGrad(useAdaGrad).lr(lr).cache(vocabCache)
.vectorLength(layerSize).build();
}
ret.lookupTable = lookupTable;
ret.tokenizerFactory = tokenizerFactory;
return ret;
}
}
}
}