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
use rand;
use rand::distributions::IndependentSample;
use nalgebra::{Norm};
use vptree::{VPTree, MetricItem};
use std::cmp;
use std::collections::BTreeMap;
use num::Zero;
use model::{Vector};
use super::tsne_util::{Vec2f, cauchy_pdf_d2, find_p_for_perplexity, dist_sq};
use super::tsne_options::{TSNEOptions};
use super::quadtree::{QuadTree};
pub struct BHTSNE {
options: TSNEOptions,
pub sigmas: Vec<f32>
}
struct IndexedVec<'a> {
index: usize,
vec: &'a Vector<f32>
}
fn norm(v: &Vector<f32>) -> f32 {
let s2: f32 = v.iter().map(|x| *x * *x).sum();
s2.sqrt()
}
impl<'a> MetricItem<f32> for IndexedVec<'a> {
fn distance(&self, other: &Self) -> f32 {
norm(&(self.vec - other.vec))
}
}
type SparseBTMatrix = Vec<BTreeMap<usize, f32>>;
impl BHTSNE {
pub fn new(opt: Option<TSNEOptions>) -> Self {
BHTSNE {
options: opt.unwrap_or(TSNEOptions::default()),
sigmas: Vec::new()
}
}
fn cost_gradient(p_sym: &SparseBTMatrix, p_mult: f32,
y: &[Vec2f], y_qt: &QuadTree) -> (f32, Vec<Vec2f>) {
let freps: Vec<_> = y.iter().map(|x| y_qt.compute_frep_quantities(x, 0.5)).collect();
let z: f32 = freps.iter().map(|x| x.1).sum();
let cost_nomult = p_sym.iter().enumerate().map(|(i, row)| {
let yi = y[i];
row.iter().map(|(j, p_ij)| {
let d = yi - y[*j];
let q_ij = cauchy_pdf_d2(d.norm_squared()) / z;
p_ij * (p_ij / q_ij).ln()
}).sum::<f32>()
}).sum::<f32>();
let cost = p_mult * (cost_nomult + p_mult.ln());
let grad: Vec<_> = p_sym.iter().enumerate().map(|(i, row)| {
let p = y[i];
let f_attr = row.iter().map(|(j, v)| {
let d = p - y[*j];
let q_z = cauchy_pdf_d2(d.norm_squared());
(v * q_z) * d
}).fold(Vec2f::zero(), |acc, x| acc + x);
let frep: Vec2f = freps[i].0 / z;
4.0 * (f_attr * p_mult + frep)
}).collect();
(cost, grad)
}
fn initial_result(&self, n: usize, s: f32) -> Vec<Vec2f> {
let mut rng = rand::thread_rng();
let normal = rand::distributions::Normal::new(0.0, s as f64);
(0..n).map(|_| {
let x = normal.ind_sample(&mut rng) as f32;
let y = normal.ind_sample(&mut rng) as f32;
Vec2f::new(x, y)
}).collect()
}
fn sparse_input_jp_matrix(&mut self, inputs: &[Vector<f32>]) -> SparseBTMatrix {
let items: Vec<IndexedVec> = inputs.iter().enumerate().map(|(i, v)| IndexedVec{ index: i, vec: v }).collect();
let ni = inputs.len();
self.sigmas.clear();
let tree = VPTree::new(items).unwrap();
let nnn = cmp::min((self.options.perplexity * 3.0).floor() as usize, ni - 1);
let mut p_cond: SparseBTMatrix = Vec::with_capacity(ni);
for i in 0..ni {
let target = &inputs[i];
let mut nn = tree.nearest_neighbors(&IndexedVec{ index: i, vec: target }, nnn+1, true);
assert!(nn[0].index == i);
nn.remove(0);
let r2: Vec<f32> = nn.iter().map(|ref x| dist_sq(&target, &x.vec)).collect();
let v = find_p_for_perplexity(&r2, self.options.perplexity).unwrap();
self.sigmas.push(v.sigma);
let mut x = BTreeMap::new();
for (i, v) in nn.iter().zip(&v.probs) {
x.insert(i.index, *v);
}
p_cond.push(x);
}
let normalization: f32 = 0.5 / (ni as f32);
let mut p_sym: SparseBTMatrix = (0..ni).map(|_| BTreeMap::new()).collect();
for (i, row) in p_cond.into_iter().enumerate() {
for (j, val) in &row {
{
let v_ij = p_sym[i].entry(*j).or_insert(0.0);
*v_ij += val * normalization;
}
{
let v_ji = p_sym[*j].entry(i).or_insert(0.0);
*v_ji += val * normalization;
}
}
}
p_sym
}
pub fn reduction(&mut self, inputs: &[Vector<f32>]) -> Vec<Vec2f> {
let n = inputs.len();
let mut eta = self.options.learning_rate;
let p = self.sparse_input_jp_matrix(inputs);
let early_p_mult = match self.options.early_exaggeration {
Some(ref eeo) => eeo.mult,
None => 1.0
};
let mut result = self.initial_result(n, self.options.initial_spread);
let qt = QuadTree::new(&result).unwrap();
let r = Self::cost_gradient(&p, early_p_mult, &result, &qt);
let mut cost = r.0;
let mut grad = r.1;
let mut prev_result = result.clone();
let mut new_result = result.clone();
const MAX_BAD_ITERATIONS: usize = 100;
for iter in 0..self.options.num_iterations {
let use_p_mult = match self.options.early_exaggeration {
Some(ref eeo) =>
if iter < eeo.iterations { early_p_mult } else { 1.0 },
None => 1.0
};
let mut bad_iterations = 0;
while bad_iterations < MAX_BAD_ITERATIONS {
for i in 0..n {
let m = self.options.momentum.rate(iter);
let curr = result[i];
let prev = prev_result[i];
let g = grad[i];
new_result[i] = curr - g * eta - g * m * (curr - prev);
}
let new_qt = QuadTree::new(&new_result).unwrap();
let (new_cost, new_grad) = Self::cost_gradient(&p, use_p_mult, &new_result, &new_qt);
if new_cost < cost - (n as f32) * 1e-10 {
cost = new_cost;
grad = new_grad;
eta *= 1.05;
break
} else {
let new_eta = eta * 0.5;
eta = new_eta;
bad_iterations += 1;
}
}
if bad_iterations >= MAX_BAD_ITERATIONS {
break;
}
let temp = prev_result;
prev_result = result;
result = new_result;
new_result = temp;
}
result
}
}