-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
BarnesHutTsne.java
873 lines (702 loc) · 25.8 KB
/
BarnesHutTsne.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
/*-
*
* * Copyright 2015 Skymind,Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * 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.
*
*/
package org.deeplearning4j.plot;
import com.google.common.util.concurrent.AtomicDouble;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.util.FastMath;
import org.nd4j.linalg.primitives.Pair;
import org.deeplearning4j.clustering.sptree.DataPoint;
import org.deeplearning4j.clustering.sptree.SpTree;
import org.deeplearning4j.clustering.vptree.VPTree;
import org.deeplearning4j.nn.api.Model;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.gradient.DefaultGradient;
import org.deeplearning4j.nn.gradient.Gradient;
import org.deeplearning4j.optimize.api.ConvexOptimizer;
import org.deeplearning4j.optimize.api.IterationListener;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.BooleanIndexing;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.indexing.functions.Value;
import org.nd4j.linalg.learning.legacy.AdaGrad;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static org.nd4j.linalg.factory.Nd4j.*;
import static org.nd4j.linalg.ops.transforms.Transforms.pow;
import static org.nd4j.linalg.ops.transforms.Transforms.sign;
/**
* Barnes hut algorithm for TSNE, uses a dual tree approximation approach.
* Work based on:
* http://lvdmaaten.github.io/tsne/
* For hight dimensions, it's recommended to reduce the dimension up to 50 using another method (PCA or other)
* @author Adam Gibson
*/
@Slf4j
public class BarnesHutTsne implements Model {
protected int maxIter = 1000;
protected double realMin = Nd4j.EPS_THRESHOLD;
protected double initialMomentum = 0.5;
protected double finalMomentum = 0.8;
protected double minGain = 1e-2;
protected double momentum = initialMomentum;
protected int switchMomentumIteration = 100;
protected boolean normalize = true;
protected boolean usePca = false;
protected int stopLyingIteration = 250;
protected double tolerance = 1e-5;
protected double learningRate = 500;
protected AdaGrad adaGrad;
protected boolean useAdaGrad = true;
protected double perplexity = 30;
//protected INDArray gains,yIncs;
protected INDArray Y;
private int N;
private double theta;
private INDArray rows;
private INDArray cols;
private INDArray vals;
private String simiarlityFunction = "cosinesimilarity";
private boolean invert = true;
private INDArray x;
private int numDimensions = 0;
public final static String Y_GRAD = "yIncs";
private SpTree tree;
private INDArray gains;
private INDArray yIncs;
protected transient IterationListener iterationListener;
public BarnesHutTsne(int numDimensions, String simiarlityFunction, double theta, boolean invert, int maxIter,
double realMin, double initialMomentum, double finalMomentum, double momentum,
int switchMomentumIteration, boolean normalize, int stopLyingIteration, double tolerance,
double learningRate, boolean useAdaGrad, double perplexity, IterationListener iterationListener,
double minGain) {
this.maxIter = maxIter;
this.realMin = realMin;
this.initialMomentum = initialMomentum;
this.finalMomentum = finalMomentum;
this.momentum = momentum;
this.normalize = normalize;
this.useAdaGrad = useAdaGrad;
this.stopLyingIteration = stopLyingIteration;
this.learningRate = learningRate;
this.switchMomentumIteration = switchMomentumIteration;
this.tolerance = tolerance;
this.perplexity = perplexity;
this.minGain = minGain;
this.numDimensions = numDimensions;
this.simiarlityFunction = simiarlityFunction;
this.theta = theta;
this.iterationListener = iterationListener;
this.invert = invert;
}
public String getSimiarlityFunction() {
return simiarlityFunction;
}
public void setSimiarlityFunction(String simiarlityFunction) {
this.simiarlityFunction = simiarlityFunction;
}
public boolean isInvert() {
return invert;
}
public void setInvert(boolean invert) {
this.invert = invert;
}
public double getTheta() {
return theta;
}
public double getPerplexity() {
return perplexity;
}
public int getNumDimensions() {
return numDimensions;
}
public void setNumDimensions(int numDimensions) {
this.numDimensions = numDimensions;
}
/**
* Convert data to probability
* co-occurrences (aka calculating the kernel)
* @param d the data to convert
* @param u the perplexity of the model
* @return the probabilities of co-occurrence
*/
public INDArray computeGaussianPerplexity(final INDArray d, double u) {
N = d.rows();
final int k = (int) (3 * u);
if (u > k)
throw new IllegalStateException("Illegal k value " + k + "greater than " + u);
rows = zeros(1, N + 1);
cols = zeros(1, N * k);
vals = zeros(1, N * k);
for (int n = 0; n < N; n++)
rows.putScalar(n + 1, rows.getDouble(n) + k);
final INDArray beta = ones(N, 1);
final double logU = FastMath.log(u);
VPTree tree = new VPTree(d, simiarlityFunction, invert);
log.info("Calculating probabilities of data similarities...");
for (int i = 0; i < N; i++) {
if (i % 500 == 0)
log.info("Handled " + i + " records");
double betaMin = -Double.MAX_VALUE;
double betaMax = Double.MAX_VALUE;
List<DataPoint> results = new ArrayList<>();
tree.search(d.slice(i), k + 1, results, new ArrayList<Double>());
double betas = beta.getDouble(i);
INDArray cArr = VPTree.buildFromData(results);
Pair<INDArray, Double> pair = computeGaussianKernel(cArr, beta.getDouble(i), k);
INDArray currP = pair.getFirst();
double hDiff = pair.getSecond() - logU;
int tries = 0;
boolean found = false;
//binary search
while (!found && tries < 200) {
if (hDiff < tolerance && -hDiff < tolerance)
found = true;
else {
if (hDiff > 0) {
betaMin = betas;
if (betaMax == Double.MAX_VALUE || betaMax == -Double.MAX_VALUE)
betas *= 2;
else
betas = (betas + betaMax) / 2.0;
} else {
betaMax = betas;
if (betaMin == -Double.MAX_VALUE || betaMin == Double.MAX_VALUE)
betas /= 2.0;
else
betas = (betas + betaMin) / 2.0;
}
pair = computeGaussianKernel(cArr, betas, k);
hDiff = pair.getSecond() - logU;
tries++;
}
}
currP.divi(currP.sum(Integer.MAX_VALUE));
INDArray indices = Nd4j.create(1, k + 1);
for (int j = 0; j < indices.length(); j++) {
if (j >= results.size())
break;
indices.putScalar(j, results.get(j).getIndex());
}
for (int l = 0; l < k; l++) {
cols.putScalar(rows.getInt(i) + l, indices.getDouble(l + 1));
vals.putScalar(rows.getInt(i) + l, currP.getDouble(l));
}
}
return vals;
}
@Override
public INDArray input() {
return x;
}
@Override
public void validateInput() {
}
@Override
public ConvexOptimizer getOptimizer() {
return null;
}
@Override
public INDArray getParam(String param) {
return null;
}
@Override
public void initParams() {
}
@Override
public void addListeners(IterationListener... listener) {
// no-op
}
@Override
public Map<String, INDArray> paramTable() {
return null;
}
@Override
public Map<String, INDArray> paramTable(boolean backprapParamsOnly) {
return null;
}
@Override
public void setParamTable(Map<String, INDArray> paramTable) {
}
@Override
public void setParam(String key, INDArray val) {
}
@Override
public void clear() {}
@Override
public void applyConstraints(int iteration, int epoch) {
//No op
}
/* compute the gradient given the current solution, the probabilities and the constant */
protected Pair<Double, INDArray> gradient(INDArray p) {
throw new UnsupportedOperationException();
}
/**
* Symmetrize the value matrix
* @param rowP
* @param colP
* @param valP
* @return
*/
public INDArray symmetrized(INDArray rowP, INDArray colP, INDArray valP) {
INDArray rowCounts = Nd4j.create(N);
for (int n = 0; n < N; n++) {
int begin = rowP.getInt(n);
int end = rowP.getInt(n + 1);
for (int i = begin; i < end; i++) {
boolean present = false;
for (int m = rowP.getInt(colP.getInt(i)); m < rowP.getInt(colP.getInt(i) + 1); m++)
if (colP.getInt(m) == n) {
present = true;
}
if (present)
rowCounts.putScalar(n, rowCounts.getDouble(n) + 1);
else {
rowCounts.putScalar(n, rowCounts.getDouble(n) + 1);
rowCounts.putScalar(colP.getInt(i), rowCounts.getDouble(colP.getInt(i)) + 1);
}
}
}
int numElements = rowCounts.sum(Integer.MAX_VALUE).getInt(0);
INDArray offset = Nd4j.create(N);
INDArray symRowP = Nd4j.create(N + 1);
INDArray symColP = Nd4j.create(numElements);
INDArray symValP = Nd4j.create(numElements);
for (int n = 0; n < N; n++)
symRowP.putScalar(n + 1, symRowP.getDouble(n) + rowCounts.getDouble(n));
for (int n = 0; n < N; n++) {
for (int i = rowP.getInt(n); i < rowP.getInt(n + 1); i++) {
boolean present = false;
for (int m = rowP.getInt(colP.getInt(i)); m < rowP.getInt(colP.getInt(i)) + 1; m++) {
if (colP.getInt(m) == n) {
present = true;
if (n < colP.getInt(i)) {
// make sure we do not add elements twice
symColP.putScalar(symRowP.getInt(n) + offset.getInt(n), colP.getInt(i));
symColP.putScalar(symRowP.getInt(colP.getInt(i)) + offset.getInt(colP.getInt(i)), n);
symValP.putScalar(symRowP.getInt(n) + offset.getInt(n),
valP.getDouble(i) + valP.getDouble(m));
symValP.putScalar(symRowP.getInt(colP.getInt(i)) + offset.getInt(colP.getInt(i)),
valP.getDouble(i) + valP.getDouble(m));
}
}
}
// If (colP[i], n) is not present, there is no addition involved
if (!present) {
int colPI = colP.getInt(i);
if (n < colPI) {
symColP.putScalar(symRowP.getInt(n) + offset.getInt(n), colPI);
symColP.putScalar(symRowP.getInt(colP.getInt(i)) + offset.getInt(colPI), n);
symValP.putScalar(symRowP.getInt(n) + offset.getInt(n), valP.getDouble(i));
symValP.putScalar(symRowP.getInt(colPI) + offset.getInt(colPI), valP.getDouble(i));
}
}
// Update offsets
if (!present || (present && n < colP.getInt(i))) {
offset.putScalar(n, offset.getInt(n) + 1);
int colPI = colP.getInt(i);
if (colPI != n)
offset.putScalar(colPI, offset.getDouble(colPI) + 1);
}
}
}
// Divide the result by two
symValP.divi(2.0);
return symValP;
}
/**
* Computes a gaussian kernel
* given a vector of squared distance distances
*
* @param distances
* @param beta
* @return
*/
public Pair<INDArray, Double> computeGaussianKernel(INDArray distances, double beta, int k) {
// Compute Gaussian kernel row
INDArray currP = Nd4j.create(k);
for (int m = 0; m < k; m++)
currP.putScalar(m, FastMath.exp(-beta * distances.getDouble(m + 1)));
double sum = currP.sum(Integer.MAX_VALUE).getDouble(0);
double h = 0.0;
for (int m = 0; m < k; m++)
h += beta * (distances.getDouble(m + 1) * currP.getDouble(m));
h = (h / sum) + FastMath.log(sum);
return new Pair<>(currP, h);
}
/**
* Init the model
*/
@Override
public void init() {
}
/**
* Set the IterationListeners for the ComputationGraph (and all layers in the network)
*
* @param listeners
*/
@Override
public void setListeners(Collection<IterationListener> listeners) {
}
/**
* Set the IterationListeners for the ComputationGraph (and all layers in the network)
*
* @param listeners
*/
@Override
public void setListeners(IterationListener... listeners) {
}
@Override
public void fit() {
if (theta == 0.0) {
log.debug("theta == 0, using decomposed version, might be slow");
Tsne decomposedTsne = new Tsne(maxIter, realMin, initialMomentum, finalMomentum, minGain, momentum,
switchMomentumIteration, normalize, usePca, stopLyingIteration, tolerance, learningRate,
useAdaGrad, perplexity);
Y = decomposedTsne.calculate(x, numDimensions, perplexity);
} else {
//output
if (Y == null) {
Y = randn(x.rows(), numDimensions, Nd4j.getRandom()).muli(1e-3f);
}
computeGaussianPerplexity(x, perplexity);
vals = symmetrized(rows, cols, vals).divi(vals.sum(Integer.MAX_VALUE));
//lie about gradient
vals.muli(12);
for (int i = 0; i < maxIter; i++) {
step(vals, i);
if (i == switchMomentumIteration)
momentum = finalMomentum;
if (i == stopLyingIteration)
vals.divi(12);
if (iterationListener != null) {
iterationListener.iterationDone(this, i);
}
log.info("Error at iteration " + i + " is " + score());
}
}
}
@Override
public void update(Gradient gradient) {
}
/**
* An individual iteration
* @param p the probabilities that certain points
* are near each other
* @param i the iteration (primarily for debugging purposes)
*/
public void step(INDArray p, int i) {
update(gradient().getGradientFor(Y_GRAD), Y_GRAD);
}
@Override
public void update(INDArray gradient, String paramType) {
INDArray yGrads = gradient;
gains = gains.add(.2).muli(sign(yGrads)).neqi(sign(yIncs))
.addi(gains.mul(0.8).muli(sign(yGrads)).neqi(sign(yIncs)));
BooleanIndexing.applyWhere(gains, Conditions.lessThan(minGain), new Value(minGain));
INDArray gradChange = gains.mul(yGrads);
if (useAdaGrad) {
if (adaGrad == null) {
adaGrad = new AdaGrad(gradient.shape(), learningRate);
adaGrad.setStateViewArray(Nd4j.zeros(gradient.shape()).reshape(1, gradChange.length()),
gradChange.shape(), gradient.ordering(), true);
}
gradChange = adaGrad.getGradient(gradChange, 0);
}
else {
gradChange.muli(learningRate);
}
yIncs.muli(momentum).subi(gradChange);
Y.addi(yIncs);
}
/**
* Save the model as a file with a csv format, adding the label as the last column.
* @param labels
* @param path the path to write
* @throws IOException
*/
public void saveAsFile(List<String> labels, String path) throws IOException {
BufferedWriter write = null;
try {
write = new BufferedWriter(new FileWriter(new File(path)));
for (int i = 0; i < Y.rows(); i++) {
if (i >= labels.size())
break;
String word = labels.get(i);
if (word == null)
continue;
StringBuilder sb = new StringBuilder();
INDArray wordVector = Y.getRow(i);
for (int j = 0; j < wordVector.length(); j++) {
sb.append(wordVector.getDouble(j));
if (j < wordVector.length() - 1)
sb.append(",");
}
sb.append(",");
sb.append(word);
sb.append(" ");
sb.append("\n");
write.write(sb.toString());
}
write.flush();
write.close();
} finally {
if (write != null)
write.close();
}
}
/**
* Plot tsne
*
* @param matrix the matrix to plot
* @param nDims the number
* @param labels
* @param path the path to write
* @throws IOException
* @deprecated use {@link #fit(INDArray)} and {@link #saveAsFile(List, String)} instead.
*/
@Deprecated
public void plot(INDArray matrix, int nDims, List<String> labels, String path) throws IOException {
fit(matrix, nDims);
saveAsFile(labels, path);
}
@Override
public double score() {
// Get estimate of normalization term
INDArray buff = Nd4j.create(numDimensions);
AtomicDouble sum_Q = new AtomicDouble(0.0);
for (int n = 0; n < N; n++)
tree.computeNonEdgeForces(n, theta, buff, sum_Q);
// Loop over all edges to compute t-SNE error
double C = .0;
INDArray linear = Y;
for (int n = 0; n < N; n++) {
int begin = rows.getInt(n);
int end = rows.getInt(n + 1);
int ind1 = n;
for (int i = begin; i < end; i++) {
int ind2 = cols.getInt(i);
buff.assign(linear.slice(ind1));
buff.subi(linear.slice(ind2));
double Q = pow(buff, 2).sum(Integer.MAX_VALUE).getDouble(0);
Q = (1.0 / (1.0 + Q)) / sum_Q.doubleValue();
C += vals.getDouble(i) * FastMath.log(vals.getDouble(i) + Nd4j.EPS_THRESHOLD)
/ (Q + Nd4j.EPS_THRESHOLD);
}
}
return C;
}
@Override
public void computeGradientAndScore() {
}
@Override
public void accumulateScore(double accum) {
}
@Override
public INDArray params() {
return null;
}
@Override
public int numParams() {
return 0;
}
@Override
public int numParams(boolean backwards) {
return 0;
}
@Override
public void setParams(INDArray params) {
}
@Override
public void setParamsViewArray(INDArray params) {
throw new UnsupportedOperationException();
}
@Override
public INDArray getGradientsViewArray() {
throw new UnsupportedOperationException();
}
@Override
public void setBackpropGradientsViewArray(INDArray gradients) {
throw new UnsupportedOperationException();
}
@Override
public void applyLearningRateScoreDecay() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void fit(INDArray data) {
this.x = data;
fit();
}
/**
* Change the dimensions with
*
* @deprecated Use {@link #fit(INDArray)}
*/
@Deprecated
public void fit(INDArray data, int nDims) {
this.x = data;
this.numDimensions = nDims;
fit();
}
@Override
public void iterate(INDArray input) {
}
@Override
public Gradient gradient() {
if (yIncs == null)
yIncs = zeros(Y.shape());
if (gains == null)
gains = ones(Y.shape());
AtomicDouble sumQ = new AtomicDouble(0);
/* Calculate gradient based on barnes hut approximation with positive and negative forces */
INDArray posF = Nd4j.create(Y.shape());
INDArray negF = Nd4j.create(Y.shape());
if (tree == null)
tree = new SpTree(Y);
tree.computeEdgeForces(rows, cols, vals, N, posF);
for (int n = 0; n < N; n++)
tree.computeNonEdgeForces(n, theta, negF.slice(n), sumQ);
INDArray dC = posF.subi(negF.divi(sumQ));
Gradient ret = new DefaultGradient();
ret.gradientForVariable().put(Y_GRAD, dC);
return ret;
}
@Override
public Pair<Gradient, Double> gradientAndScore() {
return new Pair<>(gradient(), score());
}
@Override
public int batchSize() {
return 0;
}
@Override
public NeuralNetConfiguration conf() {
return null;
}
@Override
public void setConf(NeuralNetConfiguration conf) {
}
/**
* Return the matrix reduce to the NDim.
*/
public INDArray getData() {
return Y;
}
public void setData(INDArray data) {
this.Y = data;
}
public static class Builder {
private int maxIter = 1000;
private double realMin = 1e-12f;
private double initialMomentum = 5e-1f;
private double finalMomentum = 8e-1f;
private double momentum = 5e-1f;
private int switchMomentumIteration = 100;
private boolean normalize = true;
private int stopLyingIteration = 100;
private double tolerance = 1e-5f;
private double learningRate = 1e-1f;
private boolean useAdaGrad = false;
private double perplexity = 30;
private double minGain = 1e-1f;
private double theta = 0.5;
private boolean invert = true;
private int numDim = 2;
private String similarityFunction = "cosinesimilarity";
public Builder minGain(double minGain) {
this.minGain = minGain;
return this;
}
public Builder perplexity(double perplexity) {
this.perplexity = perplexity;
return this;
}
public Builder useAdaGrad(boolean useAdaGrad) {
this.useAdaGrad = useAdaGrad;
return this;
}
public Builder learningRate(double learningRate) {
this.learningRate = learningRate;
return this;
}
public Builder tolerance(double tolerance) {
this.tolerance = tolerance;
return this;
}
public Builder stopLyingIteration(int stopLyingIteration) {
this.stopLyingIteration = stopLyingIteration;
return this;
}
public Builder normalize(boolean normalize) {
this.normalize = normalize;
return this;
}
public Builder setMaxIter(int maxIter) {
this.maxIter = maxIter;
return this;
}
public Builder setRealMin(double realMin) {
this.realMin = realMin;
return this;
}
public Builder setInitialMomentum(double initialMomentum) {
this.initialMomentum = initialMomentum;
return this;
}
public Builder setFinalMomentum(double finalMomentum) {
this.finalMomentum = finalMomentum;
return this;
}
public Builder setMomentum(double momentum) {
this.momentum = momentum;
return this;
}
public Builder setSwitchMomentumIteration(int switchMomentumIteration) {
this.switchMomentumIteration = switchMomentumIteration;
return this;
}
public Builder similarityFunction(String similarityFunction) {
this.similarityFunction = similarityFunction;
return this;
}
public Builder invertDistanceMetric(boolean invert) {
this.invert = invert;
return this;
}
public Builder theta(double theta) {
this.theta = theta;
return this;
}
public Builder numDimension(int numDim) {
this.numDim = numDim;
return this;
}
public BarnesHutTsne build() {
return new BarnesHutTsne(numDim, similarityFunction, theta, invert, maxIter, realMin, initialMomentum,
finalMomentum, momentum, switchMomentumIteration, normalize, stopLyingIteration, tolerance,
learningRate, useAdaGrad, perplexity, null, minGain);
}
}
}