-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMeansBuilder.java
76 lines (62 loc) · 2.65 KB
/
MeansBuilder.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
package com.example.vijay.sentimentanalysis_ondevice;
import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.deeplearning4j.text.documentiterator.LabelledDocument;
import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Simple utility class that builds centroid vector for LabelledDocument
* based on previously trained ParagraphVectors model
*
* @author raver119@gmail.com
*/
public class MeansBuilder {
private VocabCache<VocabWord> vocabCache;
private InMemoryLookupTable<VocabWord> lookupTable;
private TokenizerFactory tokenizerFactory;
public MeansBuilder(InMemoryLookupTable<VocabWord> lookupTable, TokenizerFactory tokenizerFactory) {
this.lookupTable = lookupTable;
this.vocabCache = lookupTable.getVocab();
this.tokenizerFactory = tokenizerFactory;
}
/**
* This method returns centroid (mean vector) for document.
*
* @param document
* @return
*/
public INDArray documentAsVector(LabelledDocument document) {
List<String> documentAsTokens = tokenizerFactory.create(document.getContent()).getTokens();
AtomicInteger cnt = new AtomicInteger(0);
for (String word: documentAsTokens) {
if (vocabCache.containsWord(word)) cnt.incrementAndGet();
}
INDArray allWords = Nd4j.create(cnt.get(), lookupTable.layerSize());
cnt.set(0);
for (String word: documentAsTokens) {
if (vocabCache.containsWord(word))
allWords.putRow(cnt.getAndIncrement(), lookupTable.vector(word));
}
INDArray mean = allWords.mean(0);
return mean;
}
public INDArray textAsVector(String rawText) {
List<String> documentAsTokens = tokenizerFactory.create(rawText).getTokens();
AtomicInteger cnt = new AtomicInteger(0);
for (String word: documentAsTokens) {
if (vocabCache.containsWord(word)) cnt.incrementAndGet();
}
INDArray allWords = Nd4j.create(cnt.get(), lookupTable.layerSize());
cnt.set(0);
for (String word: documentAsTokens) {
if (vocabCache.containsWord(word))
allWords.putRow(cnt.getAndIncrement(), lookupTable.vector(word));
}
INDArray mean = allWords.mean(0);
return mean;
}
}