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
use rand;
use rand::distributions::IndependentSample;
use nalgebra::{Norm};
use util::remove_diagonal;
use super::tsne_util::{Vec2f, cauchy_pdf_d2, find_p_for_perplexity, dist_sq};
use super::tsne_options::{TSNEOptions};
use model::{Vector, Matrix};
pub struct TSNE {
options: TSNEOptions,
}
pub fn input_joint_probability_matrix(inputs: &[Vector<f32>], perplexity: f32) -> Matrix<f32> {
let n = inputs.len();
let mut d2 = Matrix::zeros((n,n));
for i in 0..n {
let xi = &inputs[i];
for j in 0..i {
let d = dist_sq(xi, &inputs[j]);
assert!(d > 0.0);
d2[[i, j]] = d;
d2[[j, i]] = d;
}
}
let m = remove_diagonal(d2);
let n = m.rows();
let mut p: Vec<f32> = Vec::with_capacity(n*n);
for (i, r) in m.outer_iter().enumerate() {
let s: &[f32] = r.as_slice().unwrap();
let v = find_p_for_perplexity(s, perplexity).unwrap();
p.extend_from_slice(&v.probs[0..i]);
p.push(0.0);
p.extend_from_slice(&v.probs[i..]);
}
let f : f32 = 1.0 / (2.0 * (n as f32));
let pm = Matrix::from_shape_vec((n, n), p).ok().unwrap();
let mut p_sym = Matrix::zeros((n, n));
for i in 0..n {
for j in 0..i {
let x = (pm[(i, j)] + pm[[j, i]]) * f;
p_sym[[i, j]] = x;
p_sym[[j, i]] = x;
}
}
p_sym
}
pub fn output_q_matrix(v: &Vec<Vec2f>) -> Matrix<f32> {
let n = v.len();
let mut c = Matrix::zeros((n, n));
for i in 0..n {
for j in 0..i {
let d2 = (v[i] - v[j]).norm_squared();
let w = cauchy_pdf_d2(d2);
c[[i, j]] = w;
c[[j, i]] = w;
}
}
let z: f32 = c.iter().sum();
c / z
}
pub fn cost_function(p_sym: &Matrix<f32>, q: &Matrix<f32>) -> f32 {
let n = p_sym.rows();
assert_eq!(n, q.rows());
(0..n).map(|i| {
(0..n).map(|j| {
if i != j && p_sym[[i, j]] > 0.0 {
p_sym[[i, j]] * (p_sym[[i, j]] / q[[i, j]]).ln()
}
else {
0.0
}
}).sum::<f32>()
}).sum()
}
impl TSNE {
pub fn new(opt: Option<TSNEOptions>) -> Self {
TSNE {
options: opt.unwrap_or(TSNEOptions::default())
}
}
fn dcost(p_sym: &Matrix<f32>, q: &Matrix<f32>, y: &Vec<Vec2f>, i: usize) -> Vec2f {
let x = &y[i];
y.iter().enumerate().map(|(j, e)| {
let to_vec = *x - *e;
let d = cauchy_pdf_d2( to_vec.norm_squared() );
let pdiff = p_sym[[i, j]] - q[[i, j]];
to_vec * (pdiff * d)
}).fold(Vec2f::new(0.0, 0.0), |a, b| { a + b }) * 4.0
}
fn full_gradient(p_sym: &Matrix<f32>, q: &Matrix<f32>, y: &Vec<Vec2f>) -> Vec<Vec2f> {
let n = p_sym.rows();
(0..n).map(|i| Self::dcost(p_sym, q, y, i)).collect()
}
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()
}
pub fn reduction(&mut self, inputs: &[Vector<f32>]) -> Vec<Vec2f> {
let n = inputs.len();
let mut eta = self.options.learning_rate;
let p = input_joint_probability_matrix(inputs, self.options.perplexity);
let early_p = match self.options.early_exaggeration {
Some(ref eeo) => &p * eeo.mult,
None => p.clone()
};
let mut result = self.initial_result(n, self.options.initial_spread);
let mut q = output_q_matrix(&result);
let mut cost = cost_function(&early_p, &q);
let mut prev_result = result.clone();
let mut new_result = result.clone();
for iter in 0..self.options.num_iterations {
let use_p = match self.options.early_exaggeration {
Some(ref eeo) =>
if iter < eeo.iterations { &early_p } else { &p },
None => &p
};
let grad = Self::full_gradient(&use_p, &q, &result);
loop {
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_q = output_q_matrix(&new_result);
let new_cost = cost_function(&use_p, &new_q);
if new_cost < cost - (n as f32) * 1e-10 {
q = new_q;
cost = new_cost;
eta *= 1.05;
break
} else {
let new_eta = eta * 0.5;
eta = new_eta;
}
}
prev_result = result;
result = new_result.clone();
}
result
}
}