forked from lvdmaaten/bhtsne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsne.cpp
3152 lines (2695 loc) · 99.4 KB
/
tsne.cpp
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
/*
*
* Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the Delft University of Technology.
* 4. Neither the name of the Delft University of Technology nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
*/
#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <string>
#include "vptree.h"
#include "sptree.h"
#include "tsne.h"
using namespace std;
//const unsigned int POP_SIZE = 100;
static double sign(double x) { return (x == .0 ? .0 : (x < .0 ? -1.0 : 1.0)); }
static void zeroMean(double* X, int N, int D);
// Exact input similarities
static void computeExactGaussianInputSimilarity(double* X, int N, int D, double* P, double perplexity);
static void computeExactLaplacianInputSimilarity(double* X, int N, int D, double* P, double perplexity);
static void computeExactStudentInputSimilarity(double* X, int no_dims, int N, int D, double* P);
// BH input similarities
static void computeGaussianInputSimilarity(double* X, int N, int D, unsigned int** _row_P, unsigned int** _col_P, double** _val_P, double perplexity, int K);
static void computeLaplacianInputSimilarity(double* X, int N, int D, unsigned int** _row_P, unsigned int** _col_P, double** _val_P, double perplexity, int K);
static void computeStudentInputSimilarity(double* X, int no_dims, int N, int D, unsigned int** _row_P, unsigned int** _col_P, double** _val_P, int K);
static double randn();
static double randn(double mean, double stdDev);
// Exact gradients
static void computeExactGradientKL(double* P, double* Y, int N, int D, int freeze_index, double* dC);
// using ChiSq distributed output similarities Q
static void computeExactGradientKLChiSq(double* P, double* Y, int N, int D, double* dC);
// using Student0.5 distributed output similarities Q
static void computeExactGradientKLStudentHalf(double* P, double* Y, int N, int D, double* dC);
// using StudentAlpha distributed output similarities Q
static void computeExactGradientKLStudentAlpha(double* P, double* Y, int N, int D, double alpha, double* dC);
static void computeExactGradientRKL(double* P, double* Y, int N, int D, double* dC);
static void computeExactGradientJS(double* P, double* Y, int N, int D, double* dC);
// approximated exact gradients
static void approximateExactGradient(double* P, double* Y, int N, int D, double* dC, double costFunc(double*, int, double*));
// BH approximated gradients
static void computeApproxGradientKL(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, int freeze_index, double* dC, double theta);
// using ChiSq distributed output similarities Q
static void computeApproxGradientKLChiSq(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta);
// using Student0.5 distributed output similarities Q
static void computeApproxGradientKLStudentHalf(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta);
// using StudentAlpha distributed output similarities Q
static void computeApproxGradientKLStudentAlpha(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double alpha, double* dC, double theta);
static void computeApproxGradientRKL(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta);
static void computeApproxGradientJS(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta);
static void approximateApproxGradient(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D,
double* dC, double theta, double costFunc(unsigned int*, unsigned int*, double*, double*, int, int, double, double*));
// Exact cost functions
static double evaluateExactErrorKL(double* P, double* Y, int N, int D, double* costs);
static double evaluateExactErrorKL(double* P, int N, double* Q);
// using ChiSq distributed output similarities Q
static double evaluateExactErrorKLChiSq(double* P, double* Y, int N, int D, double* costs);
// using Student0.5 distributed output similarities Q
static double evaluateExactErrorKLStudentHalf(double* P, double* Y, int N, int D, double* costs);
// using StudentAlpha distributed output similarities Q
static double evaluateExactErrorKLStudentAlpha(double* P, double* Y, int N, int D, double alpha, double* costs);
static double evaluateExactErrorRKL(double* P, double* Y, int N, int D, double* costs);
static double evaluateExactErrorRKL(double* P, int N, double* Q);
static double evaluateExactErrorJS(double* P, double* Y, int N, int D, double* costs);
static double evaluateExactErrorJS(double* P, int N, double* Q);
// helper to compute KL(Q||M)
static double evaluateExactErrorJSQM(double* P, int N, double* Q);
// BH approximated cost functions
static double evaluateApproxErrorKL(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double theta, double* costs);
// using ChiSq distributed output similarities Q
static double evaluateApproxErrorKLChiSq(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double theta, double* costs);
// using Student0.5 distributed output similarities Q
static double evaluateApproxErrorKLStudentHalf(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double theta, double* costs);
// using StudentAlpha distributed output similarities Q
static double evaluateApproxErrorKLStudentAlpha(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double alpha, double theta, double* costs);
static double evaluateApproxErrorRKL(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double theta, double* costs);
static double evaluateApproxErrorJS(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double theta, double* costs);
// helper to compute KL(P||M)
//static double evaluateApproxErrorJSPM(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double theta, double* costs);
// helper to compute KL(Q||M)
static double evaluateApproxErrorJSQM(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int D, double theta);
static void computeEuclideanDistance(double* X, int N, int D, double* DD, bool squared);
static void updateEuclideanDistance(double* X, int N, int update_index, int D, double* DD, bool squared);
static void symmetrizeMatrix(unsigned int** row_P, unsigned int** col_P, double** val_P, int N);
// genetic algorithm optimizer
//static void computeExactGeneticOptimization(double* P, double* Y, double* Y_genomes, int N, int D, double costFunc(double*, int, double*));
static void computeExactGeneticOptimization(double* P, double* Y, int N, int iter, int D, double costFunc(double*, double*, int, int, double*));
static void computeApproxGeneticOptimization(unsigned int* row_P, unsigned int* col_P, double* val_P, double* Y, int N, int iter, int D, double theta,
double costFunc(unsigned int*, unsigned int*, double*, double*, int, int, double, double*));
static vector<pair<double, int>> sortArr(vector<double> arr, int n);
// Perform t-SNE
void TSNE::run(double* X, int N, int D, double* Y, double* costs, int* landmarks, int no_dims, double perplexity, double eta,
double momentum, double final_momentum, double theta, int rand_seed, bool skip_random_init, int max_iter,
int lying_factor, int stop_lying_iter, int start_lying_iter, int mom_switch_iter, int input_similarities,
int output_similarities, int cost_function, int optimization, int freeze_index) {
double alpha = 0.1;
// Set random seed
if (skip_random_init != true) {
if(rand_seed >= 0) {
printf("Using random seed: %d\n", rand_seed);
srand((unsigned int) rand_seed);
} else {
printf("Using current time as random seed...\n");
srand(time(NULL));
}
}
// Determine whether we are using an exact algorithm
if(N - 1 < 3 * perplexity) { printf("Perplexity too large for the number of data points!\n"); exit(1); }
//printf("Using no_dims = %d, perplexity = %f, exaggeration factor = %d, theta = %f\nlearning rate = %f, momentum = %f, final momentum = %f, momentum switch iter = %d\nstop lying iter = %d, restart lying iter = %d\n", no_dims, perplexity, lying_factor, theta, eta, momentum, final_momentum, mom_switch_iter, stop_lying_iter, start_lying_iter);
bool exact = (theta == .0) ? true : false;
// Set learning parameters
float total_time = .0;
clock_t start, end;
// Allocate some memory
double* dY = (double*)malloc(N * no_dims * sizeof(double));
double* uY = (double*)malloc(N * no_dims * sizeof(double));
double* gains = (double*)malloc(N * no_dims * sizeof(double));
if (dY == NULL || uY == NULL || gains == NULL) { printf("Memory allocation failed!\n"); exit(1); }
for (int i = 0; i < N * no_dims; i++) uY[i] = .0;
for (int i = 0; i < N * no_dims; i++) gains[i] = 1.0;
// Normalize input data (to prevent numerical problems)
printf("Computing input similarities...\n");
start = clock();
zeroMean(X, N, D);
double max_X = .0;
for(int i = 0; i < N * D; i++) {
if(fabs(X[i]) > max_X) max_X = fabs(X[i]);
}
for(int i = 0; i < N * D; i++) X[i] /= max_X;
// Compute input similarities for exact t-SNE
double* P; unsigned int* row_P; unsigned int* col_P; double* val_P;
if(exact) {
// Compute similarities
printf("Exact?");
P = (double*) malloc(N * N * sizeof(double));
if(P == NULL) { printf("Memory allocation failed!\n"); exit(1); }
switch (input_similarities) {
case 1:
computeExactLaplacianInputSimilarity(X, N, D, P, perplexity);
break;
case 2:
computeExactStudentInputSimilarity(X, no_dims, N, D, P);
break;
default:
computeExactGaussianInputSimilarity(X, N, D, P, perplexity);
}
// Symmetrize input similarities
printf("Symmetrizing...\n");
int nN = 0;
for(int n = 0; n < N; n++) {
int mN = (n + 1) * N;
for(int m = n + 1; m < N; m++) {
P[nN + m] += P[mN + n];
P[mN + n] = P[nN + m];
mN += N;
}
nN += N;
}
double sum_P = .0;
for(int i = 0; i < N * N; i++) sum_P += P[i];
for(int i = 0; i < N * N; i++) P[i] /= sum_P;
}
// Compute input similarities for approximate t-SNE
else {
// Compute asymmetric pairwise input similarities
switch (input_similarities) {
case 1:
computeLaplacianInputSimilarity(X, N, D, &row_P, &col_P, &val_P, perplexity, (int)(3 * perplexity));
break;
case 2:
computeStudentInputSimilarity(X, no_dims, N, D, &row_P, &col_P, &val_P, (int)(3 * perplexity));
break;
default:
computeGaussianInputSimilarity(X, N, D, &row_P, &col_P, &val_P, perplexity, (int)(3 * perplexity));
}
// Symmetrize input similarities
symmetrizeMatrix(&row_P, &col_P, &val_P, N);
double sum_P = .0;
for(int i = 0; i < row_P[N]; i++) sum_P += val_P[i];
for(int i = 0; i < row_P[N]; i++) val_P[i] /= sum_P;
}
end = clock();
// Lie about the P-values
if(exact) { for(int i = 0; i < N * N; i++) P[i] *= lying_factor; } //default was 12.0
else { for(int i = 0; i < row_P[N]; i++) val_P[i] *= lying_factor; } //default was 12.0
if(exact) printf("Input similarities computed in %4.2f seconds!\nLearning embedding...\n", (float) (end - start) / CLOCKS_PER_SEC);
else printf("Input similarities computed in %4.2f seconds (sparsity = %f)!\nLearning embedding...\n", (float) (end - start) / CLOCKS_PER_SEC, (double) row_P[N] / ((double) N * (double) N));
//always randomly init Y for genetic optimizer
if (optimization == 1) {
printf("Initializing Y (Chromosomes) at random!\n");
for (int i = 0; i < N * no_dims * N; i++) Y[i] = randn() * .0001;
}
// Initialize solution (randomly)
else {
if (skip_random_init != true) {
printf("Initializing Y at random!\n");
for (int i = 0; i < N * no_dims; i++) Y[i] = randn() * .0001;
}
else {
printf("Skip random initialization of Y!\n");
// check whether a freeze index is passed that is > 0
// which would indicate the remainder freeze_index < n < N to be initialized at random
if (freeze_index != 0) {
printf("Still, test observations are initialized at random!\n");
for (int i = freeze_index * no_dims; i < N * no_dims; i++) Y[i] = randn() * .0001;
}
}
}
string cost_function_name;
// Save results of iteration 0
double C = .0;
if (exact) {
switch (cost_function) {
case 1:
C = evaluateExactErrorRKL(P, Y, N, no_dims, costs);
cost_function_name = "RKL";
break;
case 2:
C = evaluateExactErrorJS(P, Y, N, no_dims, costs);
cost_function_name = "JS";
break;
default:
cost_function_name = "KL";
switch (output_similarities) {
case 1:
C = evaluateExactErrorKLChiSq(P, Y, N, no_dims, costs);
break;
case 2:
C = evaluateExactErrorKLStudentHalf(P, Y, N, no_dims, costs);
break;
case 3:
C = evaluateExactErrorKLStudentAlpha(P, Y, N, no_dims, alpha, costs);
break;
default:
C = evaluateExactErrorKL(P, Y, N, no_dims, costs);
}
}
}
else { // doing approximate computation here!
switch (cost_function) {
case 1:
cost_function_name = "RKL";
C = evaluateApproxErrorRKL(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
case 2:
cost_function_name = "JS";
C = evaluateApproxErrorJS(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
default:
cost_function_name = "KL";
switch (output_similarities) {
case 1:
C = evaluateApproxErrorKLChiSq(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
case 2:
C = evaluateApproxErrorKLStudentHalf(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
case 3:
C = evaluateApproxErrorKLStudentAlpha(row_P, col_P, val_P, Y, N, no_dims, alpha, theta, costs);
break;
default:
C = evaluateApproxErrorKL(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
//C_compare = evaluateApproxErrorJS(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
}
}
}
printf("Initial Solution: %s error is %f\n", cost_function_name.c_str(), C);
save_data(Y, landmarks, costs, N, no_dims, 0);
// Perform main training loop
start = clock();
for(int iter = 0; iter < max_iter; iter++) {
// set costs to 0
for (int i = 0; i < N; i++) costs[i] = 0.0;
if (optimization == 0) {
// Compute gradient
if (exact) {
switch (cost_function) {
case 1:
computeExactGradientRKL(P, Y, N, no_dims, dY);
//approximateExactGradient(P, Y, N, no_dims, dY, evaluateExactErrorRKL);
break;
case 2:
computeExactGradientJS(P, Y, N, no_dims, dY);
//approximateExactGradient(P, Y, N, no_dims, dY, evaluateExactErrorJS);
break;
default:
switch (output_similarities) {
case 1:
computeExactGradientKLChiSq(P, Y, N, no_dims, dY);
break;
case 2:
computeExactGradientKLStudentHalf(P, Y, N, no_dims, dY);
break;
case 3:
computeExactGradientKLStudentAlpha(P, Y, N, no_dims, alpha, dY);
break;
default:
computeExactGradientKL(P, Y, N, no_dims, freeze_index, dY);
//approximateExactGradient(P, Y, N, no_dims, dY, evaluateExactErrorKL);
break;
}
}
}
// Compute approximate gradient
else {
switch (cost_function) {
case 1:
//computeApproxGradientRKL(row_P, col_P, val_P, Y, N, no_dims, dY, theta);
approximateApproxGradient(row_P, col_P, val_P, Y, N, no_dims, dY, theta, evaluateApproxErrorRKL);
break;
case 2:
computeApproxGradientJS(row_P, col_P, val_P, Y, N, no_dims, dY, theta);
//approximateApproxGradient(row_P, col_P, val_P, Y, N, no_dims, dY, theta, evaluateApproxErrorJS);
break;
default:
switch (output_similarities) {
case 1:
computeApproxGradientKLChiSq(row_P, col_P, val_P, Y, N, no_dims, dY, theta);
break;
case 2:
computeApproxGradientKLStudentHalf(row_P, col_P, val_P, Y, N, no_dims, dY, theta);
break;
case 3:
computeApproxGradientKLStudentAlpha(row_P, col_P, val_P, Y, N, no_dims, alpha, dY, theta);
break;
default:
computeApproxGradientKL(row_P, col_P, val_P, Y, N, no_dims, freeze_index, dY, theta);
//approximateApproxGradient(row_P, col_P, val_P, Y, N, no_dims, dY, theta, evaluateApproxErrorKL);
break;
}
}
}
// Update gains
for (int i = freeze_index * no_dims; i < N * no_dims; i++) gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8);
for (int i = freeze_index * no_dims; i < N * no_dims; i++) if (gains[i] < .01) gains[i] = .01;
// Perform gradient update (with momentum and gains)
for (int i = freeze_index * no_dims; i < N * no_dims; i++) uY[i] = momentum * uY[i] - eta * gains[i] * dY[i];
for (int i = freeze_index * no_dims; i < N * no_dims; i++) Y[i] = Y[i] + uY[i];
}
else {
if (exact) {
computeExactGeneticOptimization(P, Y, N, iter, no_dims, evaluateExactErrorKL);
}
else {
computeApproxGeneticOptimization(row_P, col_P, val_P, Y, N, iter, no_dims, theta, evaluateApproxErrorKL);
}
}
// Make solution zero-mean
zeroMean(Y, N, no_dims);
// Stop lying about the P-values after a while, and switch momentum
if(iter + 1 == stop_lying_iter) {
if(exact) { for(int i = 0; i < N * N; i++) P[i] /= lying_factor; } //default was 12.0
else { for(int i = 0; i < row_P[N]; i++) val_P[i] /= lying_factor; } //default was 12.0
}
if(iter + 1 == mom_switch_iter) momentum = final_momentum;
// Start lying againg about the P-values for the final iterations
if (iter + 1 == start_lying_iter) {
if (exact) { for (int i = 0; i < N * N; i++) P[i] *= lying_factor; } //default was 12.0
else { for (int i = 0; i < row_P[N]; i++) val_P[i] *= lying_factor; } //default was 12.0
}
// Print out progress and save intermediate results
// if (iter > 0 && (iter % 50 == 0 || iter == max_iter - 1)) {
if ((iter == 0 || (iter + 1) % 50 == 0 || iter == max_iter - 1)) {
end = clock();
C = .0;
if (exact) {
switch (cost_function) {
case 1:
C = evaluateExactErrorRKL(P, Y, N, no_dims, costs);
break;
case 2:
C = evaluateExactErrorJS(P, Y, N, no_dims, costs);
break;
default:
switch (output_similarities) {
case 1:
C = evaluateExactErrorKLChiSq(P, Y, N, no_dims, costs);
break;
case 2:
C = evaluateExactErrorKLStudentHalf(P, Y, N, no_dims, costs);
break;
case 3:
C = evaluateExactErrorKLStudentAlpha(P, Y, N, no_dims, alpha, costs);
break;
default:
C = evaluateExactErrorKL(P, Y, N, no_dims, costs);
}
}
}
else { // doing approximate computation here!
switch (cost_function) {
case 1:
C = evaluateApproxErrorRKL(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
case 2:
C = evaluateApproxErrorJS(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
default:
switch (output_similarities) {
case 1:
C = evaluateApproxErrorKLChiSq(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
case 2:
C = evaluateApproxErrorKLStudentHalf(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
break;
case 3:
C = evaluateApproxErrorKLStudentAlpha(row_P, col_P, val_P, Y, N, no_dims, alpha, theta, costs);
break;
default:
C = evaluateApproxErrorKL(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
//C_compare = evaluateApproxErrorJS(row_P, col_P, val_P, Y, N, no_dims, theta, costs);
}
}
}
if (iter == 0) {
printf("Iteration %d: %s error is %f\n", iter + 1, cost_function_name.c_str(), C);
}
else {
total_time += (float) (end - start) / CLOCKS_PER_SEC;
printf("Iteration %d: %s error is %f (50 iterations in %4.2f seconds)\n", iter + 1, cost_function_name.c_str(), C, (float) (end - start) / CLOCKS_PER_SEC);
//printf("Iteration %d: JS error would be %f (50 iterations in %4.2f seconds)\n", iter + 1, C_compare, (float)(end - start) / CLOCKS_PER_SEC);
}
//no matter whether iteration is 0 or % 50 == 0 or max_iter - 1, save the current results
save_data(Y, landmarks, costs, N, no_dims, iter + 1);
start = clock();
}
}
end = clock(); total_time += (float) (end - start) / CLOCKS_PER_SEC;
// Clean up memory
free(dY);
free(uY);
free(gains);
if(exact) free(P);
else {
free(row_P); row_P = NULL;
free(col_P); col_P = NULL;
free(val_P); val_P = NULL;
}
printf("Fitting performed in %4.2f seconds.\n", total_time);
}
// Compute gradient of the t-SNE cost function (KL - using Barnes-Hut algorithm)
static void computeApproxGradientKL(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, int freeze_index, double* dC, double theta)
{
// Construct space-partitioning tree on current map
SPTree* tree = new SPTree(D, Y, N);
// Compute all terms required for t-SNE gradient
double sum_Q = .0;
double* pos_f = (double*) calloc(N * D, sizeof(double));
double* neg_f = (double*) calloc(N * D, sizeof(double));
if(pos_f == NULL || neg_f == NULL) { printf("Memory allocation failed!\n"); exit(1); }
tree->computeEdgeForcesKL(inp_row_P, inp_col_P, inp_val_P, N, pos_f);
for(int n = 0; n < N; n++) tree->computeNonEdgeForcesKL(n, theta, neg_f + n * D, &sum_Q);
// Compute final t-SNE gradient
for(int i = 0; i < N * D; i++) {
dC[i] = pos_f[i] - (neg_f[i] / sum_Q);
}
free(pos_f);
free(neg_f);
delete tree;
}
// Compute gradient of the t-SNE cost function (KL - ChiSq - using Barnes-Hut algorithm)
void computeApproxGradientKLChiSq(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta)
{
// Construct space-partitioning tree on current map
SPTree* tree = new SPTree(D, Y, N);
// Compute all terms required for t-SNE gradient
double sum_Q = .0;
double* pos_f = (double*)calloc(N * D, sizeof(double));
double* neg_f = (double*)calloc(N * D, sizeof(double));
if (pos_f == NULL || neg_f == NULL) { printf("Memory allocation failed!\n"); exit(1); }
// compute Edge forces
unsigned int ind1 = 0;
unsigned int ind2 = 0;
for (unsigned int n = 0; n < N; n++) {
for (unsigned int i = inp_row_P[n]; i < inp_row_P[n + 1]; i++) {
// Compute pairwise distance and Q-value
double dist = 0.0;
ind2 = inp_col_P[i] * D;
for (unsigned int d = 0; d < D; d++) {
double diff = Y[ind1 + d] - Y[ind2 + d];
dist += diff * diff;
}
dist = sqrt(dist);
double mult = inp_val_P[i] / dist;
// Sum positive force
for (unsigned int d = 0; d < D; d++) {
double diff = Y[ind1 + d] - Y[ind2 + d];
pos_f[ind1 + d] += mult * diff;
}
}
ind1 += D;
}
for (int n = 0; n < N; n++) tree->computeNonEdgeForcesKLChiSq(n, theta, neg_f + n * D, &sum_Q);
// Compute final t-SNE gradient
for (int i = 0; i < N * D; i++) {
dC[i] = pos_f[i] - (neg_f[i] / sum_Q);
}
free(pos_f);
free(neg_f);
delete tree;
}
void computeApproxGradientKLStudentHalf(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta)
{
// Construct space-partitioning tree on current map
SPTree* tree = new SPTree(D, Y, N);
// Compute all terms required for t-SNE gradient
double sum_Q = .0;
double* pos_f = (double*)calloc(N * D, sizeof(double));
double* neg_f = (double*)calloc(N * D, sizeof(double));
if (pos_f == NULL || neg_f == NULL) { printf("Memory allocation failed!\n"); exit(1); }
// Loop over all edges in the graph
unsigned int ind1 = 0;
unsigned int ind2 = 0;
for (unsigned int n = 0; n < N; n++) {
for (unsigned int i = inp_row_P[n]; i < inp_row_P[n + 1]; i++) {
// Compute pairwise distance and Q-value
double dist = 0.0;
ind2 = inp_col_P[i] * D;
for (unsigned int d = 0; d < D; d++) {
double diff = Y[ind1 + d] - Y[ind2 + d];
dist += diff * diff;
}
double mult = inp_val_P[i] / (1 + 2 * dist);
// Sum positive force
for (unsigned int d = 0; d < D; d++) {
double diff = Y[ind1 + d] - Y[ind2 + d];
pos_f[ind1 + d] += mult * diff;
}
}
ind1 += D;
}
for (int n = 0; n < N; n++) tree->computeNonEdgeForcesKLStudentHalf(n, theta, neg_f + n * D, &sum_Q);
// Compute final t-SNE gradient
for (int i = 0; i < N * D; i++) {
dC[i] = pos_f[i] - (neg_f[i] / sum_Q);
}
free(pos_f);
free(neg_f);
delete tree;
}
void computeApproxGradientKLStudentAlpha(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double alpha, double* dC, double theta)
{
// Construct space-partitioning tree on current map
SPTree* tree = new SPTree(D, Y, N);
// Compute all terms required for t-SNE gradient
double sum_Q = .0;
double* pos_f = (double*)calloc(N * D, sizeof(double));
double* neg_f = (double*)calloc(N * D, sizeof(double));
if (pos_f == NULL || neg_f == NULL) { printf("Memory allocation failed!\n"); exit(1); }
// Loop over all edges in the graph
unsigned int ind1 = 0;
unsigned int ind2 = 0;
for (unsigned int n = 0; n < N; n++) {
for (unsigned int i = inp_row_P[n]; i < inp_row_P[n + 1]; i++) {
// Compute pairwise distance and Q-value
double dist = 0.0;
ind2 = inp_col_P[i] * D;
for (unsigned int d = 0; d < D; d++) {
double diff = Y[ind1 + d] - Y[ind2 + d];
dist += diff * diff;
}
double mult = inp_val_P[i] / (1 + dist/alpha);
// Sum positive force
for (unsigned int d = 0; d < D; d++) {
double diff = Y[ind1 + d] - Y[ind2 + d];
pos_f[ind1 + d] += mult * diff;
}
}
ind1 += D;
}
for (int n = 0; n < N; n++) tree->computeNonEdgeForcesKLStudentAlpha(n, alpha, theta, neg_f + n * D, &sum_Q);
// Compute final t-SNE gradient
for (int i = 0; i < N * D; i++) {
dC[i] = pos_f[i] - (neg_f[i] / sum_Q);
}
free(pos_f);
free(neg_f);
delete tree;
}
// Compute gradient of the t-SNE cost function (RKL - using Barnes-Hut algorithm)
static void computeApproxGradientRKL(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta)
{
// First, compute cost CRKL (inefficient in the current way)
double* costs = (double*)calloc(N, sizeof(double));
double cRKL = evaluateApproxErrorRKL(inp_row_P, inp_col_P, inp_val_P, Y, N, D, theta, costs);
free(costs); costs = NULL;
// Construct space-partitioning tree on current map
SPTree* tree = new SPTree(D, Y, N);
// Compute all terms required for t-SNE gradient
double sum_Q = .0;
// depends on dimension d
double* term_1 = (double*)calloc(N * D, sizeof(double));
double* term_2 = (double*)calloc(N * D, sizeof(double));
double* term_3 = (double*)calloc(N * D, sizeof(double));
if (term_1 == NULL || term_2 == NULL || term_3 == NULL) { printf("Memory allocation failed!\n"); exit(1); }
for (int n = 0; n < N; n++) tree->computeNonEdgeForcesRKLGradient(n, theta, term_1 + n * D,
term_2 + n * D,
term_3 + n * D,
&sum_Q,
inp_row_P, inp_col_P);
// Compute final t-SNE gradient nonedge forces
for (int n = 0; n < N; n++) {
for (int d = 0; d < D; d++) {
dC[n * D + d] = term_1[n * D + d];
dC[n * D + d] -= term_2[n * D + d];
dC[n * D + d] += log(sum_Q) * term_3[n * D + d];
dC[n * D + d] += cRKL * term_3[n * D + d];
dC[n * D + d] /= sum_Q;
}
}
// Compute final t-SNE gradient Edge forces
double* buff = (double*)calloc(D, sizeof(double));
int ind1, ind2;
double C = .0, E;
for (int n = 0; n < N; n++) {
ind1 = n * D;
for (int i = inp_row_P[n]; i < inp_row_P[n + 1]; i++) {
E = .0;
ind2 = inp_col_P[i] * D;
for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d];
for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d];
for (int d = 0; d < D; d++) E += buff[d] * buff[d];
E = (1.0 / (1.0 + E));
// finally, add to gradient
for (int d = 0; d < D; d++) {
dC[n * D + d] += log(inp_val_P[n * D]) * E * E / sum_Q * buff[d];
}
}
}
// Cleanup memory
free(buff);
free(term_1); term_1 = NULL;
free(term_2); term_2 = NULL;
free(term_3); term_3 = NULL;
delete tree;
}
// Compute gradient of the t-SNE cost function (JS - using Barnes-Hut algorithm)
void computeApproxGradientJS(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D, double* dC, double theta)
{
// First, compute cost CJSQM (inefficient in the current way)
//double* costs = (double*)calloc(N, sizeof(double));
double cJSQM = evaluateApproxErrorJSQM(inp_row_P, inp_col_P, inp_val_P, Y, N, D, theta);
//free(costs); costs = NULL;
// Construct space-partitioning tree on current map
SPTree* tree = new SPTree(D, Y, N);
// Compute all terms required for t-SNE gradient
double sum_Q = .0;
// depends on dimension d
double* term_1 = (double*)calloc(N * D, sizeof(double));
double* term_2 = (double*)calloc(N * D, sizeof(double));
if (term_1 == NULL || term_2 == NULL) { printf("Memory allocation failed!\n"); exit(1); }
for (int n = 0; n < N; n++) tree->computeNonEdgeForcesJSGradient(n, theta, term_1 + n * D, term_2 + n * D, &sum_Q,
inp_row_P, inp_col_P);
// Compute final t-SNE gradient nonedge forces
for (int n = 0; n < N; n++) {
for (int d = 0; d < D; d++) {
dC[n * D + d] = log(0.5) * term_1[n * D + d];
dC[n * D + d] += cJSQM * term_2[n * D + d];
dC[n * D + d] /= sum_Q;
}
}
// Compute final t-SNE gradient Edge forces
double* buff = (double*)calloc(D, sizeof(double));
int ind1, ind2;
double C = .0, E;
for (int n = 0; n < N; n++) {
ind1 = n * D;
for (int i = inp_row_P[n]; i < inp_row_P[n + 1]; i++) {
E = .0;
ind2 = inp_col_P[i] * D;
for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d];
for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d];
for (int d = 0; d < D; d++) E += buff[d] * buff[d];
E = (1.0 / (1.0 + E));
// finally, add to gradient
for (int d = 0; d < D; d++) {
dC[n * D + d] += (log((0.5 * inp_val_P[n * D] + 0.5 * E / sum_Q) / (E / sum_Q)) + cJSQM) * E * E / sum_Q * buff[d];
}
}
}
// Cleanup memory
free(buff);
free(term_1); term_1 = NULL;
free(term_2); term_2 = NULL;
delete tree;
}
static void approximateApproxGradient(unsigned int* inp_row_P, unsigned int* inp_col_P, double* inp_val_P, double* Y, int N, int D,
double* dC, double theta, double costFunc(unsigned int*, unsigned int*, double*, double*, int, int, double, double*))
{
// interval range
double h = sqrt(DBL_EPSILON);
double* costs = (double*)calloc(N, sizeof(double));
// Compute final t-SNE gradient
for (int n = 0; n < N; n++) {
for (int d = 0; d < D; d++) {
//dC[i] = (f(x_i + h) - (f(x_i - h)) / 2h
// increment Y[nD + d] by h
Y[n * D + d] += h;
dC[n * D + d] = costFunc(inp_row_P, inp_col_P, inp_val_P, Y, N, D, theta, costs);
// subtract Y[nD + d] with h
Y[n * D + d] -= (2 * h);
dC[n * D + d] -= costFunc(inp_row_P, inp_col_P, inp_val_P, Y, N, D, theta, costs);
//correct Y[nD + d] to original value
Y[n * D + d] += h;
//divide by 2h to obtain final gradient
dC[n * D + d] /= (2 * h);
}
}
free(costs); costs = NULL;
}
// Compute gradient of the t-SNE cost function (KL - exact)
static void computeExactGradientKL(double* P, double* Y, int N, int D, int freeze_index, double* dC) {
// Make sure the current gradient contains zeros
for(int i = 0; i < N * D; i++) dC[i] = 0.0;
// Compute the squared Euclidean distance matrix
double* DD = (double*) malloc(N * N * sizeof(double));
if(DD == NULL) { printf("Memory allocation failed!\n"); exit(1); }
computeEuclideanDistance(Y, N, D, DD, true);
// Compute Q-matrix and normalization sum
double* Q = (double*) malloc(N * N * sizeof(double));
if(Q == NULL) { printf("Memory allocation failed!\n"); exit(1); }
double sum_Q = .0;
int nN = 0;
for(int n = 0; n < N; n++) {
for(int m = 0; m < N; m++) {
if(n != m) {
Q[nN + m] = 1 / (1 + DD[nN + m]);
sum_Q += Q[nN + m];
}
}
nN += N;
}
// Perform the computation of the gradient
nN = 0;
int nD = 0;
for(int n = 0; n < N; n++) {
int mD = 0;
for(int m = 0; m < N; m++) {
if(n != m) {
double mult = (P[nN + m] - (Q[nN + m] / sum_Q)) * Q[nN + m];
for(int d = 0; d < D; d++) {
dC[nD + d] += (Y[nD + d] - Y[mD + d]) * mult;
}
}
mD += D;
}
nN += N;
nD += D;
}
// Free memory
free(DD); DD = NULL;
free(Q); Q = NULL;
}
// Compute gradient of the t-SNE cost function (KL - ChiSq - exact)
void computeExactGradientKLChiSq(double* P, double* Y, int N, int D, double* dC)
{
// Make sure the current gradient contains zeros
for (int i = 0; i < N * D; i++) dC[i] = 0.0;
// Compute the Euclidean distance matrix
double* DD = (double*)malloc(N * N * sizeof(double));
if (DD == NULL) { printf("Memory allocation failed!\n"); exit(1); }
computeEuclideanDistance(Y, N, D, DD, false);
// Compute Q-matrix and normalization sum
double* Q = (double*)malloc(N * N * sizeof(double));
if (Q == NULL) { printf("Memory allocation failed!\n"); exit(1); }
double sum_Q = .0;
int nN = 0;
for (int n = 0; n < N; n++) {
for (int m = 0; m < N; m++) {
if (n != m) {
Q[nN + m] = exp(-0.5 * DD[nN + m]);
sum_Q += Q[nN + m];
}
}
nN += N;
}
for (int i = 0; i < N * N; i++) Q[i] /= sum_Q;
// Perform the computation of the gradient
nN = 0;
int nD = 0;
for (int n = 0; n < N; n++) {
int mD = 0;
for (int m = 0; m < N; m++) {
if (n != m) {
double mult = (P[nN + m] - Q[nN + m]) / DD[nN + m];
for (int d = 0; d < D; d++) {
dC[nD + d] += (Y[nD + d] - Y[mD + d]) * mult;
}
}
mD += D;
}
nN += N;
nD += D;
}
// Free memory
free(DD); DD = NULL;
free(Q); Q = NULL;
}
void computeExactGradientKLStudentHalf(double* P, double* Y, int N, int D, double* dC)
{
// Make sure the current gradient contains zeros
for (int i = 0; i < N * D; i++) dC[i] = 0.0;
// Compute the squared Euclidean distance matrix
double* DD = (double*)malloc(N * N * sizeof(double));
if (DD == NULL) { printf("Memory allocation failed!\n"); exit(1); }
computeEuclideanDistance(Y, N, D, DD, true);
// Compute Q-matrix and normalization sum
double* Q = (double*)malloc(N * N * sizeof(double));
if (Q == NULL) { printf("Memory allocation failed!\n"); exit(1); }
double sum_Q = .0;
int nN = 0;
for (int n = 0; n < N; n++) {
for (int m = 0; m < N; m++) {
if (n != m) {
Q[nN + m] = pow(1 + 2 * DD[nN + m], -3.0/4.0);
sum_Q += Q[nN + m];
}
}
nN += N;
}
// Perform the computation of the gradient
nN = 0;
int nD = 0;
for (int n = 0; n < N; n++) {
int mD = 0;
for (int m = 0; m < N; m++) {
if (n != m) {
double mult = (P[nN + m] - (Q[nN + m] / sum_Q)) * pow(Q[nN + m], 4.0/3.0);
for (int d = 0; d < D; d++) {
dC[nD + d] += (Y[nD + d] - Y[mD + d]) * mult;
}
}
mD += D;
}
nN += N;
nD += D;
}
// Free memory
free(DD); DD = NULL;
free(Q); Q = NULL;
}
void computeExactGradientKLStudentAlpha(double* P, double* Y, int N, int D, double alpha, double* dC)
{
// Make sure the current gradient contains zeros
for (int i = 0; i < N * D; i++) dC[i] = 0.0;