Debian Codegraph @

dwtools/TableOfReal_and_Discriminant.cpp

raw symbols SCIP
1 /* TableOfReal_and_Discriminant.cpp
2 *
3 * Copyright (C) 1993-2020 David Weenink, 2020,2021,2026 Paul Boersma
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 3 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 #include "TableOfReal_and_Discriminant.h"
20
21 autoDiscriminant TableOfReal_to_Discriminant (TableOfReal me) {
22 try {
23 autoDiscriminant thee = Thing_new (Discriminant);
24 const integer dimension = my numberOfColumns;
25
26 Melder_require (NUMdefined (my data.get()),
27 U"There should be no undefined elements in the table.");
28 Melder_require (TableOfReal_hasRowLabels (me),
29 U"All rows should be labeled.");
30
31 autoTableOfReal mew = TableOfReal_sortOnlyByRowLabels (me);
32 if (! TableOfReal_hasColumnLabels (mew.get()))
33 TableOfReal_setSequentialColumnLabels (mew.get(), 0, 0, U"c", 1, 1);
34
35 thy groups = TableOfReal_to_SSCPList_byLabel (mew.get());
36 thy total = TableOfReal_to_SSCP (mew.get(), 0, 0, 0, 0);
37
38 if ((thy numberOfGroups = thy groups->size) < 2)
39 Melder_throw (U"Number of groups should be greater than one.");
40
41 TableOfReal_centreColumns_byRowLabel (mew.get());
42
43 // Overall centroid and apriori probabilities and costs.
44
45 autoVEC centroid = zero_VEC (dimension);
46 autoMAT between = zero_MAT (thy numberOfGroups, dimension);
47 thy aprioriProbabilities = raw_VEC (thy numberOfGroups);
48
49 longdouble sum = 0.0;
50 for (integer k = 1; k <= thy numberOfGroups; k ++) {
51 const SSCP m = thy groups->at [k];
52 const double scale = SSCP_getNumberOfObservations (m);
53 centroid.all() += scale * m -> centroid.all();
54 sum += scale;
55 }
56 centroid.all() /= double (sum);
57
58 for (integer k = 1; k <= thy numberOfGroups; k ++) {
59 const SSCP m = thy groups->at [k];
60 const double scale = SSCP_getNumberOfObservations (m);
61 thy aprioriProbabilities [k] = scale / my numberOfRows;
62 between.row (k) <<= m -> centroid.all() - centroid.all();
63 between.row (k) *= sqrt (scale);
64 }
65
66 // We need to solve B'B.x = lambda W'W.x, where B'B and W'W are the between and within covariance matrices.
67 // We do not calculate these covariance matrices directly from the data but instead use the GSVD to solve for
68 // the eigenvalues and eigenvectors of the equation.
69
70 thy eigen = Thing_new (Eigen);
71 Eigen_initFromSquareRootPair (thy eigen.get(), between.get(), mew -> data.get());
72
73 /*
74 Costs.
75 */
76 thy costs = raw_MAT (thy numberOfGroups, thy numberOfGroups);
77
78 thy costs.all() <<= 1.0;
79 thy costs.diagonal() <<= 0.0;
80
81 return thee;
82 } catch (MelderError) {
83 Melder_throw (me, U": Discriminant not created.");
84 }
85 }
86
87
88 autoTableOfReal Discriminant_TableOfReal_mahalanobis (Discriminant me, TableOfReal thee, integer group, bool poolCovarianceMatrices) {
89 try {
90 Melder_require (group > 0 && group <= my numberOfGroups,
91 U"Group should be in the range [1, ", my numberOfGroups, U"].");
92 autoSSCP pool = SSCPList_to_SSCP_pool (my groups.get());
93 autoCovariance covg = SSCP_to_Covariance (pool.get(), my numberOfGroups);
94 autoCovariance cov = SSCP_to_Covariance (my groups->at [group], 1);
95 autoTableOfReal him;
96 if (poolCovarianceMatrices) { // use group mean instead of overall mean!
97 covg -> centroid.all() <<= cov -> centroid.all();
98 him = Covariance_TableOfReal_mahalanobis (covg.get(), thee, false);
99 } else {
100 him = Covariance_TableOfReal_mahalanobis (cov.get(), thee, false);
101 }
102 return him;
103 } catch (MelderError) {
104 Melder_throw (U"TableOfReal not created.");
105 }
106 }
107
108 autoTableOfReal Discriminant_TableOfReal_mahalanobis_all (Discriminant me, TableOfReal thee, bool poolCovarianceMatrices) {
109 autoCovariance covg;
110 if (poolCovarianceMatrices) {
111 autoSSCP pool = SSCPList_to_SSCP_pool (my groups.get());
112 covg = SSCP_to_Covariance (pool.get(), my numberOfGroups);
113 }
114 autoTableOfReal him = TableOfReal_create (thy numberOfRows, 1);
115 his rowLabels.all() <<= thy rowLabels.all();
116 for (integer igroup = 1 ; igroup <= my numberOfGroups; igroup ++) {
117 conststring32 label = Thing_getName (my groups->at [igroup]);
118 autoCovariance cov = SSCP_to_Covariance (my groups->at [igroup], 1);
119 autoTableOfReal groupMahalanobis;
120 if (poolCovarianceMatrices) {
121 covg -> centroid.all() <<= cov -> centroid.all();
122 groupMahalanobis = Covariance_TableOfReal_mahalanobis (covg.get(), thee, false);
123 } else {
124 groupMahalanobis = Covariance_TableOfReal_mahalanobis (cov.get(), thee, false);
125 }
126 for (integer idata = 1; idata <= thy numberOfRows; idata ++)
127 if (Melder_equ (label, his rowLabels [idata].get()))
128 his data [idata] [1] = groupMahalanobis-> data [idata] [1];
129 }
130 return him;
131 }
132
133 autoClassificationTable Discriminant_TableOfReal_to_ClassificationTable (Discriminant me, TableOfReal thee, bool poolCovarianceMatrices, bool useAprioriProbabilities) {
134 try {
135 const integer numberOfGroups = Discriminant_getNumberOfGroups (me);
136 const integer dimension = Eigen_getDimensionOfComponents (my eigen.get());
137
138 Melder_require (dimension == thy numberOfColumns,
139 U"The number of columns should agree with the dimension of the discriminant.");
140
141 autoVEC log_p = raw_VEC (numberOfGroups);
142 autoVEC log_apriori = raw_VEC (numberOfGroups);
143 autoVEC ln_determinant = raw_VEC (numberOfGroups);
144 autoVEC buf = raw_VEC (dimension);
145
146 autovector <SSCP> sscpvec = newvectorzero <SSCP> (numberOfGroups);
147 autoSSCP pool = SSCPList_to_SSCP_pool (my groups.get());
148 autoClassificationTable him = ClassificationTable_create (thy numberOfRows, numberOfGroups);
149 his rowLabels.all() <<= thy rowLabels.all();
150
151 /*
152 Scale the sscp to become a covariance matrix.
153 */
154 pool -> data.get() *= 1.0 / (pool -> numberOfObservations - numberOfGroups);
155
156 double lnd;
157 autoSSCPList agroups;
158 SSCPList groups; // ppgb FIXME dit kan niet goed izjn
159 if (poolCovarianceMatrices) {
160 /*
161 Covariance matrix S can be decomposed as S = L.L'. Calculate L^-1.
162 L^-1 will be used later in the Mahalanobis distance calculation:
163 v'.S^-1.v == v'.L^-1'.L^-1.v == (L^-1.v)'.(L^-1.v).
164 */
165 if (Melder_debug == 52)
166 Melder_casual (U"***** before lower Cholesky inverse: \n", pool -> data.all());
167 MATlowerCholeskyInverse_inplace (pool -> data.get(), & lnd);
168 if (Melder_debug == 52)
169 Melder_casual (U"***** after lower Cholesky inverse: \n", pool -> data.all());
170 for (integer j = 1; j <= numberOfGroups; j ++) {
171 ln_determinant [j] = lnd;
172 sscpvec [j] = pool.get();
173 }
174 groups = my groups.get();
175 } else {
176 /*
177 Calculate the inverses of all group covariance matrices.
178 In case of a singular matrix, substitute inverse of pooled.
179 */
180 agroups = Data_copy (my groups.get());
181 groups = agroups.get();
182 integer npool = 0;
183 for (integer j = 1; j <= numberOfGroups; j ++) {
184 const SSCP t = groups->at [j];
185 const integer no = Melder_ifloor (SSCP_getNumberOfObservations (t));
186 t -> data.get() *= 1.0 / (no - 1);
187
188 sscpvec [j] = groups->at [j];
189 try {
190 MATlowerCholeskyInverse_inplace (t -> data.get(), & ln_determinant [j]);
191 } catch (MelderError) {
192 /*
193 Clear the error.
194 Try the alternative: the pooled covariance matrix.
195 */
196 Melder_clearError ();
197 if (npool == 0)
198 MATlowerCholeskyInverse_inplace (pool -> data.get(), & lnd);
199 npool ++;
200 sscpvec [j] = pool.get();
201 ln_determinant [j] = lnd;
202 }
203 }
204 if (npool > 0)
205 Melder_warning (npool, U" groups use pooled covariance matrix.");
206 }
207
208 /*
209 Labels for columns in ClassificationTable
210 */
211 for (integer j = 1; j <= numberOfGroups; j ++) {
212 conststring32 name = Thing_getName (my groups->at [j]);
213 if (! name)
214 name = U"?";
215 TableOfReal_setColumnLabel (him.get(), j, name);
216 }
217
218 /*
219 Normalize the sum of the apriori probabilities to 1.
220 Next take ln (p) because otherwise probabilities might be too small to represent.
221 */
222 if (Melder_debug == 52)
223 Melder_casual (U"***** before normalizing priors: \n", my aprioriProbabilities.all());
224 VECnormalize_inplace (my aprioriProbabilities.get(), 1.0, 1.0);
225 if (Melder_debug == 52)
226 Melder_casual (U"***** after normalizing priors: \n", my aprioriProbabilities.all());
227 const double logg = log (numberOfGroups);
228 for (integer j = 1; j <= numberOfGroups; j ++)
229 log_apriori [j] = ( useAprioriProbabilities ? log (my aprioriProbabilities [j]) : - logg );
230
231 /*
232 Generalized squared distance function:
233 D^2(x) = (x - mu)' S^-1 (x - mu) + ln (determinant(S)) - 2 ln (apriori)
234 */
235 for (integer i = 1; i <= thy numberOfRows; i ++) {
236 double norm = 0.0, pt_max = -1e308;
237 for (integer j = 1; j <= numberOfGroups; j ++) {
238 const SSCP t = groups->at [j];
239 const double md = NUMmahalanobisDistanceSquared (sscpvec [j] -> data.get(), thy data.row (i), t -> centroid.get());
240 if (Melder_debug == 52)
241 Melder_casual (U"***** Mahalanobis distance (squared): ", i, U" ", j, U" ", md);
242 const double pt = log_apriori [j] - 0.5 * (ln_determinant [j] + md);
243 if (pt > pt_max)
244 pt_max = pt;
245 log_p [j] = pt;
246 }
247 for (integer j = 1; j <= numberOfGroups; j ++)
248 norm += log_p [j] = exp (log_p [j] - pt_max);
249 for (integer j = 1; j <= numberOfGroups; j ++)
250 his data [i] [j] = log_p [j] / norm;
251 }
252 return him;
253 } catch (MelderError) {
254 Melder_throw (U"ClassificationTable from Discriminant & TableOfReal not created.");
255 }
256 }
257
258 autoClassificationTable Discriminant_TableOfReal_to_ClassificationTable_dw (Discriminant me, TableOfReal thee, bool poolCovarianceMatrices, bool useAprioriProbabilities, double alpha, double minProb, autoTableOfReal *displacements) {
259 try {
260 const integer g = Discriminant_getNumberOfGroups (me);
261 const integer p = Eigen_getDimensionOfComponents (my eigen.get());
262 const integer m = thy numberOfRows;
263
264 Melder_require (p == thy numberOfColumns,
265 U"The number of columns does not agree with the dimension of the discriminant.");
266
267 autoVEC log_p = raw_VEC (g);
268 autoVEC log_apriori = raw_VEC (g);
269 autoVEC ln_determinant = raw_VEC (g);
270 autoVEC buf = raw_VEC (p);
271 autoVEC displacement = raw_VEC (p);
272 autoVEC x = zero_VEC (p);
273 autovector <SSCP> sscpvec = newvectorzero <SSCP> (g);
274 autoSSCP pool = SSCPList_to_SSCP_pool (my groups.get());
275 autoClassificationTable him = ClassificationTable_create (m, g);
276 his rowLabels.all() <<= thy rowLabels.all();
277 autoTableOfReal adisplacements = Data_copy (thee);
278
279 /*
280 Scale the sscp to become a covariance matrix.
281 */
282
283 pool -> data.get() *= 1.0 / (pool -> numberOfObservations - g);
284
285 double lnd;
286 autoSSCPList agroups;
287 SSCPList groups;
288 if (poolCovarianceMatrices) {
289
290 /*
291 Covariance matrix S can be Cholesky decomposed as S = L.L'.
292 Calculate L^-1.
293 L^-1 will be used later in the Mahalanobis distance calculation:
294 v'.S^-1.v = v'.L^-1'.L^-1.v = (L^-1.v)'.(L^-1.v).
295 */
296
297 MATlowerCholeskyInverse_inplace (pool -> data.get(), & lnd);
298 for (integer j = 1; j <= g; j ++) {
299 ln_determinant [j] = lnd;
300 sscpvec [j] = pool.get();
301 }
302 groups = my groups.get();
303 } else {
304
305 /*
306 Calculate the inverses of all group covariance matrices.
307 In case of a singular matrix, substitute inverse of pooled.
308 */
309
310 agroups = Data_copy (my groups.get());
311 groups = agroups.get();
312 integer npool = 0;
313 for (integer j = 1; j <= g; j ++) {
314 const SSCP t = groups->at [j];
315 const integer no = Melder_ifloor (SSCP_getNumberOfObservations (t));
316 t -> data.get() *= 1.0 / (no - 1);
317
318 sscpvec [j] = groups->at [j];
319 try {
320 MATlowerCholeskyInverse_inplace (t -> data.get(), & ln_determinant [j]);
321 } catch (MelderError) {
322
323 /*
324 Clear the error.
325 Try the alternative: the pooled covariance matrix.
326 */
327
328 Melder_clearError ();
329 if (npool == 0)
330 MATlowerCholeskyInverse_inplace (pool -> data.get(), & lnd);
331 npool ++;
332 sscpvec [j] = pool.get();
333 ln_determinant [j] = lnd;
334 }
335 }
336 if (npool > 0)
337 Melder_warning (npool, U" groups use pooled covariance matrix.");
338 }
339
340 /*
341 Labels for columns in ClassificationTable
342 */
343
344 for (integer j = 1; j <= g; j ++) {
345 conststring32 name = Thing_getName (my groups->at [j]);
346 if (! name)
347 name = U"?";
348 TableOfReal_setColumnLabel (him.get(), j, name);
349 }
350
351 /*
352 Normalize the sum of the apriori probabilities to 1.
353 Next take ln (p) because otherwise probabilities might be too small to represent.
354 */
355
356 const double logg = log (g);
357 VECnormalize_inplace (my aprioriProbabilities.get(), 1.0, 1.0);
358 for (integer j = 1; j <= g; j ++) {
359 log_apriori [j] = ( useAprioriProbabilities ? log (my aprioriProbabilities [j]) : - logg );
360 }
361
362 /*
363 Generalized squared distance function:
364 D^2(x) = (x - mu)' S^-1 (x - mu) + ln (determinant(S)) - 2 ln (apriori)
365 */
366
367 for (integer i = 1; i <= m; i ++) {
368 SSCP winner;
369 double norm = 0, pt_max = -1e308;
370 integer iwinner = 1;
371 for (integer k = 1; k <= p; k ++)
372 x [k] = thy data [i] [k] + displacement [k];
373 for (integer j = 1; j <= g; j ++) {
374 const SSCP t = groups->at [j];
375 const double md = NUMmahalanobisDistanceSquared (sscpvec [j] -> data.get(), x.get(), t -> centroid.get());
376 const double pt = log_apriori [j] - 0.5 * (ln_determinant [j] + md);
377 if (pt > pt_max) {
378 pt_max = pt;
379 iwinner = j;
380 }
381 log_p [j] = pt;
382 }
383 for (integer j = 1; j <= g; j ++)
384 norm += log_p [j] = exp (log_p [j] - pt_max);
385
386 for (integer j = 1; j <= g; j ++)
387 his data [i] [j] = log_p [j] / norm;
388
389 /*
390 Save old displacement, calculate new displacement
391 */
392
393 winner = groups->at [iwinner];
394 for (integer k = 1; k <= p; k ++) {
395 adisplacements -> data [i] [k] = displacement [k];
396 if (his data [i] [iwinner] > minProb) {
397 double delta_k = winner -> centroid [k] - x [k];
398 displacement [k] += alpha * delta_k;
399 }
400 }
401 }
402 *displacements = adisplacements.move();
403 return him;
404 } catch (MelderError) {
405 Melder_throw (U"ClassificationTable for Weenink procedure not created.");
406 }
407 }
408
409
410 autoConfiguration Discriminant_TableOfReal_to_Configuration (Discriminant me, TableOfReal thee, integer numberOfDimensions) {
411 try {
412 Melder_require (thy numberOfColumns == my eigen -> dimension,
413 U"The number of columns in the TableOfReal (", thy numberOfColumns, U") should be equal to the dimension of the eigenvectors of the Discriminant (", my eigen -> dimension, U").");
414 if (numberOfDimensions == 0)
415 numberOfDimensions = Discriminant_getNumberOfFunctions (me);
416 Melder_require (numberOfDimensions <= my eigen -> numberOfEigenvalues,
417 U"The number of dimensions should not exceed the number of eigenvectors in the Discriminant (", my eigen -> numberOfEigenvalues, U").");
418 autoConfiguration him = Configuration_create (thy numberOfRows, numberOfDimensions);
419 mul_MAT_out (his data.get(), thy data.get(), my eigen -> eigenvectors.horizontalBand (1, numberOfDimensions).transpose ());
420 TableOfReal_copyLabels (thee, him.get(), 1, 0);
421 TableOfReal_setSequentialColumnLabels (him.get(), 0, 0, U"Eigenvector ", 1, 1);
422 return him;
423 } catch (MelderError) {
424 Melder_throw (U"Configuration not created.");
425 }
426 }
427
428 autoConfiguration TableOfReal_to_Configuration_lda (TableOfReal me, integer numberOfDimensions) {
429 try {
430 autoDiscriminant thee = TableOfReal_to_Discriminant (me);
431 autoConfiguration him = Discriminant_TableOfReal_to_Configuration (thee.get(), me, numberOfDimensions);
432 return him;
433 } catch (MelderError) {
434 Melder_throw (me, U": Configuration with lda data not created.");
435 }
436 }
437
438 /* End of file TableOfReal_and_Discriminant.cpp */