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
use linalg::{Matrix, MatrixSlice, Vector};
use rulinalg::utils;
use learning::UnSupModel;
use learning::toolkit::rand_utils;
#[derive(Clone, Copy, Debug)]
pub enum CovOption {
Full,
Regularized(f64),
Diagonal,
}
#[derive(Debug)]
pub struct GaussianMixtureModel {
comp_count: usize,
mix_weights: Vector<f64>,
model_means: Option<Matrix<f64>>,
model_covars: Option<Vec<Matrix<f64>>>,
log_lik: f64,
max_iters: usize,
pub cov_option: CovOption,
}
impl UnSupModel<Matrix<f64>, Matrix<f64>> for GaussianMixtureModel {
fn train(&mut self, inputs: &Matrix<f64>) {
let k = self.comp_count;
let mut cov_vec = Vec::with_capacity(k);
for _ in 0..k {
cov_vec.push(Matrix::identity(inputs.cols()));
}
self.model_covars = Some(cov_vec);
let random_rows: Vec<usize> =
rand_utils::reservoir_sample(&(0..inputs.rows()).collect::<Vec<usize>>(), k);
self.model_means = Some(inputs.select_rows(&random_rows));
for _ in 0..self.max_iters {
let log_lik_0 = self.log_lik;
let (weights, log_lik_1) = self.membership_weights(inputs);
if (log_lik_1 - log_lik_0).abs() < 1e-15 {
break;
}
self.log_lik = log_lik_1;
self.update_params(inputs, weights);
}
}
fn predict(&self, inputs: &Matrix<f64>) -> Matrix<f64> {
if let (&Some(_), &Some(_)) = (&self.model_means, &self.model_covars) {
self.membership_weights(inputs).0
} else {
panic!("Model has not been trained.");
}
}
}
impl GaussianMixtureModel {
pub fn new(k: usize) -> GaussianMixtureModel {
GaussianMixtureModel {
comp_count: k,
mix_weights: Vector::ones(k) / (k as f64),
model_means: None,
model_covars: None,
log_lik: 0f64,
max_iters: 100,
cov_option: CovOption::Full,
}
}
pub fn with_weights(k: usize, mixture_weights: Vector<f64>) -> GaussianMixtureModel {
assert!(mixture_weights.size() == k,
"Mixture weights must have length k.");
assert!(!mixture_weights.data().iter().any(|&x| x < 0f64),
"Mixture weights must have only non-negative entries.");
let sum = mixture_weights.sum();
let normalized_weights = mixture_weights / sum;
GaussianMixtureModel {
comp_count: k,
mix_weights: normalized_weights,
model_means: None,
model_covars: None,
log_lik: 0f64,
max_iters: 100,
cov_option: CovOption::Full,
}
}
pub fn means(&self) -> Option<&Matrix<f64>> {
self.model_means.as_ref()
}
pub fn covariances(&self) -> Option<&Vec<Matrix<f64>>> {
self.model_covars.as_ref()
}
pub fn mixture_weights(&self) -> &Vector<f64> {
&self.mix_weights
}
pub fn set_max_iters(&mut self, iters: usize) {
self.max_iters = iters;
}
fn membership_weights(&self, inputs: &Matrix<f64>) -> (Matrix<f64>, f64) {
let n = inputs.rows();
let mut member_weights_data = Vec::with_capacity(n * self.comp_count);
let mut cov_sqrt_dets = Vec::with_capacity(self.comp_count);
let mut cov_invs = Vec::with_capacity(self.comp_count);
if let Some(ref covars) = self.model_covars {
for cov in covars {
let covar_det = cov.det();
let covar_inv = cov.inverse().expect("Could not compute inverse of covariance.");
cov_sqrt_dets.push(covar_det.sqrt());
cov_invs.push(covar_inv);
}
}
let mut log_lik = 0f64;
if let Some(ref means) = self.model_means {
for i in 0..n {
let mut pdfs = Vec::with_capacity(self.comp_count);
let x_i = MatrixSlice::from_matrix(inputs, [i, 0], 1, inputs.cols());
for j in 0..self.comp_count {
let mu_j = MatrixSlice::from_matrix(means, [j, 0], 1, means.cols());
let diff = x_i - mu_j;
let pdf = (&diff * &cov_invs[j] * diff.transpose() * -0.5).into_vec()[0]
.exp() / cov_sqrt_dets[j];
pdfs.push(pdf);
}
let weighted_pdf_sum = utils::dot(&pdfs, self.mix_weights.data());
for (idx, pdf) in pdfs.iter().enumerate() {
member_weights_data.push(self.mix_weights[idx] * pdf / (weighted_pdf_sum));
}
log_lik += weighted_pdf_sum.ln();
}
}
(Matrix::new(n, self.comp_count, member_weights_data), log_lik)
}
fn update_params(&mut self, inputs: &Matrix<f64>, membership_weights: Matrix<f64>) {
let n = membership_weights.rows();
let d = inputs.cols();
let sum_weights = membership_weights.sum_rows();
self.mix_weights = &sum_weights / (n as f64);
let mut new_means = membership_weights.transpose() * inputs;
for (mean, w) in new_means.iter_rows_mut().zip(sum_weights.data().iter()) {
for m in mean.iter_mut() {
*m /= *w;
}
}
let mut new_covs = Vec::with_capacity(self.comp_count);
for k in 0..self.comp_count {
let mut cov_mat = Matrix::zeros(d, d);
let new_means_k = MatrixSlice::from_matrix(&new_means, [k, 0], 1, d);
for i in 0..n {
let inputs_i = MatrixSlice::from_matrix(inputs, [i, 0], 1, d);
let diff = inputs_i - new_means_k;
cov_mat += self.compute_cov(diff, membership_weights[[i, k]]);
}
new_covs.push(cov_mat / sum_weights[k]);
}
self.model_means = Some(new_means);
self.model_covars = Some(new_covs);
}
fn compute_cov(&self, diff: Matrix<f64>, weight: f64) -> Matrix<f64> {
match self.cov_option {
CovOption::Full => (diff.transpose() * diff) * weight,
CovOption::Regularized(eps) => (diff.transpose() * diff) * weight + eps,
CovOption::Diagonal => Matrix::from_diag(&diff.elemul(&diff).into_vec()) * weight,
}
}
}
#[cfg(test)]
mod tests {
use super::GaussianMixtureModel;
use linalg::Vector;
#[test]
fn test_means_none() {
let model = GaussianMixtureModel::new(5);
assert_eq!(model.means(), None);
}
#[test]
fn test_covars_none() {
let model = GaussianMixtureModel::new(5);
assert_eq!(model.covariances(), None);
}
#[test]
#[should_panic]
fn test_negative_mixtures() {
let mix_weights = Vector::new(vec![-0.25, 0.75, 0.5]);
let _ = GaussianMixtureModel::with_weights(3, mix_weights);
}
#[test]
#[should_panic]
fn test_wrong_length_mixtures() {
let mix_weights = Vector::new(vec![0.1, 0.25, 0.75, 0.5]);
let _ = GaussianMixtureModel::with_weights(3, mix_weights);
}
}