-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathofxTSNE.cpp
98 lines (81 loc) · 2.35 KB
/
ofxTSNE.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
#include "ofxTSNE.h"
vector<vector<double> > ofxTSNE::run(vector<vector<float> > & data, int dims, double perplexity, double theta, bool normalize, bool runManually) {
this->data = data;
this->dims = dims;
this->perplexity = perplexity;
this->theta = theta;
this->normalize = normalize;
this->runManually = runManually;
max_iter = 1000;
iter = 0;
N = data.size();
D = data[0].size();
if (N - 1 < 3 * perplexity) {
ofLog(OF_LOG_WARNING, "Perplexity too large for number of data points, setting to max");
perplexity = (float) (N-1) / 3.0 - 1.0;
}
X = (double*) malloc(D * N * sizeof(double));
Y = (double*) malloc(dims * N * sizeof(double));
int idx = 0;
for (int i=0; i<N; i++) {
for (int j=0; j<D; j++) {
X[idx] = data[i][j];
idx++;
}
}
// t-SNE
tsne.run(X, N, D, Y, dims, perplexity, theta, runManually);
if (runManually) {
return tsnePoints;
}
return iterate();
}
vector<vector<double> > ofxTSNE::iterate(){
if (iter > max_iter) {
return tsnePoints;
}
if (runManually) {
tsne.runIteration();
}
// keep track of min for normalization
vector<double> min_, max_;
min_.resize(dims);
max_.resize(dims);
for (int i=0; i<dims; i++) {
min_[i] = numeric_limits<double>::max();
max_[i] = numeric_limits<double>::min();
}
// unpack Y into tsnePoints
tsnePoints.clear();
int idxY = 0;
for (int i=0; i<N; i++) {
vector<double> tsnePoint;
tsnePoint.resize(dims);
for (int j=0; j<dims; j++) {
tsnePoint[j] = Y[idxY];
if (normalize) {
if (tsnePoint[j] < min_[j]) min_[j] = tsnePoint[j];
if (tsnePoint[j] > max_[j]) max_[j] = tsnePoint[j];
}
idxY++;
}
tsnePoints.push_back(tsnePoint);
}
// normalize if requested
if (normalize) {
for (int i=0; i<tsnePoints.size(); i++) {
for (int j=0; j<dims; j++) {
tsnePoints[i][j] = (tsnePoints[i][j] - min_[j]) / (max_[j] - min_[j]);
}
}
}
iter++;
if (iter == max_iter) {
finish();
}
return tsnePoints;
}
void ofxTSNE::finish() {
delete(X);
delete(Y);
}