Debian Codegraph @

dwtools/GaussianMixture.cpp

raw
1 /* GaussianMixture.cpp
2 *
3 * Copyright (C) 2011-2023 David Weenink
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /*
20 djmw 20101021 Initial version
21 */
22 #include "Distributions_and_Strings.h"
23 #include "GaussianMixture.h"
24 #include "NUMmachar.h"
25 #include "NUM2.h"
26 #include "Strings_extensions.h"
27
28 #include "oo_DESTROY.h"
29 #include "GaussianMixture_def.h"
30 #include "oo_COPY.h"
31 #include "GaussianMixture_def.h"
32 #include "oo_EQUAL.h"
33 #include "GaussianMixture_def.h"
34 #include "oo_CAN_WRITE_AS_ENCODING.h"
35 #include "GaussianMixture_def.h"
36 #include "oo_WRITE_TEXT.h"
37 #include "GaussianMixture_def.h"
38 #include "oo_READ_TEXT.h"
39 #include "GaussianMixture_def.h"
40 #include "oo_WRITE_BINARY.h"
41 #include "GaussianMixture_def.h"
42 #include "oo_READ_BINARY.h"
43 #include "GaussianMixture_def.h"
44 #include "oo_DESCRIPTION.h"
45 #include "GaussianMixture_def.h"
46
47 #include "enums_getText.h"
48 #include "GaussianMixture_enums.h"
49 #include "enums_getValue.h"
50 #include "GaussianMixture_enums.h"
51
52 Thing_implement (GaussianMixture, Daata, 0);
53
54 void structGaussianMixture :: v1_info () {
55 structDaata :: v1_info ();
56 MelderInfo_writeLine (U"Number of components: ", our numberOfComponents);
57 MelderInfo_writeLine (U"Dimension of component: ", our dimension);
58 MelderInfo_writeLine (U"Mixing probabilities:");
59 for (integer im = 1; im <= numberOfComponents; im ++)
60 MelderInfo_writeLine (U" ", im, U": p = ", our mixingProbabilities [im], U" Name = \"", Thing_getName (our covariances->at [im]), U"\"");
61 }
62
63 static integer GaussianMixture_getNumberOfParametersInComponent (GaussianMixture me) {
64 Melder_assert (my covariances->size > 0);
65 const Covariance thee = my covariances->at [1];
66 return ( thy numberOfRows == 1 ? 2 * thy numberOfColumns : thy numberOfColumns * (thy numberOfColumns + 3) / 2 );
67 }
68
69 static double GaussianMixture_getLikelihoodValue (GaussianMixture me, constMAT const& probabilities, kGaussianMixtureCriterion criterion) {
70 Melder_require (probabilities.ncol == my numberOfComponents,
71 U"The number of columns in the probabilities should equal the number of components.");
72 const integer numberOfData = probabilities.nrow;
73 Melder_require (numberOfData > my numberOfComponents,
74 U"The number of rows in the probabilities should be larger than the number of components.");
75 if (criterion == kGaussianMixtureCriterion::COMPLETE_DATA_ML) {
76 /*
77 Bishop eq. 9.40 (we rewrote ln(a)+ln(b) = ln (a*b)):
78 ln(p(X,Z|μ,S,π)= sum(n=1...N, sum (k=1...K, gamma [n] [k])*ln (π [k]*N(x [n]|μ [k],S [k])),
79 where gamma [n] [k] = mixingProbablities [k] * probabilities [n] [k] /
80 sum(1...K, mixingProbablities [k] * probabilities [n] [k])
81 */
82 longdouble lnpcd = 0.0;
83 for (integer irow = 1; irow <= numberOfData; irow ++) {
84 longdouble psum = 0.0, lnsum = 0.0;
85 for (integer icol = 1; icol <= my numberOfComponents; icol ++) {
86 const longdouble pp = my mixingProbabilities [icol] * probabilities [irow] [icol];
87 psum += pp;
88 lnsum += pp * log (pp); // scaling outside the loop
89 }
90 if (psum > 0)
91 lnpcd += lnsum / psum; // scaling: as responsibilities
92 }
93 return lnpcd;
94 }
95 /*
96 The common factor for the following criteria is the log(likelihood), Bishop eq. 9.28
97 */
98 longdouble lnp = 0.0;
99 for (integer irow = 1; irow <= numberOfData; irow ++) {
100 const double psum = NUMinner (my mixingProbabilities.get(), probabilities.row (irow));
101 if (psum > 0.0)
102 lnp += (longdouble) log (psum);
103 }
104
105 if (criterion == kGaussianMixtureCriterion::LIKELIHOOD)
106 return lnp;
107
108 const double numberOfParametersPerComponent = GaussianMixture_getNumberOfParametersInComponent (me);
109 const double numberOfParametersTotal = numberOfParametersPerComponent * my numberOfComponents;
110 if (criterion == kGaussianMixtureCriterion::MESSAGE_LENGTH) {
111 /*
112 Equation (15) in
113 Figueiredo & Jain, Unsupervised Learning of Finite Mixture Models :
114 IEEE TRANSACTIONS ON PATTERN ANALYSIS AND MACHINE INTELLIGENCE, VOL. 24, NO. 3, MARCH 2002
115
116 L(theta,Y)= N/2*sum(m=1..k, log(n*alpha [m]/12)) +k/2*ln(n/12) +k(N+1)/2
117 - log (sum(i=1..n, sum(m=1..k, alpha [k]*p(k))))
118 */
119 longdouble logmpn = 0.0;
120 integer numberOfNonZeroComponents = 0;
121 for (integer ic = 1; ic <= my numberOfComponents; ic ++)
122 if (my mixingProbabilities [ic] > 0) {
123 logmpn += log (my mixingProbabilities [ic]);
124 numberOfNonZeroComponents ++;
125 }
126 /*
127 A rewritten L(theta,Y) is
128 */
129 return lnp - 0.5 * numberOfNonZeroComponents * (numberOfParametersPerComponent + 1) * (log (numberOfData / 12.0) + 1.0)
130 - 0.5 * numberOfParametersPerComponent * logmpn;
131 } else if (criterion == kGaussianMixtureCriterion::BAYES_INFORMATION)
132 return 2.0 * lnp - numberOfParametersTotal * log (numberOfData);
133 else if (criterion == kGaussianMixtureCriterion::AKAIKE_INFORMATION)
134 return 2.0 * (lnp - numberOfParametersTotal);
135 else if (criterion == kGaussianMixtureCriterion::AKAIKE_CORRECTED) {
136 return 2.0 * (lnp - numberOfParametersTotal * (numberOfData / (numberOfData - numberOfParametersTotal - 1.0)));
137 }
138 return lnp;
139 }
140
141 static void GaussianMixture_getResponsibilities (GaussianMixture me, constMATVU const& probabilities, integer componentToUpdate, MAT const& responsibilities) {
142 Melder_require (responsibilities.nrow == probabilities.nrow && responsibilities.ncol == probabilities.ncol,
143 U"The responsibilities and the probabilities should have the same dimensions.");
144 Melder_require (responsibilities.ncol == my numberOfComponents,
145 U"The number of columns of the responsibilities should equal the number of components.");
146 const integer fromComponent = componentToUpdate == 0 ? 1 : componentToUpdate;
147 const integer toComponent = componentToUpdate == 0 ? my numberOfComponents : componentToUpdate;
148
149 for (integer irow = 1; irow <= probabilities.nrow; irow ++) {
150 responsibilities.row (irow).part (fromComponent, toComponent) <<= probabilities.row (irow).part (fromComponent, toComponent) * my mixingProbabilities.part (fromComponent, toComponent);
151 }
152 /*
153 Maintain the invariant.
154 */
155 MATnormalizeRows_inplace (responsibilities, 1.0, 1.0);
156 }
157
158 static void GaussianMixture_updateComponent (GaussianMixture me, integer component, MATVU const& data, MATVU const& responsibilities) {
159 integer numberOfData = data.nrow;
160 Melder_require (my dimension == data.ncol,
161 U"The number of columns in the data and the dimension of the GaussianMixture should be equal.");
162 Melder_require (my numberOfComponents == responsibilities.ncol,
163 U"The number of components and the number of columns in the responsibilities should conform.");
164 Melder_require (responsibilities.nrow == data.nrow,
165 U"The number of rows in the data and the responsibilities should conform.");
166 Melder_require (component > 0 && component <= my numberOfComponents,
167 U"The component number should be in the range from 1 to ", my numberOfComponents, U".");
168
169 const Covariance thee = my covariances->at [component];
170 /*
171 Update the means: Bishop eq. 9.24
172 */
173 thy centroid.all() <<= 0.0;
174 for (integer irow = 1; irow <= numberOfData; irow ++)
175 thy centroid.get() += responsibilities [irow] [component] * data.row (irow);
176
177 const double totalComponentResponsibility = NUMsum (responsibilities.column (component));
178 thy centroid.get () /= totalComponentResponsibility;
179 /*
180 update covariance with the new mean: Bishop eq. 9.25
181 */
182 thy data.all() <<= 0.0;
183 autoVEC dif = raw_VEC (thy numberOfColumns);
184 if (thy numberOfRows == 1) { // 1xn covariance
185 autoVEC variance = raw_VEC (thy numberOfColumns);
186 for (integer irow = 1; irow <= numberOfData; irow ++) {
187 dif.all() <<= data.row (irow) - thy centroid.get();
188 variance.all() <<= dif.all() * dif.all();
189 thy data.row (1) += responsibilities [irow] [component] * variance.get();
190 }
191 } else { // nxn covariance
192 autoMAT covar = raw_MAT (thy numberOfColumns, thy numberOfColumns);
193 for (integer irow = 1; irow <= numberOfData; irow ++) {
194 dif.all() <<= data.row (irow) - thy centroid.get();
195 outer_MAT_out (covar.get(), dif.get(), dif.get());
196 thy data.get() += responsibilities [irow] [component] * covar.get();
197 }
198 }
199 thy data.get() /= totalComponentResponsibility;
200 thy numberOfObservations = my mixingProbabilities [component] * numberOfData;
201 }
202
203 static void GaussianMixture_setDefaultMixtureNames (GaussianMixture me) {
204 for (integer component = 1; component <= my numberOfComponents; component ++) {
205 Covariance cov = my covariances->at [component];
206 Thing_setName (cov, Melder_cat (U"c", component));
207 }
208 }
209
210 static void GaussianMixture_addCovarianceFraction (GaussianMixture me, integer component, Covariance him, double fraction) {
211 Melder_require (component > 0 && component <= my numberOfComponents,
212 U"The component number should be in the range from 1 to ", my numberOfComponents, U".");
213 const Covariance thee = my covariances->at [component];
214 Melder_require (thy numberOfColumns == his numberOfColumns,
215 U"The dimension of the Covariance should equal the dimension of the covariances in the GaussianMixture.");
216 /*
217 Prevent instability: add lambda fraction of global covariances
218 */
219 if (thy numberOfRows == 1)
220 if (his numberOfRows == 1)
221 thy data.row (1) += fraction * his data.row (1);
222 else
223 thy data.row (1) += fraction * his data.diagonal();
224 else
225 if (his numberOfRows == 1)
226 thy data.diagonal() += his data.row (1);
227 else
228 thy data.get() += his data.get() * fraction;
229 }
230
231 static void GaussianMixture_setColumnLabelsFromTableOfReal (GaussianMixture me, TableOfReal thee) {
232 for (integer component = 1; component <= my numberOfComponents; component ++) {
233 const Covariance cov = my covariances->at [component];
234 for (integer j = 1; j <= my dimension; j ++)
235 TableOfReal_setColumnLabel (cov, j, thy columnLabels [j].get());
236 }
237 }
238
239 // only from big to reduced or same
240 static void Covariance_into_Covariance (Covariance me, Covariance thee) {
241 Melder_require (my numberOfColumns == thy numberOfColumns,
242 U"Dimensions should be equal.");
243 SSCP_unExpand (thee); // to its original state
244 thy numberOfObservations = my numberOfObservations;
245 thy centroid.all() <<= my centroid.all();
246 thy columnLabels.all() <<= my columnLabels.all();
247
248 if (my numberOfRows == thy numberOfRows) {
249 thy rowLabels.all() <<= my rowLabels.all();
250 thy data.all() <<= my data.all();
251 } else {
252 for (integer ir = 1; ir <= my numberOfRows; ir ++)
253 for (integer ic = ir; ic <= my numberOfColumns; ic ++) {
254 const integer dij = ic - ir;
255 if (dij < thy numberOfRows)
256 thy data [dij + 1] [ic] = my data [ir] [ic];
257 }
258 }
259 }
260
261 conststring32 GaussianMixture_criterionText (kGaussianMixtureCriterion criterion) {
262 if (criterion == kGaussianMixtureCriterion::LIKELIHOOD)
263 return U"(1/n)*Likelihood";
264 else if (criterion == kGaussianMixtureCriterion::MESSAGE_LENGTH)
265 return U"(1/n)*Messagelength";
266 else if (criterion == kGaussianMixtureCriterion::BAYES_INFORMATION)
267 return U"(1/n)*BayesInformation";
268 else if (criterion == kGaussianMixtureCriterion::AKAIKE_INFORMATION)
269 return U"(1/n)*AkaikeInformation";
270 else if (criterion == kGaussianMixtureCriterion::AKAIKE_CORRECTED)
271 return U"(1/n)*AkaikeCorrected";
272 else if (criterion == kGaussianMixtureCriterion::COMPLETE_DATA_ML)
273 return U"(1/n)*CompleteDataML";
274 else
275 return U"???";
276 }
277
278 void GaussianMixture_removeUnsupportedComponents (GaussianMixture me) {
279 integer numberOfComponents = my numberOfComponents;
280 for (integer component = numberOfComponents; component > 0; component --) {
281 if (my mixingProbabilities [component] <= 0.0) {
282 my covariances -> removeItem (component);
283 my numberOfComponents --;
284 for (integer ic = component; ic <= my numberOfComponents; ic ++)
285 my mixingProbabilities [ic] = my mixingProbabilities [ic + 1];
286 }
287 }
288 my mixingProbabilities. resize (my numberOfComponents); // they stay normalized
289 }
290
291 autoGaussianMixture GaussianMixture_create (integer numberOfComponents, integer dimension, kGaussianMixtureStorage storage) {
292 try {
293 autoGaussianMixture me = Thing_new (GaussianMixture);
294 my numberOfComponents = numberOfComponents;
295 my dimension = dimension;
296 my mixingProbabilities = raw_VEC (numberOfComponents);
297 my mixingProbabilities.all() <<= 1.0 / numberOfComponents;
298 my covariances = CovarianceList_create ();
299 kSSCPstorage sscpStorage = storage == kGaussianMixtureStorage::DIAGONALS ? kSSCPstorage::DIAGONAL : kSSCPstorage::COMPLETE;
300 for (integer component = 1; component <= numberOfComponents; component ++) {
301 autoCovariance cov = Covariance_create_reduceStorage (dimension, sscpStorage);
302 my covariances -> addItemAtPosition_move (cov.move(), component);
303 }
304 GaussianMixture_setDefaultMixtureNames (me.get());
305 return me;
306 } catch (MelderError) {
307 Melder_throw (U"GaussianMixture not created.");
308 }
309 }
310
311 void GaussianMixture_generateOneVector_inline (GaussianMixture me, VEC const& c, autostring32 *out_covname, VEC const& buf) {
312 try {
313 const double p = NUMrandomUniform (0.0, 1.0);
314 const integer component = NUMgetIndexFromProbability (my mixingProbabilities.get(), p);
315 Covariance thee = my covariances->at [component];
316 if (thy numberOfRows == 1) { // 1xn reduced form
317 for (integer i = 1; i <= my dimension; i ++)
318 c [i] = NUMrandomGauss (thy centroid [i], sqrt (thy data [1] [i]));
319 } else { // nxn
320 if (! thy pca)
321 SSCP_expandWithPCA (thee); // on demand expanding
322 Covariance_PCA_generateOneVector_inline (thee, thy pca.get(), c, buf);
323 }
324 if (out_covname) {
325 autostring32 name = Melder_dup (thy name.get());
326 *out_covname = name.move();
327 }
328 } catch (MelderError) {
329 Melder_throw (me, U": vector not generated.");
330 }
331 }
332
333 autoGaussianMixture TableOfReal_to_GaussianMixture_fromRowLabels (TableOfReal me, kGaussianMixtureStorage storage) {
334 try {
335 autoStrings rowLabels = TableOfReal_extractRowLabels (me);
336 autoDistributions dist = Strings_to_Distributions (rowLabels.get());
337 const integer numberOfComponents = dist -> numberOfRows;
338
339 autoGaussianMixture thee = GaussianMixture_create (numberOfComponents, my numberOfColumns, storage);
340
341 GaussianMixture_setColumnLabelsFromTableOfReal (thee.get(), me);
342
343 for (integer component = 1; component <= numberOfComponents; component ++) {
344 autoTableOfReal tab = TableOfReal_extractRowsWhoseLabel (me, kMelder_string::EQUAL_TO, dist -> rowLabels [component].get());
345 autoCovariance cov = TableOfReal_to_Covariance (tab.get());
346 Covariance_into_Covariance (cov.get(), thy covariances->at [component]);
347 Thing_setName (thy covariances->at [component], dist -> rowLabels [component].get());
348 }
349 thy mixingProbabilities.all() <<= dist -> data.column (1).part (1, dist -> numberOfRows);
350 thy mixingProbabilities.all() /= my numberOfRows;
351 return thee;
352 } catch (MelderError) {
353 Melder_throw (me, U": no GaussianMixture created.");
354 }
355 }
356
357 autoCovariance GaussianMixture_to_Covariance_between (GaussianMixture me) {
358 return CovarianceList_to_Covariance_between (my covariances.get());
359 }
360 autoCovariance GaussianMixture_to_Covariance_within (GaussianMixture me) {
361 return CovarianceList_to_Covariance_within (my covariances.get());
362 }
363
364 autoCovariance GaussianMixture_to_Covariance_total (GaussianMixture me) {
365 try {
366 autoCovariance thee = GaussianMixture_to_Covariance_between (me);
367 autoCovariance within = GaussianMixture_to_Covariance_within (me);
368 thy data.all() += within -> data.all();
369 return thee;
370 } catch (MelderError) {
371 Melder_throw (me, U": no Covariance (total) created.");
372 }
373 }
374
375 autoCovariance GaussianMixture_extractComponent (GaussianMixture me, integer component) {
376 try {
377 Melder_require (component > 0 && component <= my numberOfComponents,
378 U"The component should be in the range from 1 to ", my numberOfComponents, U".");
379 autoCovariance thee = Data_copy (my covariances->at [component]);
380 return thee;
381 } catch (MelderError) {
382 Melder_throw (me, U": no component extracted.");
383 }
384 }
385
386 autoTableOfReal GaussianMixture_extractMixingProbabilities (GaussianMixture me) {
387 try {
388 autoTableOfReal thee = TableOfReal_create (my numberOfComponents, 2);
389 TableOfReal_setColumnLabel (thee.get(), 1, U"componentProbability");
390 TableOfReal_setColumnLabel (thee.get(), 2, U"numberOfObservations");
391 for (integer im = 1; im <= my numberOfComponents; im ++) {
392 const Covariance cov = my covariances->at [im];
393 thy data [im] [1] = my mixingProbabilities [im];
394 thy data [im] [2] = cov -> numberOfObservations;
395 TableOfReal_setRowLabel (thee.get(), im, Thing_getName (cov));
396 }
397 return thee;
398 } catch (MelderError) {
399 Melder_throw (me, U": no mixing probabilities extracted.");
400 }
401 }
402
403 autoTableOfReal GaussianMixture_extractCentroids (GaussianMixture me) {
404 try {
405 autoTableOfReal thee = TableOfReal_create (my numberOfComponents, my dimension);
406
407 for (integer component = 1; component <= my numberOfComponents; component ++) {
408 const Covariance cov = my covariances->at [component];
409 if (component == 1)
410 for (integer j = 1; j <= my dimension; j ++)
411 TableOfReal_setColumnLabel (thee.get(), j, cov -> columnLabels [j].get());
412 TableOfReal_setRowLabel (thee.get(), component, Thing_getName (cov));
413 thy data.row (component) <<= cov -> centroid.get();
414 }
415 return thee;
416 } catch (MelderError) {
417 Melder_throw (me, U": no centroid extracted.");
418 }
419 }
420
421 autoPCA GaussianMixture_to_PCA (GaussianMixture me) {
422 try {
423 autoCovariance him = GaussianMixture_to_Covariance_total (me);
424 autoPCA thee = SSCP_to_PCA (him.get());
425 return thee;
426 } catch (MelderError) {
427 Melder_throw (me, U": no PCA calculated.");
428 }
429 }
430
431 void GaussianMixture_getIntervalsAlongDirections (GaussianMixture me, integer d1, integer d2, double nsigmas, double *out_xmin, double *out_xmax, double *out_ymin, double *out_ymax) {
432 Melder_require (d1 > 0 && d1 <= my dimension && d2 > 0 && d2 <= my dimension,
433 U"The directions should be in the range from 1 to ", my dimension, U".");
434 autoSSCPList sscps = SSCPList_extractTwoDimensions (my covariances->asSSCPList(), d1, d2);
435 SSCPList_getEllipsesBoundingBoxCoordinates (sscps.get(), -nsigmas, 0, out_xmin, out_xmax, out_ymin, out_ymax);
436 }
437
438 void GaussianMixture_getIntervalAlongDirection (GaussianMixture me, integer d, double nsigmas, double *out_xmin, double *out_xmax) {
439 GaussianMixture_getIntervalsAlongDirections (me, d, d, nsigmas, out_xmin, out_xmax, nullptr, nullptr);
440 }
441
442 void GaussianMixture_PCA_getIntervalsAlongDirections (GaussianMixture me, PCA thee, integer d1, integer d2, double nsigmas, double *out_xmin, double *out_xmax, double *out_ymin, double *out_ymax) {
443 Melder_require (my dimension == thy dimension,
444 U"The dimensions should agree.");
445 Melder_require (d1 >= 1 && d1 <= my dimension && d2 >= 1 && d2 <= my dimension,
446 U"The dimensions should be in the range from 1 to ", my dimension, U".");
447
448 autoSSCPList sscps = SSCPList_toTwoDimensions (my covariances->asSSCPList(), thy eigenvectors.row (d1), thy eigenvectors.row (d2));
449 SSCPList_getEllipsesBoundingBoxCoordinates (sscps.get(), -nsigmas, 0, out_xmin, out_xmax, out_ymin, out_ymax);
450 }
451
452
453 void GaussianMixture_PCA_getIntervalAlongDirection (GaussianMixture me, PCA thee, integer d, double nsigmas, double *out_xmin, double *out_xmax) {
454 GaussianMixture_PCA_getIntervalsAlongDirections (me, thee, d, d, nsigmas, out_xmin, out_xmax, nullptr, nullptr);
455 }
456
457 void GaussianMixture_PCA_drawMarginalPdf (GaussianMixture me, PCA thee, Graphics g, integer d, double xmin, double xmax, double ymin, double ymax, integer npoints, integer nbins, bool garnish) {
458 Melder_require (my dimension == thy dimension,
459 U"The dimensions should agree.");
460 Melder_require (d >= 1 && d <= my dimension,
461 U"The dimension must be in the range from 1 to ", my dimension, U".");
462 if (npoints <= 1)
463 npoints = 1000;
464 constexpr double nsigmas = 2;
465 if (xmax <= xmin)
466 GaussianMixture_PCA_getIntervalAlongDirection (me, thee, d, nsigmas, & xmin, & xmax);
467 const double dx = (xmax - xmin) / npoints, x1 = xmin + 0.5 * dx;
468 const double scalef = ( nbins <= 0 ? 1.0 : 1.0 ); // TODO
469 autoVEC p = raw_VEC (npoints);
470 for (integer i = 1; i <= npoints; i ++) {
471 const double x = x1 + (i - 1) * dx;
472 Melder_assert (thy eigenvectors.ncol == thy dimension);
473 p [i] = scalef * GaussianMixture_getMarginalProbabilityAtPosition (me, thy eigenvectors.row (d), x);
474 }
475 const double pmax = NUMmax_u (p.get());
476 if (isundef (pmax))
477 return;
478 if (ymin >= ymax) {
479 ymin = 0.0;
480 ymax = pmax;
481 }
482 Graphics_setInner (g);
483 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
484 Graphics_function (g, p.asArgumentToFunctionThatExpectsOneBasedArray(), 1, npoints, x1, xmax - 0.5 * dx);
485 Graphics_unsetInner (g);
486 if (garnish) {
487 Graphics_drawInnerBox (g);
488 Graphics_markBottom (g, xmin, true, true, false, nullptr);
489 Graphics_markBottom (g, xmax, true, true, false, nullptr);
490 Graphics_markLeft (g, ymin, true, true, false, nullptr);
491 Graphics_markLeft (g, ymax, true, true, false, nullptr);
492 }
493 }
494
495 void GaussianMixture_drawMarginalPdf (GaussianMixture me, Graphics g, integer d, double xmin, double xmax, double ymin, double ymax, integer npoints, integer /* nbins */, bool garnish) {
496 Melder_require (d >= 1 && d <= my dimension,
497 U"The dimension should be in the range from 1 to ", my dimension, U".");
498
499 if (npoints <= 1)
500 npoints = 1000;
501
502 constexpr double nsigmas = 2.0;
503 if (xmax <= xmin)
504 GaussianMixture_getIntervalAlongDirection (me, d, nsigmas, & xmin, & xmax);
505
506 const double dx = (xmax - xmin) / (npoints - 1);
507 const double scalef = 1.0; // TODO
508 autoVEC p = raw_VEC (npoints);
509 autoVEC pos = raw_VEC (my dimension);
510
511 for (integer k = 1; k <= my dimension; k++)
512 pos [k] = ( k == d ? 1.0 : 0.0 );
513 for (integer i = 1; i <= npoints; i++) {
514 const double x = xmin + (i - 1) * dx;
515 p [i] = scalef * GaussianMixture_getMarginalProbabilityAtPosition (me, pos.get(), x);
516 }
517 const double pmax = NUMmax_u (p.get());
518 if (isundef (pmax))
519 return;
520 if (ymin >= ymax) {
521 ymin = 0;
522 ymax = pmax;
523 }
524
525 Graphics_setInner (g);
526 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
527 Graphics_function (g, p.asArgumentToFunctionThatExpectsOneBasedArray(), 1, npoints, xmin, xmax);
528 Graphics_unsetInner (g);
529
530 if (garnish) {
531 Graphics_drawInnerBox (g);
532 Graphics_markBottom (g, xmin, true, true, false, nullptr);
533 Graphics_markBottom (g, xmax, true, true, false, nullptr);
534 Graphics_markLeft (g, ymin, true, true, false, nullptr);
535 Graphics_markLeft (g, ymax, true, true, false, nullptr);
536 }
537 }
538
539 void GaussianMixture_PCA_drawConcentrationEllipses (GaussianMixture me, PCA him, Graphics g, double scale,
540 bool confidence, char32 *label, integer d1, integer d2, double xmin, double xmax, double ymin, double ymax, double fontSize, bool garnish) {
541 Melder_require (my dimension == his dimension,
542 U"The numbers of dimensions should agree.");
543 const integer dim1 = integer_abs (d1), dim2 = integer_abs (d2);
544 Melder_require (dim1 >= 1 && dim1 <= my dimension && dim2 >= 1 && dim2 <= my dimension,
545 U"The dimension numbers should be in the range from 1 to ", my dimension, U" (or the negative of this value for a reversed axis).");
546 autoVEC eigenvector1 = copy_VEC (his eigenvectors.row (dim1));
547 autoVEC eigenvector2 = copy_VEC (his eigenvectors.row (dim2));
548 if (d1 < 0)
549 eigenvector1.all() *= -1.0;
550 if (d2 < 0)
551 eigenvector2.all() *= -1.0;
552
553 autoSSCPList thee = SSCPList_toTwoDimensions (my covariances->asSSCPList(), eigenvector1.all(), eigenvector2.all());
554
555 SSCPList_drawConcentrationEllipses (thee.get(), g, -scale, confidence, label, 1, 2, xmin, xmax, ymin, ymax, fontSize, 0);
556
557 if (garnish) {
558 char32 llabel [40];
559 Graphics_drawInnerBox (g);
560 Graphics_marksLeft (g, 2, true, true, false);
561 Melder_sprint (llabel,40, U"pc ", d2);
562 Graphics_textLeft (g, true, llabel);
563 Graphics_marksBottom (g, 2, true, true, false);
564 Melder_sprint (llabel,40, U"pc ", d1);
565 Graphics_textBottom (g, true, llabel);
566 }
567 }
568
569 void GaussianMixture_drawConcentrationEllipses (GaussianMixture me, Graphics g, double scale, bool confidence, char32 *label,
570 bool pcaDirections, integer d1, integer d2, double xmin, double xmax, double ymin, double ymax, double fontSize, bool garnish) {
571 const integer dim1 = integer_abs (d1), dim2 = integer_abs (d2);
572 Melder_require (dim1 >= 1 && dim1 <= my dimension && dim2 >= 1 && dim2 <= my dimension,
573 U"The dimensions should be in the range from 1 to ", my dimension, U" (or the negative of this value for a reversed axis).");
574 if (! pcaDirections) {
575 SSCPList_drawConcentrationEllipses (my covariances->asSSCPList(), g, -scale, confidence, label,
576 dim1, dim2, xmin, xmax, ymin, ymax, fontSize, garnish);
577 return;
578 }
579
580 autoPCA him = GaussianMixture_to_PCA (me);
581
582 GaussianMixture_PCA_drawConcentrationEllipses (me, him.get(), g, scale, confidence, label, d1, d2,
583 xmin, xmax, ymin, ymax, fontSize, garnish);
584 }
585
586 void GaussianMixture_initialGuess (GaussianMixture me, TableOfReal thee) {
587 try {
588 autoCovariance cov_t = TableOfReal_to_Covariance (thee);
589 for (integer icol = 1; icol <= thy numberOfColumns; icol ++) {
590 const double min = NUMmin_e (thy data.column (icol));
591 const double max = NUMmax_e (thy data.column (icol));
592 for (integer component = 1; component <= my numberOfComponents; component ++) {
593 const Covariance covi = my covariances->at [component];
594 covi -> centroid [icol] = NUMrandomUniform (min, max);
595 }
596 }
597 const double varianceScaleFactor = 1.0 / (10 * thy numberOfColumns);
598 for (integer component = 1; component <= my numberOfComponents; component ++) {
599 const Covariance cov = my covariances->at [component];
600 if (cov -> numberOfRows == 1)
601 cov -> data.row (1) <<= varianceScaleFactor * cov_t -> data.diagonal();
602 else
603 cov -> data.diagonal() <<= varianceScaleFactor * cov_t -> data.diagonal();
604 }
605 } catch (MelderError) {
606 Melder_throw (me, U" & ", thee, U": no initial guess possible.");
607 }
608 }
609
610 void GaussianMixture_initialGuess2 (GaussianMixture me, TableOfReal thee, double nSigmas, double ru_range) {
611 try {
612 autoCovariance cov_t = TableOfReal_to_Covariance (thee);
613 /*
614 Assume equal probabilities for mixture
615 Assume equal covariance matrices
616 Spread centroids on an ellips in pc1-pc2 plane?
617 */
618 if (my dimension == 1) {
619 const double dm = 2.0 * sqrt (cov_t -> data [1] [1]) / my numberOfComponents;
620 double m1 = cov_t -> centroid [1] - dm;
621 for (integer im = 1; im <= my numberOfComponents; im ++) {
622 const Covariance covi = my covariances->at [im];
623 covi -> centroid [1] = m1;
624 covi -> data [1] [1] = dm * dm;
625 m1 += dm;
626 covi -> numberOfObservations = thy numberOfRows / my numberOfComponents;
627 }
628 } else {
629 autoPCA pca = SSCP_to_PCA (cov_t.get());
630 autoSSCP s2d = SSCP_toTwoDimensions (cov_t.get(), pca -> eigenvectors.row (1), pca -> eigenvectors.row (2));
631 autoMAT means2d = raw_MAT (my numberOfComponents, 2);
632
633 double a, b, cs, sn;
634 NUMeigencmp22 (s2d -> data [1] [1], s2d -> data [1] [2], s2d -> data [2] [2], & a, & b, & cs, & sn);
635
636 const double a_scaled = nSigmas * sqrt (a);
637 const double b_scaled = nSigmas * sqrt (b);
638 const double angle_inc = NUM2pi / my numberOfComponents;
639 double angle = 0.0;
640 for (integer im = 1; im <= my numberOfComponents; im++, angle += angle_inc) {
641 const double xc = a_scaled * (1.0 + NUMrandomUniform (-ru_range, ru_range)) * cos (angle);
642 const double yc = b_scaled * (1.0 + NUMrandomUniform (-ru_range, ru_range)) * sin (angle);
643 means2d [im] [1] = s2d -> centroid [1] + xc * cs - yc * sn;
644 means2d [im] [2] = s2d -> centroid [2] + xc * sn + yc * cs;
645 }
646 /*
647 Reconstruct the n-dimensional means from the 2-d pc's and the 2 eigenvectors
648 */
649 autoMAT means = mul_MAT (means2d.get(), pca -> eigenvectors.horizontalBand (1, 2));
650
651 for (integer im = 1; im <= my numberOfComponents; im ++) {
652 const Covariance covi = my covariances->at [im];
653 covi -> centroid.all() <<= means.row (im);
654 covi -> numberOfObservations = thy numberOfRows / my numberOfComponents;
655 }
656 /*
657 Trick: use the new means to get the between SSCP,
658 if there is only one component the cov_b will be zero!
659 */
660 autoCovariance cov_b = GaussianMixture_to_Covariance_between (me);
661 const double var_t = SSCP_getTotalVariance (cov_t.get());
662 const double var_b = SSCP_getTotalVariance (cov_b.get());
663 if (var_b >= var_t) { // we have chosen our initial values too far out
664 const double scale = 0.9 * sqrt (var_t / var_b);
665 for (integer im = 1; im <= my numberOfComponents; im ++) {
666 const Covariance covi = my covariances->at [im];
667 for (integer ic = 1; ic <= my dimension; ic ++)
668 covi -> centroid [ic] -= (1.0 - scale) * (covi -> centroid [ic] - cov_b -> centroid [ic]);
669 }
670 cov_b = GaussianMixture_to_Covariance_between (me);
671 }
672 /*
673 Within variances are now (total - between) / numberOfComponents;
674 */
675 if (my numberOfComponents > 1)
676 cov_t -> data.all() *= var_b / var_t / my numberOfComponents;
677 /*
678 Copy them
679 */
680 for (integer im = 1; im <= my numberOfComponents; im ++) {
681 const Covariance cov = my covariances->at [im];
682 if (cov -> numberOfRows == 1)
683 cov -> data.row (1) <<= cov_t -> data.diagonal();
684 else
685 cov -> data.all() <<= cov_t -> data.all();
686 }
687 }
688 } catch (MelderError) {
689 Melder_throw (me, U" & ", thee, U": no initial guess possible.");
690 }
691 }
692
693 autoClassificationTable GaussianMixture_TableOfReal_to_ClassificationTable (GaussianMixture me, TableOfReal thee) {
694 try {
695 autoClassificationTable him = ClassificationTable_create (thy numberOfRows, my numberOfComponents);
696 for (integer ic = 1; ic <= my numberOfComponents; ic ++) {
697 const Covariance cov = my covariances->at [ic];
698 SSCP_expandWithLowerCholeskyInverse (cov);
699 TableOfReal_setColumnLabel (him.get(), ic, Thing_getName (cov));
700 }
701
702 const double ln2pid = -0.5 * my dimension * log (NUM2pi);
703 autoVEC lnN = raw_VEC (my numberOfComponents);
704 for (integer irow = 1; irow <= thy numberOfRows; irow ++) {
705 longdouble psum = 0.0;
706 for (integer ic = 1; ic <= my numberOfComponents; ic ++) {
707 const Covariance cov = my covariances->at [ic];
708 const double dsq = NUMmahalanobisDistanceSquared (cov -> lowerCholeskyInverse.get(), thy data.row (irow), cov -> centroid.get());
709 lnN [ic] = ln2pid - 0.5 * (cov -> lnd + dsq);
710 psum += his data [irow] [ic] = my mixingProbabilities [ic] * exp (lnN [ic]);
711 }
712 if (psum == 0.0) { // p's might be too small (underflow), make the largest equal to sfmin
713 double lnmax = -1e308;
714 integer imm = 1;
715 for (integer ic = 1; ic <= my numberOfComponents; ic ++) {
716 if (lnN [ic] > lnmax)
717 lnmax = lnN [ic];
718 imm = ic;
719 }
720 his data [irow] [imm] = NUMfpp -> sfmin;
721 }
722
723 // for (integer im = 1; im <= my numberOfComponents; im++) { his data [i] [im] /= psum; }
724
725 TableOfReal_setRowLabel (him.get(), irow, thy rowLabels [irow].get());
726 }
727 return him;
728 } catch (MelderError) {
729 Melder_throw (U"No ClassificationTable created from GaussianMixture & TableOfReal.");
730 }
731 }
732
733 void GaussianMixture_splitComponent (GaussianMixture me, integer component) {
734 try {
735 Melder_require (component > 0 && component <= my numberOfComponents,
736 U"The component should be in [1, ", my numberOfComponents, U"].");
737
738 Covariance thee = my covariances->at [component];
739 // Always new PCA because we cannot be sure of data unchanged.
740 SSCP_expandWithPCA (thee);
741 autoCovariance cov1 = Data_copy (thee);
742 autoCovariance cov2 = Data_copy (thee);
743 SSCP_unExpandPCA (cov1.get());
744 SSCP_unExpandPCA (cov2.get());
745
746 // Eventually cov1 replaces component, cov2 at end
747
748 autoVEC mixingProbabilities = raw_VEC (my numberOfComponents + 1);
749 for (integer i = 1; i <= my numberOfComponents; i ++)
750 mixingProbabilities [i] = my mixingProbabilities [i];
751
752 const double gamma = 0.5, lambda = 0.5, eta = 0.5, mu = 0.5;
753 mixingProbabilities [component] = gamma * my mixingProbabilities [component];
754 mixingProbabilities [my numberOfComponents + 1] = (1.0 - gamma) * my mixingProbabilities [component];
755 const double mp12 = mixingProbabilities [component] / mixingProbabilities [my numberOfComponents + 1];
756 const double factor1 = (eta - eta * lambda * lambda - 1.0) / gamma + 1.0;
757 const double factor2 = (eta * lambda * lambda - eta - lambda * lambda) / (1.0 - gamma) + 1.0;
758 constVEC ev = thy pca -> eigenvectors.row (1);
759 const double d2 = thy pca -> eigenvalues [1];
760
761 for (integer i = 1; i <= my dimension; i ++) {
762 cov1 -> centroid [i] -= (1.0 / sqrt (mp12)) * sqrt (d2) * mu * ev [i];
763 cov2 -> centroid [i] += sqrt (mp12) * sqrt (d2) * mu * ev [i];
764
765 if (thy numberOfRows == 1) { // diagonal
766 cov1 -> data [1] [i] = cov1 -> data [1] [i] / mp12 + factor1 * d2;
767 cov1 -> data [1] [i] = cov2 -> data [i] [i] * mp12 + factor2 * d2;
768 } else {
769 for (integer j = i; j <= my dimension; j++) {
770 cov1 -> data [j] [i] = cov1 -> data [i] [j] = cov1 -> data [i] [j] / mp12 + factor1 * d2 * ev [i] * ev [j];
771 cov2 -> data [j] [i] = cov2 -> data [i] [j] = cov2 -> data [i] [j] * mp12 + factor2 * d2 * ev [i] * ev [j];
772 }
773 }
774 }
775 cov1 -> numberOfObservations *= gamma;
776 cov2 -> numberOfObservations *= 1.0 - gamma;
777
778 // Replace cov1 at component + add cov2. If something goes wrong we should be able to restore original!
779 try {
780 Thing_setName (cov2.get(), Melder_cat (Thing_getName (cov2.get()), U"-", my numberOfComponents + 1));
781 my covariances -> addItem_move (cov2.move());
782 } catch (MelderError) {
783 Melder_throw (me, U" cannot add new component.");
784 }
785
786 my covariances -> replaceItem_move (cov1.move(), component);
787
788 my numberOfComponents ++;
789 my mixingProbabilities = mixingProbabilities.move();
790 } catch (MelderError) {
791 Melder_throw (me, U": component ", component, U" cannot be split.");
792 }
793 }
794
795 void GaussianMixture_TableOfReal_getComponentProbabilities (GaussianMixture me, TableOfReal thee, integer componentToUpdate, MAT const& probabilities) {
796 try {
797 Melder_require (probabilities.nrow == thy numberOfRows,
798 U"The number of rows in the TableOfReal and the probabilities should be equal.");
799 Melder_require (probabilities.ncol == my numberOfComponents,
800 U"The number of columns in the TableOfReal and the probabilities should be equal.");
801 Melder_require (my dimension == thy numberOfColumns,
802 U"The number of columns in the TableOfReal and the dimension of the GaussianMixture should be equal.");
803 Melder_require (componentToUpdate >= 0 && componentToUpdate <= my numberOfComponents,
804 U"The component number should be in the interval from 0 to ", my numberOfComponents);
805 const double ln2pid = my dimension * log (NUM2pi);
806
807 const integer fromComponent = componentToUpdate == 0 ? 1 : componentToUpdate;
808 const integer toComponent = componentToUpdate == 0 ? my numberOfComponents : componentToUpdate;
809
810 for (integer component = fromComponent; component <= toComponent; component ++) {
811 const Covariance covi = my covariances->at [component];
812 SSCP_expandWithLowerCholeskyInverse (covi);
813
814 for (integer irow = 1; irow <= thy numberOfRows; irow++) {
815 const double dsq = NUMmahalanobisDistanceSquared (covi -> lowerCholeskyInverse.get(), thy data.row (irow), covi -> centroid.get());
816 probabilities [irow] [component] = std::max (1e-300, exp (- 0.5 * (ln2pid + covi -> lnd + dsq))); // prevent probabilities from being zero
817 }
818 }
819 } catch (MelderError) {
820 Melder_throw (me, U" & ", thee, U": no component probabilies could be calculated.");
821 }
822 }
823
824 void GaussianMixture_TableOfReal_getResponsilities (GaussianMixture me, TableOfReal thee, MAT const& responsibilities) {
825 Melder_require (responsibilities.nrow == thy numberOfRows,
826 U"The number of rows in the TableOfReal and the responsibilities should be equal.");
827 Melder_require (responsibilities.ncol == my numberOfComponents,
828 U"The number of columns in the TableOfReal and the responsibilities should be equal.");
829 Melder_require (my dimension == thy numberOfColumns,
830 U"The number of columns in the TableOfReal and the dimension of the GaussianMixture should be equal.");
831 autoMAT probabilities = raw_MAT (responsibilities.nrow, responsibilities.ncol);
832 GaussianMixture_TableOfReal_getComponentProbabilities (me, thee, 0, probabilities.get());
833 GaussianMixture_getResponsibilities (me, probabilities.get(), 0, responsibilities);
834 }
835
836 autoTableOfReal GaussianMixture_TableOfReal_to_TableOfReal_probabilities (GaussianMixture me, TableOfReal thee) {
837 try {
838 Melder_require (my dimension == thy numberOfColumns,
839 U"The number of columns in the TableOfReal and the dimension of the GaussianMixture should be equal.");
840 autoTableOfReal him = TableOfReal_create (thy numberOfRows, my numberOfComponents);
841 his rowLabels.all() <<= thy rowLabels.all();
842 TableOfReal_setSequentialColumnLabels (him.get(), 1, my numberOfComponents, U"c", 1, 1);
843 GaussianMixture_TableOfReal_getComponentProbabilities (me, thee, 0, his data.get());
844 return him;
845 } catch (MelderError) {
846 Melder_throw (me, U" & ", thee, U": no probabilies could be calculated.");
847 }
848 }
849
850 autoTableOfReal GaussianMixture_TableOfReal_to_TableOfReal_responsibilities (GaussianMixture me, TableOfReal thee) {
851 try {
852 autoTableOfReal him = GaussianMixture_TableOfReal_to_TableOfReal_probabilities (me, thee);
853 GaussianMixture_getResponsibilities (me, his data.get(), 0, his data.get());
854 return him;
855 } catch (MelderError) {
856 Melder_throw (me, U" & ", thee, U": no responsibilities could be calculated.");
857 }
858 }
859
860 void GaussianMixture_expandPCA (GaussianMixture me) {
861 for (integer im = 1; im <= my numberOfComponents; im ++) {
862 const Covariance him = my covariances->at [im];
863 Melder_require (his numberOfRows > 1,
864 U"Nothing to expand.");
865 his pca = SSCP_to_PCA (him);
866 }
867 }
868
869 void GaussianMixture_unExpandPCA (GaussianMixture me) {
870 for (integer im = 1; im <= my numberOfComponents; im ++) {
871 SSCP_unExpandPCA (my covariances->at [im]);
872 }
873 }
874
875 void GaussianMixture_TableOfReal_improveLikelihood (GaussianMixture me, TableOfReal thee, double delta_lnp, integer maxNumberOfIterations, double lambda, kGaussianMixtureCriterion criterion) {
876 try {
877 Melder_require (thy numberOfColumns == my dimension,
878 U"The number of columns and the dimension of the model should agree.");
879 Melder_require (my numberOfComponents < thy numberOfRows / 2,
880 U"Not enough data points.");
881
882 const conststring32 criterionText = GaussianMixture_criterionText (criterion);
883
884 // The global covariance matrix is added with scaling coefficient lambda during updating the
885 // mixture covariances to prevent numerical instabilities.
886
887 autoCovariance covg = TableOfReal_to_Covariance (thee);
888 autoMAT probabilities = raw_MAT (thy numberOfRows, my numberOfComponents);
889 autoMAT responsibilities = raw_MAT (thy numberOfRows, my numberOfComponents);
890
891 GaussianMixture_TableOfReal_getComponentProbabilities (me, thee, 0, probabilities.get());
892
893 double lnp = GaussianMixture_getLikelihoodValue (me, probabilities.get(), criterion);
894 integer iter = 0;
895 autoMelderProgress progress (U"Improve likelihood...");
896 try {
897 double lnp_prev, lnp_start = lnp / thy numberOfRows;
898 do {
899 iter ++;
900 /*
901 E-step: get responsibilities (gamma) with current parameters
902 See C. Bishop (2006), Pattern reconition and machine learning, Springer, page 439...
903 */
904 GaussianMixture_getResponsibilities (me, probabilities.get(), 0, responsibilities.get());
905
906 lnp_prev = lnp;
907
908 /*
909 M-step: 1. new means & covariances
910 */
911 for (integer component = 1; component <= my numberOfComponents; component ++) {
912 GaussianMixture_updateComponent (me, component, thy data.get(), responsibilities.get());
913 GaussianMixture_addCovarianceFraction (me, component, covg.get(), lambda);
914 }
915
916 /*
917 M-step: 2. new mixingProbabilities
918 */
919 autoVEC totalResponsibilities = columnSums_VEC (responsibilities.get());
920 my mixingProbabilities.all() <<= totalResponsibilities.get();
921 my mixingProbabilities.all() *= 1.0 / responsibilities.nrow;
922
923 GaussianMixture_TableOfReal_getComponentProbabilities (me, thee, 0, probabilities.get());
924
925 lnp = GaussianMixture_getLikelihoodValue (me, probabilities.get(), criterion);
926 Melder_progress ((double) iter / (double) maxNumberOfIterations, criterionText, U": ", lnp / thy numberOfRows, U", L0: ", lnp_start);
927 } while (fabs (lnp - lnp_prev) > std::max (fabs (delta_lnp * lnp_prev), NUMeps) && iter < maxNumberOfIterations);
928 } catch (MelderError) {
929 Melder_clearError ();
930 }
931
932 // During EM, covariances were underestimated by a factor of (n-1)/n. Correction now.
933
934 for (integer component = 1; component <= my numberOfComponents; component ++) {
935 const Covariance cov = my covariances->at [component];
936 if (cov -> numberOfObservations > 1.5)
937 cov -> data.row (1) *= cov -> numberOfObservations / (cov -> numberOfObservations - 1.0);
938 }
939 } catch (MelderError) {
940 Melder_throw (me, U" & ", thee, U": likelihood cannot be improved.");
941 }
942 }
943
944
945 double GaussianMixture_TableOfReal_getLikelihoodValue (GaussianMixture me, TableOfReal thee, kGaussianMixtureCriterion criterion) {
946 autoMAT probabilities = raw_MAT (thy numberOfRows, my numberOfComponents);
947 GaussianMixture_TableOfReal_getComponentProbabilities (me, thee, 0, probabilities.get());
948 return GaussianMixture_getLikelihoodValue (me, probabilities.get(), criterion);
949 }
950
951 autoMAT newMATremoveColumn (constMAT const& m, integer columnToRemove) {
952 Melder_require (m.ncol > 1,
953 U"We cannot remove the last column.");
954 Melder_require (columnToRemove > 0 && columnToRemove <= m.ncol,
955 U"The column number should be in the range from 1 to ",m.ncol, U".");
956 autoMAT resized = raw_MAT (m.nrow, m.ncol - 1);
957 resized.verticalBand (1, columnToRemove - 1) <<= m.verticalBand (1, columnToRemove - 1);
958 if (columnToRemove < m.ncol)
959 resized.verticalBand (columnToRemove, m.ncol - 1) <<= m.verticalBand (columnToRemove + 1, m.ncol);
960 return resized;
961 }
962
963 autoGaussianMixture TableOfReal_to_GaussianMixture_CEMM (TableOfReal me, integer minimumNumberOfComponents, integer maximumNumberOfComponents, kGaussianMixtureStorage storage, integer maximumNumberOfIterations, double tolerance, bool info) {
964 try {
965 autoGaussianMixture thee = GaussianMixture_create (maximumNumberOfComponents, my numberOfColumns, storage);
966 GaussianMixture_setColumnLabelsFromTableOfReal (thee.get(), me);
967 GaussianMixture_initialGuess (thee.get(), me);
968 if (maximumNumberOfIterations <= 0)
969 return thee;
970 return GaussianMixture_TableOfReal_to_GaussianMixture_CEMM (thee.get(), me, minimumNumberOfComponents, maximumNumberOfIterations, tolerance, info);
971 } catch (MelderError) {
972 Melder_throw (me, U"GaussianMixture not created from TableOfReal.");
973 }
974 }
975
976 autoGaussianMixture GaussianMixture_TableOfReal_to_GaussianMixture_CEMM (GaussianMixture me, TableOfReal thee, integer minimumNumberOfComponents, integer maxNumberOfIterations, double tolerance, bool info) {
977 try {
978 Melder_require (thy numberOfColumns == my dimension,
979 U"The number of columns in the TableOfReal and the dimension of the model should agree.");
980 Melder_require (my numberOfComponents < thy numberOfRows / 2,
981 U"Not enough data points.");
982 kGaussianMixtureCriterion criterion = kGaussianMixtureCriterion::MESSAGE_LENGTH;
983 const conststring32 criterionText = GaussianMixture_criterionText (criterion);
984 const bool deleteWeakComponents = minimumNumberOfComponents > 0;
985 autoGaussianMixture him = Data_copy (me);
986 autoMAT probabilities = zero_MAT (thy numberOfRows, his numberOfComponents);
987 autoMAT responsibilities = zero_MAT (thy numberOfRows, his numberOfComponents);
988
989 autoCovariance covg = TableOfReal_to_Covariance (thee);
990
991 const double npars = GaussianMixture_getNumberOfParametersInComponent (him.get());
992 const double nparsd2 = ( deleteWeakComponents ? npars / 2.0 : 0.0 );
993
994 // Initial E-step: Update all component probabilities.
995
996 GaussianMixture_TableOfReal_getComponentProbabilities (him.get(), thee, 0, probabilities.get());
997 GaussianMixture_getResponsibilities (me, probabilities.get(), 0, responsibilities.get());
998
999 double lnew = GaussianMixture_getLikelihoodValue (him.get(), probabilities.get(), criterion);
1000
1001 autoMelderProgress progress (U"Gaussian mixture...");
1002 autoGaussianMixture best = Data_copy (me);
1003
1004 double lstart = lnew / thy numberOfRows;
1005 integer iter = 0, numberOfNonzeroComponents = his numberOfComponents;
1006 double lmax = -1e308, lprev;
1007 if (info)
1008 MelderInfo_writeLine (U"iter = 0, ML = ", lstart, U" ", criterionText);
1009 while (numberOfNonzeroComponents >= minimumNumberOfComponents) {
1010 do {
1011 iter ++;
1012 lprev = lnew;
1013 for (integer icomponent = 1; icomponent <= his numberOfComponents; icomponent ++) {
1014
1015 GaussianMixture_getResponsibilities (him.get(), probabilities.get(), icomponent, responsibilities.get());
1016 // Now check if enough support for a component exists
1017
1018 const double componentSupport = NUMsum (responsibilities.column (icomponent)) - nparsd2;
1019 double totalSupport = 0.0;
1020 for (integer component = 1; component <= his numberOfComponents; component ++)
1021 totalSupport += std::max (0.0, NUMsum (responsibilities.column (component)) - nparsd2);
1022
1023 his mixingProbabilities [icomponent] = std::max (0.0, componentSupport / totalSupport);
1024
1025 VECnormalize_inplace (his mixingProbabilities.get(), 1.0, 1.0); // redistribute probability mass
1026
1027 if (his mixingProbabilities [icomponent] > 0.0) {
1028 // update probabilities for component
1029 GaussianMixture_updateComponent (him.get(), icomponent, thy data.get(), responsibilities.get());
1030 //if (lambda > 0)
1031 // GaussianMixture_addCovarianceFraction (him.get(), icomponent, covg.get(), lambda);
1032 GaussianMixture_TableOfReal_getComponentProbabilities (him.get(), thee, icomponent, probabilities.get());
1033 } else {
1034 /*
1035 "Remove" the component from GaussianMixture, the probabilities and responsibilities
1036 */
1037 if (numberOfNonzeroComponents > minimumNumberOfComponents) {
1038 numberOfNonzeroComponents --;
1039 probabilities.column (icomponent) <<= 0.0;
1040 responsibilities.column (icomponent) <<= 0.0;
1041 MATnormalizeRows_inplace (responsibilities.get(), 1.0, 1.0); // maintain invariant
1042 if (info)
1043 MelderInfo_writeLine (U"iter = ", iter, U", component ", icomponent, U" removed.");
1044 }
1045 }
1046 }
1047
1048 // L(theta,Y)=N/2 sum(m=1..k, log(n*mixingP [m]/12))+k/2log(n/12)+k/2(N+1)-loglikelihood reduces to:
1049 // k/2 (N+1){log(n/12)+1}+N/2sum(m=1..k,mixingP [m]) - loglikelihood
1050
1051 lnew = GaussianMixture_getLikelihoodValue (him.get(), probabilities.get(), criterion);
1052 if (info)
1053 MelderInfo_writeLine (U"iter = ", iter, U", ML = ", lnew);
1054 } while (lnew > lprev && fabs (lprev - lnew) > std::max (tolerance * fabs (lnew), NUMeps) && iter < maxNumberOfIterations);
1055 if (lnew > lmax) {
1056 best = Data_copy (him.get());
1057 lmax = lnew;
1058 if (! deleteWeakComponents) {
1059 break; // TODO was goto end; is dat hetzelfde?
1060 }
1061 }
1062 if (numberOfNonzeroComponents > minimumNumberOfComponents) { // remove smallest component
1063 integer componentToDelete = 1;
1064 double mpmin = 1.1; //
1065 for (integer component = 1; component <= his numberOfComponents; component ++) {
1066 if (his mixingProbabilities [component] > 0 && his mixingProbabilities [component] < mpmin) {
1067 mpmin = his mixingProbabilities [component];
1068 componentToDelete = component;
1069 }
1070 }
1071 his mixingProbabilities [componentToDelete] = 0.0;
1072 numberOfNonzeroComponents --;
1073 probabilities.column (componentToDelete) <<= 0.0;
1074 responsibilities.column (componentToDelete) <<= 0.0;
1075 MATnormalizeRows_inplace (responsibilities.get(), 1.0, 1.0); // maintain invariant
1076 if (info)
1077 MelderInfo_writeLine (U"iter = ", iter, U", component ", componentToDelete, U" removed (after).");
1078 } else {
1079 break;
1080 }
1081 }
1082 if (info)
1083 MelderInfo_drain();
1084 GaussianMixture_removeUnsupportedComponents (best.get());
1085 return best;
1086 } catch (MelderError) {
1087 Melder_throw (U"GaussianMixture not improved.");
1088 }
1089 }
1090
1091 // The numberOfElements per covariance needs to be updated later
1092 void GaussianMixture_removeComponent (GaussianMixture me, integer component) {
1093 if (my numberOfComponents == 1)
1094 return;
1095 Melder_require (component > 0 && component <= my numberOfComponents,
1096 U"The component number should be in the range from 1 to ", my numberOfComponents, U".");
1097
1098 my covariances -> removeItem (component);
1099 my numberOfComponents --;
1100
1101 for (integer ic = component; ic <= my numberOfComponents; ic ++)
1102 my mixingProbabilities [ic] = my mixingProbabilities [ic + 1];
1103
1104 my mixingProbabilities. resize (my numberOfComponents);
1105
1106 VECnormalize_inplace (my mixingProbabilities.get(), 1.0, 1.0);
1107 }
1108
1109 autoGaussianMixture TableOfReal_to_GaussianMixture (TableOfReal me, integer numberOfComponents, double delta_lnp, integer maxNumberOfIterations, double lambda, kGaussianMixtureStorage storage, kGaussianMixtureCriterion criterion) {
1110 try {
1111 Melder_require (my numberOfRows >= 2 * numberOfComponents,
1112 U"The number of rows should at least be twice the number of components.");
1113 autoGaussianMixture thee = GaussianMixture_create (numberOfComponents, my numberOfColumns, storage);
1114 GaussianMixture_setColumnLabelsFromTableOfReal (thee.get(), me);
1115 GaussianMixture_initialGuess (thee.get(), me);
1116 if (maxNumberOfIterations <= 0)
1117 return thee;
1118 GaussianMixture_TableOfReal_improveLikelihood (thee.get(), me, delta_lnp, maxNumberOfIterations, lambda, criterion);
1119 return thee;
1120 } catch (MelderError) {
1121 Melder_throw (me, U": no GaussianMixture created.");
1122 }
1123 }
1124
1125 autoCorrelation GaussianMixture_TableOfReal_to_Correlation (GaussianMixture me, TableOfReal thee) {
1126 try {
1127 Melder_require (my dimension == thy numberOfColumns,
1128 U"Dimensions should be equal.");
1129 autoClassificationTable ct = GaussianMixture_TableOfReal_to_ClassificationTable (me, thee);
1130 autoCorrelation him = ClassificationTable_to_Correlation_columns (ct.get());
1131 return him;
1132 } catch (MelderError) {
1133 Melder_throw (U"Correlation not created from GaussianMixture & TableOfReal.");
1134 }
1135 }
1136
1137 double GaussianMixture_getProbabilityAtPosition_string (GaussianMixture me, conststring32 vector_string) {
1138 autoSTRVEC vector = splitByWhitespace_STRVEC (vector_string);
1139 autoVEC pos = zero_VEC (my dimension);
1140 for (integer i = 1; i <= vector.size; i ++) {
1141 pos [i] = Melder_atof (vector [i].get());
1142 if (i == my dimension)
1143 break;
1144 }
1145 const double p = GaussianMixture_getProbabilityAtPosition (me, pos.get());
1146 return p;
1147 }
1148
1149 double GaussianMixture_getMarginalProbabilityAtPosition (GaussianMixture me, constVECVU const& pos, double x) {
1150 longdouble p = 0.0;
1151 for (integer im = 1; im <= my numberOfComponents; im ++) {
1152 const double pim = Covariance_getMarginalProbabilityAtPosition (my covariances->at [im], pos, x);
1153 p += my mixingProbabilities [im] * pim;
1154 }
1155 return (double) p;
1156 }
1157
1158 double GaussianMixture_getProbabilityAtPosition (GaussianMixture me, constVEC const& xpos) {
1159 longdouble p = 0.0;
1160 for (integer im = 1; im <= my numberOfComponents; im ++) {
1161 const double pim = Covariance_getProbabilityAtPosition (my covariances->at [im], xpos);
1162 p += my mixingProbabilities [im] * pim;
1163 }
1164 return (double) p;
1165 }
1166
1167 autoMatrix GaussianMixture_PCA_to_Matrix_density (GaussianMixture me, PCA thee, integer d1, integer d2, double xmin, double xmax, integer nx, double ymin, double ymax, integer ny) {
1168 try {
1169 Melder_require (my dimension == thy dimension,
1170 U"Dimensions should be equal.");
1171 Melder_require (d1 <= thy numberOfEigenvalues && d2 <= thy numberOfEigenvalues,
1172 U"Direction index too high.");
1173
1174 autoVEC v = zero_VEC (my dimension);
1175 if (xmax == xmin || ymax == ymin) {
1176 double xmind, xmaxd, ymind, ymaxd, nsigmas = 2.0;
1177
1178 GaussianMixture_PCA_getIntervalsAlongDirections (me, thee, d1, d2, nsigmas, &xmind, &xmaxd, &ymind, &ymaxd);
1179 if (xmax == xmin) {
1180 xmin = xmind;
1181 xmax = xmaxd;
1182 }
1183 if (ymax == ymin) {
1184 ymin = ymind;
1185 ymax = ymaxd;
1186 }
1187 }
1188
1189 // xmin,xmax and ymin,ymax are coordinates in the pc1 vs pc2 plane
1190
1191 const double dx = fabs (xmax - xmin) / nx, dy = fabs (ymax - ymin) / ny;
1192 const double x1 = xmin + 0.5 * dx, y1 = ymin + 0.5 * dy;
1193 autoMatrix him = Matrix_create (xmin, xmax, nx, dx, x1, ymin, ymax, ny, dy, y1);
1194
1195 for (integer i = 1; i <= ny; i ++) {
1196 const double y = y1 + (i - 1) * dy;
1197 for (integer j = 1; j <= nx; j ++) {
1198 const double x = x1 + (j - 1) * dx;
1199 for (integer k = 1; k <= my dimension; k ++)
1200 v [k] = x * thy eigenvectors [d1] [k] + y * thy eigenvectors [d2] [k];
1201 his z [i] [j] = GaussianMixture_getProbabilityAtPosition (me, v.get());
1202 }
1203 }
1204 return him;
1205 } catch (MelderError) {
1206 Melder_throw (me, U" & ", thee, U": no Matrix density created.");
1207 }
1208 }
1209
1210 autoTableOfReal GaussianMixture_to_TableOfReal_randomSampling (GaussianMixture me, integer numberOfPoints) {
1211 try {
1212 const Covariance cov = my covariances->at [1];
1213 autoTableOfReal thee = TableOfReal_create (numberOfPoints, my dimension);
1214 autoVEC buf = raw_VEC (my dimension);
1215 thy columnLabels.all() <<= cov -> columnLabels.part (1, my dimension);
1216 for (integer i = 1; i <= numberOfPoints; i ++) {
1217 autostring32 covname;
1218 GaussianMixture_generateOneVector_inline (me, thy data.row (i), & covname, buf.get());
1219 TableOfReal_setRowLabel (thee.get(), i, covname.get());
1220 }
1221 GaussianMixture_unExpandPCA (me);
1222 return thee;
1223 } catch (MelderError) {
1224 GaussianMixture_unExpandPCA (me);
1225 Melder_throw (U"TableOfReal with random sampling not created.");
1226 }
1227 }
1228
1229 autoTable GaussianMixture_TableOfReal_to_Table_BHEPNormalityTests (GaussianMixture me, TableOfReal thee, double h) {
1230 try {
1231 Melder_require (thy numberOfColumns == my dimension,
1232 U"Dimensions should agree.");
1233
1234 autoMAT responsibilities = raw_MAT (thy numberOfRows, my numberOfComponents);
1235 GaussianMixture_TableOfReal_getResponsilities (me, thee, responsibilities.get());
1236 autoVEC numberOfData = columnSums_VEC (responsibilities.get());
1237
1238 const conststring32 columnNames [] = { U"component", U"probability", U"smoothing", U"statistic",
1239 U"lnmu", U"lnvar", U"numberOfData", U"dimension", U"singular" };
1240 autoTable him = Table_createWithColumnNames (my numberOfComponents, ARRAY_TO_STRVEC (columnNames));
1241
1242 for (integer component = 1; component <= my numberOfComponents; component ++) {
1243 const Covariance cov = my covariances->at [component];
1244 Table_setStringValue (him.get(), component, 1, Thing_getName (cov));
1245 }
1246
1247 for (integer component = 1; component <= my numberOfComponents; component ++) {
1248 const Covariance cov = my covariances->at [component];
1249 autoVEC componentResponsibilities = copy_VEC (responsibilities.column (component));
1250 double testStatistic, lnmu, lnvar;
1251 bool isSingular;
1252 const double probability = Covariance_TableOfReal_normalityTest_BHEP (cov, thee,
1253 componentResponsibilities.get(), & h, & testStatistic, & lnmu, & lnvar, & isSingular);
1254
1255 Table_setNumericValue (him.get(), component, 2, probability);
1256 Table_setNumericValue (him.get(), component, 3, h);
1257 Table_setNumericValue (him.get(), component, 4, testStatistic);
1258 Table_setNumericValue (him.get(), component, 5, lnmu);
1259 Table_setNumericValue (him.get(), component, 6, lnvar);
1260 Table_setNumericValue (him.get(), component, 7, numberOfData [component]);
1261 Table_setNumericValue (him.get(), component, 8, my dimension);
1262 }
1263 return him;
1264 } catch (MelderError) {
1265 Melder_throw (U"Table for BHEP not created.");
1266 }
1267 }
1268
1269 /* End of file GaussianMixture.cpp 1555*/