/
SequenceVectors.java
1419 lines (1220 loc) · 57.9 KB
/
SequenceVectors.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.deeplearning4j.models.sequencevectors;
import org.apache.commons.lang3.StringUtils;
import org.deeplearning4j.config.DL4JClassLoading;
import org.nd4j.shade.guava.primitives.Ints;
import org.nd4j.shade.guava.util.concurrent.AtomicDouble;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.val;
import org.deeplearning4j.exception.DL4JInvalidConfigException;
import org.deeplearning4j.models.embeddings.WeightLookupTable;
import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable;
import org.deeplearning4j.models.embeddings.learning.ElementsLearningAlgorithm;
import org.deeplearning4j.models.embeddings.learning.SequenceLearningAlgorithm;
import org.deeplearning4j.models.embeddings.learning.impl.elements.BatchSequences;
import org.deeplearning4j.models.embeddings.learning.impl.elements.CBOW;
import org.deeplearning4j.models.embeddings.learning.impl.elements.SkipGram;
import org.deeplearning4j.models.embeddings.learning.impl.sequence.DBOW;
import org.deeplearning4j.models.embeddings.learning.impl.sequence.DM;
import org.deeplearning4j.models.embeddings.loader.VectorsConfiguration;
import org.deeplearning4j.models.embeddings.loader.WordVectorSerializer;
import org.deeplearning4j.models.embeddings.reader.ModelUtils;
import org.deeplearning4j.models.embeddings.reader.impl.BasicModelUtils;
import org.deeplearning4j.models.embeddings.wordvectors.WordVectors;
import org.deeplearning4j.models.embeddings.wordvectors.WordVectorsImpl;
import org.deeplearning4j.models.sequencevectors.enums.ListenerEvent;
import org.deeplearning4j.models.sequencevectors.interfaces.SequenceIterator;
import org.deeplearning4j.models.sequencevectors.interfaces.VectorsListener;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.deeplearning4j.models.word2vec.wordstore.VocabConstructor;
import org.deeplearning4j.models.word2vec.wordstore.inmemory.AbstractCache;
import org.nd4j.common.util.ThreadUtils;
import org.nd4j.linalg.api.memory.conf.WorkspaceConfiguration;
import org.nd4j.linalg.api.memory.enums.LearningPolicy;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.rng.Random;
import org.nd4j.linalg.factory.Nd4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class SequenceVectors<T extends SequenceElement> extends WordVectorsImpl<T> implements WordVectors {
private static final long serialVersionUID = 78249242142L;
@Getter
protected transient SequenceIterator<T> iterator;
@Setter
protected transient ElementsLearningAlgorithm<T> elementsLearningAlgorithm;
protected transient SequenceLearningAlgorithm<T> sequenceLearningAlgorithm;
@Getter
@Setter
protected VectorsConfiguration configuration = new VectorsConfiguration();
protected static final Logger log = LoggerFactory.getLogger(SequenceVectors.class);
protected transient WordVectors existingModel;
protected transient WordVectors intersectModel;
protected transient T unknownElement;
protected transient AtomicDouble scoreElements = new AtomicDouble(0.0);
protected transient AtomicDouble scoreSequences = new AtomicDouble(0.0);
protected transient boolean configured = false;
protected transient boolean lockFactor = false;
protected boolean enableScavenger = false;
protected int vocabLimit = 0;
@Setter
protected transient Set<VectorsListener<T>> eventListeners;
@Override
public String getUNK() {
return configuration.getUNK();
}
@Override
public void setUNK(String UNK) {
configuration.setUNK(UNK);
super.setUNK(UNK);
}
public double getElementsScore() {
return scoreElements.get();
}
public double getSequencesScore() {
return scoreSequences.get();
}
@Override
public INDArray getWordVectorMatrix(String word) {
if (configuration.isUseUnknown() && !hasWord(word)) {
return super.getWordVectorMatrix(getUNK());
} else
return super.getWordVectorMatrix(word);
}
/**
* Builds vocabulary from provided SequenceIterator instance
*/
public void buildVocab() {
val constructor = new VocabConstructor.Builder<T>().addSource(iterator, minWordFrequency)
.setTargetVocabCache(vocab).fetchLabels(trainSequenceVectors).setStopWords(stopWords)
.enableScavenger(enableScavenger).setEntriesLimit(vocabLimit)
.allowParallelTokenization(configuration.isAllowParallelTokenization())
.setUnk(useUnknown && unknownElement != null ? unknownElement : null).build();
if (existingModel != null && lookupTable instanceof InMemoryLookupTable
&& existingModel.lookupTable() instanceof InMemoryLookupTable) {
log.info("Merging existing vocabulary into the current one...");
/*
if we have existing model defined, we're forced to fetch labels only.
the rest of vocabulary & weights should be transferred from existing model
*/
constructor.buildMergedVocabulary(existingModel, true);
/*
Now we have vocab transferred, and we should transfer syn0 values into lookup table
*/
((InMemoryLookupTable<VocabWord>) lookupTable)
.consume((InMemoryLookupTable<VocabWord>) existingModel.lookupTable());
} else {
log.info("Starting vocabulary building...");
// if we don't have existing model defined, we just build vocabulary
constructor.buildJointVocabulary(false, true);
// check for malformed inputs. if numWords/numSentences ratio is huge, then user is passing something weird
if (vocab.numWords() / constructor.getNumberOfSequences() > 1000) {
log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
log.warn("! !");
log.warn("! Your input looks malformed: number of sentences is too low, model accuracy may suffer !");
log.warn("! !");
log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
}
protected synchronized void initLearners() {
if (!configured) {
log.info("Building learning algorithms:");
if (trainElementsVectors && elementsLearningAlgorithm != null && !trainSequenceVectors) {
log.info(" building ElementsLearningAlgorithm: [" + elementsLearningAlgorithm.getCodeName()
+ "]");
elementsLearningAlgorithm.configure(vocab, lookupTable, configuration);
elementsLearningAlgorithm.pretrain(iterator);
}
if(sequenceLearningAlgorithm == null) {
sequenceLearningAlgorithm = new DBOW<>();
}
if (trainSequenceVectors && sequenceLearningAlgorithm != null) {
log.info(" building SequenceLearningAlgorithm: [" + sequenceLearningAlgorithm.getCodeName()
+ "]");
sequenceLearningAlgorithm.configure(vocab, lookupTable, configuration);
sequenceLearningAlgorithm.pretrain(this.iterator);
// we'll use the ELA compatible with selected SLA
if (trainElementsVectors) {
elementsLearningAlgorithm = sequenceLearningAlgorithm.getElementsLearningAlgorithm();
log.info(" building ElementsLearningAlgorithm: [" + elementsLearningAlgorithm.getCodeName()
+ "]");
}
}
configured = true;
}
}
private void initIntersectVectors() {
if (intersectModel != null && intersectModel.vocab().numWords() > 0) {
List<Integer> indexes = new ArrayList<>();
for (int i = 0; i < intersectModel.vocab().numWords(); ++i) {
String externalWord = intersectModel.vocab().wordAtIndex(i);
int index = this.vocab.indexOf(externalWord);
if (index >= 0) {
this.vocab.wordFor(externalWord).setLocked(lockFactor);
indexes.add(index);
}
}
if (indexes.size() > 0) {
int[] intersectIndexes = Ints.toArray(indexes);
Nd4j.scatterUpdate(org.nd4j.linalg.api.ops.impl.scatter.ScatterUpdate.UpdateOp.ASSIGN,
((InMemoryLookupTable<VocabWord>) lookupTable).getSyn0(),
Nd4j.createFromArray(intersectIndexes),
((InMemoryLookupTable<VocabWord>) intersectModel.lookupTable()).getSyn0(),
1);
}
}
}
/**
* Starts training over
*/
public void fit() {
val props = Nd4j.getExecutioner().getEnvironmentInformation();
if (props.getProperty("backend").equals("CUDA")) {
if (Nd4j.getAffinityManager().getNumberOfDevices() > 1)
throw new IllegalStateException("Multi-GPU word2vec/doc2vec isn't available atm");
}
Nd4j.getRandom().setSeed(configuration.getSeed());
AtomicLong timeSpent = new AtomicLong(0);
if (!trainElementsVectors && !trainSequenceVectors)
throw new IllegalStateException(
"You should define at least one training goal 'trainElementsRepresentation' or 'trainSequenceRepresentation'");
if (iterator == null)
throw new IllegalStateException("You can't fit() data without SequenceIterator defined");
if (resetModel || (lookupTable != null && vocab != null && vocab.numWords() == 0)) {
// build vocabulary from scratches
buildVocab();
}
WordVectorSerializer.printOutProjectedMemoryUse(vocab.numWords(), configuration.getLayersSize(),
configuration.isUseHierarchicSoftmax() && configuration.getNegative() > 0 ? 3 : 2);
if (vocab == null || lookupTable == null || vocab.numWords() == 0)
throw new IllegalStateException("You can't fit() model with empty Vocabulary or WeightLookupTable");
// if model vocab and lookupTable is built externally we basically should check that lookupTable was properly initialized
if (!resetModel || existingModel != null) {
lookupTable.resetWeights(false);
} else {
// otherwise we reset weights, independent of actual current state of lookup table
lookupTable.resetWeights(true);
// if preciseWeights used, we roll over data once again
if (configuration.isPreciseWeightInit()) {
log.info("Using precise weights init...");
iterator.reset();
while (iterator.hasMoreSequences()) {
val sequence = iterator.nextSequence();
// initializing elements, only once
for (T element : sequence.getElements()) {
T realElement = vocab.tokenFor(element.getLabel());
if (realElement != null && !realElement.isInit()) {
val rng = Nd4j.getRandomFactory().getNewRandomInstance(
configuration.getSeed() * realElement.hashCode(),
configuration.getLayersSize() + 1);
val randArray = Nd4j.rand(new int[] {1, configuration.getLayersSize()}, rng).subi(0.5)
.divi(configuration.getLayersSize());
lookupTable.getWeights().getRow(realElement.getIndex(), true).assign(randArray);
realElement.setInit(true);
}
}
// initializing labels, only once
for (T label : sequence.getSequenceLabels()) {
T realElement = vocab.tokenFor(label.getLabel());
if (realElement != null && !realElement.isInit()) {
Random rng = Nd4j.getRandomFactory().getNewRandomInstance(
configuration.getSeed() * realElement.hashCode(),
configuration.getLayersSize() + 1);
INDArray randArray = Nd4j.rand(new int[] {1, configuration.getLayersSize()}, rng).subi(0.5)
.divi(configuration.getLayersSize());
lookupTable.getWeights().getRow(realElement.getIndex(), true).assign(randArray);
realElement.setInit(true);
try {
rng.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
this.iterator.reset();
}
}
initLearners();
initIntersectVectors();
log.info("Starting learning process...");
timeSpent.set(System.currentTimeMillis());
if (this.stopWords == null)
this.stopWords = new ArrayList<>();
val wordsCounter = new AtomicLong(0);
for (int currentEpoch = 1; currentEpoch <= numEpochs; currentEpoch++) {
val linesCounter = new AtomicLong(0);
val sequencer = new AsyncSequencer(this.iterator, this.stopWords);
sequencer.start();
val timer = new AtomicLong(System.currentTimeMillis());
val threads = new ArrayList<VectorCalculationsThread>();
for (int x = 0; x < vectorCalcThreads; x++) {
threads.add(x, new VectorCalculationsThread(x, currentEpoch, wordsCounter, vocab.totalWordOccurrences(), linesCounter, sequencer, timer, numEpochs));
threads.get(x).start();
}
try {
sequencer.join();
} catch (Exception e) {
throw new RuntimeException(e);
}
for (int x = 0; x < vectorCalcThreads; x++) {
try {
threads.get(x).join();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// TODO: fix this to non-exclusive termination
if (trainElementsVectors && elementsLearningAlgorithm != null
&& (!trainSequenceVectors || sequenceLearningAlgorithm == null)
&& elementsLearningAlgorithm.isEarlyTerminationHit()) {
break;
}
if (trainSequenceVectors && sequenceLearningAlgorithm != null
&& (!trainElementsVectors || elementsLearningAlgorithm == null)
&& sequenceLearningAlgorithm.isEarlyTerminationHit()) {
break;
}
log.info("Epoch [" + currentEpoch + "] finished; Elements processed so far: [" + wordsCounter.get()
+ "]; Sequences processed: [" + linesCounter.get() + "]");
if (eventListeners != null && !eventListeners.isEmpty()) {
for (VectorsListener listener : eventListeners) {
if (listener.validateEvent(ListenerEvent.EPOCH, currentEpoch))
listener.processEvent(ListenerEvent.EPOCH, this, currentEpoch);
}
}
}
log.info("Time spent on training: {} ms", System.currentTimeMillis() - timeSpent.get());
}
protected void trainSequence(@NonNull Sequence<T> sequence, AtomicLong nextRandom, double alpha) {
if (sequence.getElements().isEmpty())
return;
/*
we do NOT train elements separately if sequenceLearningAlgorithm isn't CBOW
we skip that, because PV-DM includes CBOW
*/
if (trainElementsVectors && !(trainSequenceVectors && sequenceLearningAlgorithm instanceof DM)) {
// call for ElementsLearningAlgorithm
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
if (!elementsLearningAlgorithm.isEarlyTerminationHit()) {
scoreElements.set(elementsLearningAlgorithm.learnSequence(sequence, nextRandom, alpha));
}
}
if (trainSequenceVectors) {
// call for SequenceLearningAlgorithm
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
if (!sequenceLearningAlgorithm.isEarlyTerminationHit())
scoreSequences.set(sequenceLearningAlgorithm.learnSequence(sequence, nextRandom, alpha));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SequenceVectors)) return false;
SequenceVectors<?> that = (SequenceVectors<?>) o;
return configured == that.configured && lockFactor == that.lockFactor && enableScavenger == that.enableScavenger && vocabLimit == that.vocabLimit && Objects.equals(elementsLearningAlgorithm, that.elementsLearningAlgorithm) && Objects.equals(sequenceLearningAlgorithm, that.sequenceLearningAlgorithm) && Objects.equals(getConfiguration(), that.getConfiguration()) && Objects.equals(existingModel, that.existingModel) && Objects.equals(intersectModel, that.intersectModel) && Objects.equals(unknownElement, that.unknownElement);
}
@Override
public int hashCode() {
return Objects.hash(elementsLearningAlgorithm, sequenceLearningAlgorithm, getConfiguration(), existingModel, intersectModel, unknownElement, configured, lockFactor, enableScavenger, vocabLimit);
}
@Override
public String toString() {
return "SequenceVectors{" +
"iterator=" + iterator +
", elementsLearningAlgorithm=" + elementsLearningAlgorithm +
", sequenceLearningAlgorithm=" + sequenceLearningAlgorithm +
", configuration=" + configuration +
", existingModel=" + existingModel +
", intersectModel=" + intersectModel +
", unknownElement=" + unknownElement +
", scoreElements=" + scoreElements +
", scoreSequences=" + scoreSequences +
", configured=" + configured +
", lockFactor=" + lockFactor +
", enableScavenger=" + enableScavenger +
", vocabLimit=" + vocabLimit +
", eventListeners=" + eventListeners +
", minWordFrequency=" + minWordFrequency +
", lookupTable=" + lookupTable +
", vocab=" + vocab +
", layerSize=" + layerSize +
", modelUtils=" + modelUtils +
", numIterations=" + numIterations +
", numEpochs=" + numEpochs +
", negative=" + negative +
", sampling=" + sampling +
", learningRate=" + learningRate +
", minLearningRate=" + minLearningRate +
", window=" + window +
", batchSize=" + batchSize +
", learningRateDecayWords=" + learningRateDecayWords +
", resetModel=" + resetModel +
", useAdeGrad=" + useAdeGrad +
", workers=" + workers +
", vectorCalcThreads=" + vectorCalcThreads +
", trainSequenceVectors=" + trainSequenceVectors +
", trainElementsVectors=" + trainElementsVectors +
", seed=" + seed +
", useUnknown=" + useUnknown +
", variableWindows=" + Arrays.toString(variableWindows) +
", stopWords=" + stopWords +
'}';
}
public static class Builder<T extends SequenceElement> {
protected VocabCache<T> vocabCache;
protected WeightLookupTable<T> lookupTable;
protected SequenceIterator<T> iterator;
protected ModelUtils<T> modelUtils = new BasicModelUtils<>();
protected WordVectors existingVectors;
protected SequenceVectors<T> intersectVectors;
protected boolean lockFactor = false;
protected double sampling = 0;
protected double negative = 0;
protected double learningRate = 0.025;
protected double minLearningRate = 0.0001;
protected int minWordFrequency = 0;
protected int iterations = 1;
protected int numEpochs = 1;
protected int layerSize = 100;
protected int window = 5;
protected boolean hugeModelExpected = false;
protected int batchSize = 512;
protected int learningRateDecayWords;
protected long seed;
protected boolean useAdaGrad = false;
protected boolean resetModel = true;
protected int workers = Runtime.getRuntime().availableProcessors();
protected boolean useUnknown = false;
protected boolean useHierarchicSoftmax = true;
protected int[] variableWindows;
protected boolean trainSequenceVectors = false;
protected boolean trainElementsVectors = true;
protected boolean preciseWeightInit = false;
protected Collection<String> stopWords = new ArrayList<>();
protected VectorsConfiguration configuration = new VectorsConfiguration();
protected boolean configurationSpecified = false;
protected transient T unknownElement;
protected String UNK = configuration.getUNK();
protected String STOP = configuration.getSTOP();
protected boolean enableScavenger = false;
protected int vocabLimit;
protected int vectorCalcThreads = 1;
/**
* Experimental field. Switches on precise mode for batch operations.
*/
protected boolean preciseMode = false;
// defaults values for learning algorithms are set here
protected ElementsLearningAlgorithm<T> elementsLearningAlgorithm;
protected SequenceLearningAlgorithm<T> sequenceLearningAlgorithm;
protected Set<VectorsListener<T>> vectorsListeners = new HashSet<>();
public Builder() {
}
public Builder(@NonNull VectorsConfiguration configuration) {
this.configuration = configuration;
configurationSpecified = true;
this.iterations = configuration.getIterations();
this.numEpochs = configuration.getEpochs();
this.minLearningRate = configuration.getMinLearningRate();
this.learningRate = configuration.getLearningRate();
this.sampling = configuration.getSampling();
this.negative = configuration.getNegative();
this.minWordFrequency = configuration.getMinWordFrequency();
this.seed = configuration.getSeed();
this.hugeModelExpected = configuration.isHugeModelExpected();
this.batchSize = configuration.getBatchSize();
this.layerSize = configuration.getLayersSize();
this.learningRateDecayWords = configuration.getLearningRateDecayWords();
this.useAdaGrad = configuration.isUseAdaGrad();
this.window = configuration.getWindow();
this.UNK = configuration.getUNK();
this.STOP = configuration.getSTOP();
this.variableWindows = configuration.getVariableWindows();
this.useHierarchicSoftmax = configuration.isUseHierarchicSoftmax();
this.preciseMode = configuration.isPreciseMode();
this.vectorCalcThreads = configuration.getVectorCalcThreads();
String modelUtilsClassName = configuration.getModelUtils();
if (StringUtils.isNotEmpty(modelUtilsClassName)) {
try {
this.modelUtils = DL4JClassLoading.createNewInstance(modelUtilsClassName);
} catch (Exception instantiationException) {
log.error(
"Got '{}' trying to instantiate ModelUtils, falling back to BasicModelUtils instead",
instantiationException.getMessage(),
instantiationException);
this.modelUtils = new BasicModelUtils<>();
}
}
if (configuration.getElementsLearningAlgorithm() != null
&& !configuration.getElementsLearningAlgorithm().isEmpty()) {
this.elementsLearningAlgorithm(configuration.getElementsLearningAlgorithm());
}
if (configuration.getSequenceLearningAlgorithm() != null
&& !configuration.getSequenceLearningAlgorithm().isEmpty()) {
this.sequenceLearningAlgorithm(configuration.getSequenceLearningAlgorithm());
}
if (configuration.getStopList() != null)
this.stopWords.addAll(configuration.getStopList());
}
/**
* This method allows you to use pre-built WordVectors model (e.g. SkipGram) for DBOW sequence learning.
* Existing model will be transferred into new model before training starts.
*
* PLEASE NOTE: This model has no effect for elements learning algorithms. Only sequence learning is affected.
* PLEASE NOTE: Non-normalized model is recommended to use here.
*
* @param vec existing WordVectors model
* @return
*/
protected Builder<T> useExistingWordVectors(@NonNull WordVectors vec) {
this.existingVectors = vec;
return this;
}
/**
* This method defines the vector configuration to be used for model building
* @param vectorsConfiguration
* @return
*/
public Builder<T> configuration(@NonNull VectorsConfiguration vectorsConfiguration) {
this.configuration = vectorsConfiguration;
configurationSpecified = true;
return this;
}
/**
* This method defines SequenceIterator to be used for model building
* @param iterator
* @return
*/
public Builder<T> iterate(@NonNull SequenceIterator<T> iterator) {
this.iterator = iterator;
return this;
}
/**
* Sets specific LearningAlgorithm as Sequence Learning Algorithm
*
* @param algoName fully qualified class name
* @return
*/
public Builder<T> sequenceLearningAlgorithm(String algoName) {
//allow easier to use setup of configuration by allowing null
//values
if(algoName == null)
return this;
this.sequenceLearningAlgorithm = DL4JClassLoading.createNewInstance(algoName);
return this;
}
/**
* Sets specific LearningAlgorithm as Sequence Learning Algorithm
*
* @param algorithm SequenceLearningAlgorithm implementation
* @return
*/
public Builder<T> sequenceLearningAlgorithm(SequenceLearningAlgorithm<T> algorithm) {
//allow easier to use setup of configuration by allowing null
//values
if(algorithm == null)
return this;
this.sequenceLearningAlgorithm = algorithm;
return this;
}
/**
* * Sets specific LearningAlgorithm as Elements Learning Algorithm
*
* @param algoName fully qualified class name
* @return
*/
public Builder<T> elementsLearningAlgorithm(String algoName) {
//allow easier to use setup of configuration by allowing null
//values
if(algoName == null)
return this;
this.elementsLearningAlgorithm = DL4JClassLoading.createNewInstance(algoName);
this.configuration.setElementsLearningAlgorithm(elementsLearningAlgorithm.getClass().getCanonicalName());
return this;
}
/**
* * Sets specific LearningAlgorithm as Elements Learning Algorithm
*
* @param algorithm ElementsLearningAlgorithm implementation
* @return
*/
public Builder<T> elementsLearningAlgorithm(ElementsLearningAlgorithm<T> algorithm) {
//allow easier to use setup of configuration by allowing null
//values
if(elementsLearningAlgorithm == null)
return this;
this.elementsLearningAlgorithm = algorithm;
return this;
}
/**
* This method defines batchSize option, viable only if iterations > 1
*
* @param batchSize
* @return
*/
public Builder<T> batchSize(int batchSize) {
this.batchSize = batchSize;
return this;
}
/**
* This method defines how many iterations should be done over batched sequences.
*
* @param iterations
* @return
*/
public Builder<T> iterations(int iterations) {
this.iterations = iterations;
return this;
}
/**
* This method defines how many iterations should be done over whole training corpus during modelling
* @param numEpochs
* @return
*/
public Builder<T> epochs(int numEpochs) {
this.numEpochs = numEpochs;
return this;
}
/**
* Sets number of worker threads to be used in the
* lower level linear algebra calculations used in
* calculating hierarchical softmax/sampling
*
* @param numWorkers
* @return
*/
public Builder<T> workers(int numWorkers) {
this.workers = numWorkers;
return this;
}
/**
* Sets number of threads running calculations.
* Note this is different from workers which affect
* the number of threads used to compute updates.
* This should be balanced with the number of workers.
* High number of threads will actually hinder performance.
*
* @param vectorCalcThreads the number of threads to compute updates
* @return
*/
public Builder<T> vectorCalcThreads(int vectorCalcThreads) {
this.vectorCalcThreads = vectorCalcThreads;
return this;
}
/**
* Enable/disable hierarchic softmax
*
* @param reallyUse
* @return
*/
public Builder<T> useHierarchicSoftmax(boolean reallyUse) {
this.useHierarchicSoftmax = reallyUse;
return this;
}
/**
* This method defines if Adaptive Gradients should be used in calculations
*
* @param reallyUse
* @return
*/
@Deprecated
public Builder<T> useAdaGrad(boolean reallyUse) {
this.useAdaGrad = reallyUse;
return this;
}
/**
* This method defines number of dimensions for outcome vectors.
* Please note: This option has effect only if lookupTable wasn't defined during building process.
*
* @param layerSize
* @return
*/
public Builder<T> layerSize(int layerSize) {
this.layerSize = layerSize;
return this;
}
/**
* This method defines initial learning rate.
* Default value is 0.025
*
* @param learningRate
* @return
*/
public Builder<T> learningRate(double learningRate) {
this.learningRate = learningRate;
return this;
}
/**
* This method defines minimal element frequency for elements found in the training corpus. All elements with frequency below this threshold will be removed before training.
* Please note: this method has effect only if vocabulary is built internally.
*
* @param minWordFrequency
* @return
*/
public Builder<T> minWordFrequency(int minWordFrequency) {
this.minWordFrequency = minWordFrequency;
return this;
}
/**
* This method sets vocabulary limit during construction.
*
* Default value: 0. Means no limit
*
* @param limit
* @return
*/
public Builder limitVocabularySize(int limit) {
if (limit < 0)
throw new DL4JInvalidConfigException("Vocabulary limit should be non-negative number");
this.vocabLimit = limit;
return this;
}
/**
* This method defines minimum learning rate after decay being applied.
* Default value is 0.01
*
* @param minLearningRate
* @return
*/
public Builder<T> minLearningRate(double minLearningRate) {
this.minLearningRate = minLearningRate;
return this;
}
/**
* This method defines, should all model be reset before training. If set to true, vocabulary and WeightLookupTable will be reset before training, and will be built from scratches
*
* @param reallyReset
* @return
*/
public Builder<T> resetModel(boolean reallyReset) {
this.resetModel = reallyReset;
return this;
}
/**
* You can pass externally built vocabCache object, containing vocabulary
*
* @param vocabCache
* @return
*/
public Builder<T> vocabCache(@NonNull VocabCache<T> vocabCache) {
this.vocabCache = vocabCache;
return this;
}
/**
* You can pass externally built WeightLookupTable, containing model weights and vocabulary.
*
* @param lookupTable
* @return
*/
public Builder<T> lookupTable(@NonNull WeightLookupTable<T> lookupTable) {
this.lookupTable = lookupTable;
this.layerSize(lookupTable.layerSize());
return this;
}
/**
* This method defines sub-sampling threshold.
*
* @param sampling
* @return
*/
public Builder<T> sampling(double sampling) {
this.sampling = sampling;
return this;
}
/**
* This method defines negative sampling value for skip-gram algorithm.
*
* @param negative
* @return
*/
public Builder<T> negativeSample(double negative) {
this.negative = negative;
return this;
}
/**
* You can provide collection of objects to be ignored, and excluded out of model
* Please note: Object labels and hashCode will be used for filtering
*
* @param stopList
* @return
*/
public Builder<T> stopWords(@NonNull List<String> stopList) {
this.stopWords.addAll(stopList);
return this;
}
/**
*
* @param trainElements
* @return
*/
public Builder<T> trainElementsRepresentation(boolean trainElements) {
this.trainElementsVectors = trainElements;
return this;
}
public Builder<T> trainSequencesRepresentation(boolean trainSequences) {
this.trainSequenceVectors = trainSequences;
return this;
}
/**
* You can provide collection of objects to be ignored, and excluded out of model
* Please note: Object labels and hashCode will be used for filtering
*
* @param stopList
* @return
*/
public Builder<T> stopWords(@NonNull Collection<T> stopList) {
for (T word : stopList) {
this.stopWords.add(word.getLabel());
}
return this;
}
/**
* Sets window size for skip-Gram training
*
* @param windowSize
* @return
*/
public Builder<T> windowSize(int windowSize) {
this.window = windowSize;
return this;
}
/**
* Sets seed for random numbers generator.
* Please note: this has effect only if vocabulary and WeightLookupTable is built internally
*
* @param randomSeed
* @return
*/
public Builder<T> seed(long randomSeed) {
// has no effect in original w2v actually
this.seed = randomSeed;
return this;
}
/**
* ModelUtils implementation, that will be used to access model.
* Methods like: similarity, wordsNearest, accuracy are provided by user-defined ModelUtils
*
* @param modelUtils model utils to be used
* @return
*/
public Builder<T> modelUtils(@NonNull ModelUtils<T> modelUtils) {
this.modelUtils = modelUtils;
return this;
}
/**
* This method allows you to specify, if UNK word should be used internally
* @param reallyUse
* @return
*/
public Builder<T> useUnknown(boolean reallyUse) {
this.useUnknown = reallyUse;
return this;
}
/**
* This method allows you to specify SequenceElement that will be used as UNK element, if UNK is used
* @param element
* @return
*/
public Builder<T> unknownElement(@NonNull T element) {
this.unknownElement = element;
this.UNK = element.getLabel();
return this;
}
/**
* This method allows to use variable window size. In this case, every batch gets processed using one of predefined window sizes
*
* @param windows
* @return
*/
public Builder<T> useVariableWindow(int... windows) {
if (windows == null || windows.length == 0)
throw new IllegalStateException("Variable windows can't be empty");
variableWindows = windows;
return this;
}
/**
* If set to true, initial weights for elements/sequences will be derived from elements themself.
* However, this implies additional cycle through input iterator.