Debian Codegraph @

dwsys/NMF.cpp

raw
1 /* NMF.cpp
2 *
3 * Copyright (C) 2019 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 #include "Graphics.h"
20 #include "NMF.h"
21 #include "NUMmachar.h"
22 #include "NUM2.h"
23 #include "SVD.h"
24
25 #include "oo_DESTROY.h"
26 #include "NMF_def.h"
27 #include "oo_COPY.h"
28 #include "NMF_def.h"
29 #include "oo_EQUAL.h"
30 #include "NMF_def.h"
31 #include "oo_CAN_WRITE_AS_ENCODING.h"
32 #include "NMF_def.h"
33 #include "oo_WRITE_TEXT.h"
34 #include "NMF_def.h"
35 #include "oo_WRITE_BINARY.h"
36 #include "NMF_def.h"
37 #include "oo_READ_TEXT.h"
38 #include "NMF_def.h"
39 #include "oo_READ_BINARY.h"
40 #include "NMF_def.h"
41 #include "oo_DESCRIPTION.h"
42 #include "NMF_def.h"
43
44 #include "enums_getText.h"
45 #include "NMF_enums.h"
46 #include "enums_getValue.h"
47 #include "NMF_enums.h"
48
49 void structNMF :: v1_info () {
50 // skipping parent classes
51 MelderInfo_writeLine (U"Number of rows: ", numberOfRows);
52 MelderInfo_writeLine (U"Number of columns: ", numberOfColumns);
53 MelderInfo_writeLine (U"Number of features: ", numberOfFeatures);
54 }
55
56 Thing_implement (NMF, Daata, 0);
57
58
59 double MATgetDivergence_ItakuraSaito (constMATVU const& ref, constMATVU const& x) {
60 Melder_assert (ref.nrow == x.nrow);
61 Melder_assert (ref.ncol == x.ncol);
62 double divergence = 0.0;
63 for (integer irow = 1; irow <= ref.nrow; irow ++)
64 for (integer icol = 1; icol <= ref.ncol; icol ++) {
65 const double refval = ref [irow] [icol];
66 if (refval == 0.0)
67 return undefined;
68 divergence += x [irow] [icol] / refval - log (x [irow] [icol] / refval) - 1.0;
69 }
70 return divergence;
71 }
72
73 void NMF_paintFeatures (NMF me, Graphics g, integer fromFeature, integer toFeature, integer fromRow, integer toRow, double minimum, double maximum, int amplitudeScale, int scaling, bool garnish) {
74 fixUnspecifiedColumnRange (& fromFeature, & toFeature, my features.get());
75 fixUnspecifiedRowRange (& fromRow, & toRow, my features.get());
76
77 autoMAT part = copy_MAT (my features.part (fromRow, toRow, fromFeature, toFeature));
78
79 if (minimum == 0.0 && maximum == 0.0) {
80 minimum = NUMmin_u (part.get());
81 maximum = NUMmax_u (part.get());
82 }
83 if (isundef (minimum) || isundef (maximum))
84 return;
85
86 Graphics_setInner (g);
87 Graphics_setWindow (g, fromFeature, toFeature, fromRow, toRow);
88 Graphics_cellArray (g, my features.part (fromRow, toRow, fromFeature, toFeature),
89 fromFeature, toFeature, fromRow, toRow, minimum, maximum);
90 Graphics_unsetInner (g);
91 if (garnish)
92 Graphics_drawInnerBox (g);
93 }
94
95 void NMF_paintWeights (NMF me, Graphics g, integer fromWeight, integer toWeight, integer fromRow, integer toRow, double minimum, double maximum, int amplitudeScale, int scaling, bool garnish) {
96 fixUnspecifiedColumnRange (& fromWeight, & toWeight, my weights.get());
97 fixUnspecifiedRowRange (& fromRow, & toRow, my weights.get());
98
99 autoMAT part = copy_MAT (my weights.part (fromRow, toRow, fromWeight, toWeight));
100
101 if (minimum == 0.0 && maximum == 0.0) {
102 minimum = NUMmin_u (part.get());
103 maximum = NUMmax_u (part.get());
104 }
105 if (isundef (minimum) || isundef (maximum))
106 return;
107
108 Graphics_setInner (g);
109 Graphics_setWindow (g, fromWeight, toWeight, fromRow, toRow);
110
111
112 Graphics_cellArray (g, my weights.part (fromRow, toRow, fromWeight, toWeight),
113 fromWeight, toWeight, fromRow, toRow, minimum, maximum);
114 Graphics_unsetInner (g);
115 if (garnish)
116 Graphics_drawInnerBox (g);
117 }
118
119 autoNMF NMF_create (integer numberOfRows, integer numberOfColumns, integer numberOfFeatures) {
120 try {
121 autoNMF me = Thing_new (NMF);
122 my numberOfRows = numberOfRows;
123 my numberOfColumns = numberOfColumns;
124 my numberOfFeatures = numberOfFeatures;
125 my features = zero_MAT (numberOfRows, numberOfFeatures);
126 my weights = zero_MAT (numberOfFeatures, numberOfColumns);
127 return me;
128 } catch (MelderError) {
129 Melder_throw (U"NMF not created.");
130 }
131 }
132
133 static void MATmakeElementsNonNegative (MATVU const& m, int strategy) {
134 for (integer irow = 1; irow <= m.nrow; irow ++)
135 for (integer icol = 1; icol <= m.ncol; icol ++)
136 if (m [irow] [icol] < 0.0)
137 m [irow] [icol] = strategy == 0 ? 0.0 : fabs (m [irow] [icol]);
138 }
139
140 static void NMF_initializeFactorization_svd (NMF me, constMATVU const& data, kNMF_Initialization initializationMethod) {
141 try {
142 autoSVD thee = SVD_createFromGeneralMatrix (data);
143 MATmakeElementsNonNegative (thy u.get(), 1);
144 MATmakeElementsNonNegative (thy v.get(), 1);
145 my features.all() <<= thy u.verticalBand (1, my numberOfFeatures);
146 for (integer irow = 1; irow <= my numberOfFeatures; irow ++)
147 my weights.row (irow) <<= thy d [irow] * thy v.row (irow);
148
149 } catch (MelderError) {
150 Melder_throw (me, U": cpuld not initialize by svd method.");
151 }
152 }
153
154 void NMF_initializeFactorization (NMF me, constMATVU const& data, kNMF_Initialization initializationMethod) {
155 if (initializationMethod == kNMF_Initialization::RANDOM_UNIFORM) {
156 const double rmin = 0.0, rmax = 1.0;
157 randomUniform_MAT_out (my features.all(), rmin, rmax);
158 randomUniform_MAT_out (my weights.all(), rmin, rmax);
159 } else {
160 NMF_initializeFactorization_svd (me, data, initializationMethod);
161 }
162 }
163
164 autoNMF NMF_createFromGeneralMatrix (constMATVU const& m, integer numberOfFeatures) {
165 try {
166 Melder_require (NUMisNonNegative (m),
167 U"No matrix elements should be negative.");
168 Melder_require (numberOfFeatures <= m.ncol,
169 U"The number of features should not exceed the number of columns.");
170 autoNMF me = NMF_create (m.nrow, m.ncol, numberOfFeatures);
171 return me;
172 } catch (MelderError) {
173 Melder_throw (U"NMF cannot be created.");
174 }
175 }
176
177 double NMF_getEuclideanDistance (NMF me, constMATVU const& data) {
178 Melder_require (data.nrow == my numberOfRows && data.ncol == my numberOfColumns,
179 U"Dimensions should match.");
180 autoMAT synthesis = NMF_synthesize (me);
181 synthesis.get() -= data;
182 return NUMnorm (synthesis.get(), 2.0);
183 }
184
185 double NMF_getItakuraSaitoDivergence (NMF me, constMATVU const& data) {
186 Melder_require (data.nrow == my numberOfRows && data.ncol == my numberOfColumns,
187 U"Dimensions should match.");
188 autoMAT synthesis = NMF_synthesize (me);
189 return MATgetDivergence_ItakuraSaito (data, synthesis.get());
190 }
191
192 static double getMaximumChange (constMATVU const& m, MATVU const& m0, const double sqrteps) {
193 double min = NUMmin_e (m0);
194 double max = NUMmax_e (m0);
195 const double extremum1 = std::max (fabs (min), fabs (max));
196 m0 -= m;
197 min = NUMmin_e (m0);
198 max = NUMmax_e (m0);
199 const double extremum2 = std::max (fabs (min), fabs (max));
200 const double dmat = extremum2 / (sqrteps + extremum1);
201 return dmat;
202 }
203
204 /*
205 Calculating elementwise matrix multiplication, division and addition m = m0 .* (numerm ./(denom + eps))
206 Set elements < zero_threshold to zero
207 */
208
209 static const void update (MATVU const& m, constMATVU const& m0, constMATVU const& numer, constMATVU const& denom, double zeroThreshold, double maximum) {
210 Melder_assert (m.nrow == m0.nrow && m.ncol == m0.ncol);
211 Melder_assert (m.nrow == numer.nrow && m.ncol == numer.ncol);
212 Melder_assert (m.nrow == denom.nrow && m.ncol == denom.ncol);
213 /*
214 The value 1e-9 is OK for matrices with values that are larger than 1.
215 For matrices with very small values we have to scale the divByZeroAvoidance value
216 otherwise the precision would suffer.
217 A scaling with the maximum value seems reasonable.
218 */
219 const double divByZeroAvoidance = 1e-09 * ( maximum < 1.0 ? maximum : 1.0 );
220 for (integer irow = 1; irow <= m.nrow; irow ++)
221 for (integer icol = 1; icol <= m.ncol; icol++) {
222 if (m0 [irow] [icol] == 0.0 || numer [irow] [icol] == 0.0) {
223 m [irow] [icol] = 0.0;
224 } else {
225 double update = m0 [irow] [icol] * (numer [irow] [icol] / (denom [irow] [icol] + divByZeroAvoidance));
226 m [irow] [icol] = ( update < zeroThreshold ? 0.0 : update );
227 }
228 }
229 }
230
231 /*
232 Algorithm for Non-negative Matrix Factorization by multiplicative updates.
233 The algoritm is inspired by the nmf_mu.c algorithm in libNMF by
234 A. Janecek, S. Schulze Grotthoff & W.N. Gangsterer (2011):
235 "LIBNMF - A library for nonnegative matrix factorization."
236 Computing and informatics% #30: 205--224.
237
238 */
239 void NMF_improveFactorization_mu (NMF me, constMATVU const& data, integer maximumNumberOfIterations, double changeTolerance, double approximationTolerance, bool info) {
240 try {
241 Melder_require (my numberOfColumns == data.ncol,
242 U"The number of columns should be equal.");
243 Melder_require (my numberOfRows == data.nrow,
244 U"The number of rows should be equal.");
245
246 autoMAT productFtD = zero_MAT (my numberOfFeatures, my numberOfColumns); // calculations of F'D
247 autoMAT productFtFW = zero_MAT (my numberOfFeatures, my numberOfColumns); // calculations of F'F W
248 autoMAT weights0 = zero_MAT (my numberOfFeatures, my numberOfColumns);
249
250 autoMAT productDWt = zero_MAT (my numberOfRows, my numberOfFeatures); // calculations of DW'
251 autoMAT productFWWt = zero_MAT (my numberOfRows, my numberOfFeatures); // calculations of FWW'
252 autoMAT features0 = zero_MAT (my numberOfRows, my numberOfFeatures);
253
254 autoMAT productWWt = zero_MAT (my numberOfFeatures, my numberOfFeatures); // calculations of WW'
255 autoMAT productFtF = zero_MAT (my numberOfFeatures, my numberOfFeatures); // calculations of F'F
256
257 const double traceDtD = NUMtrace2 (data.transpose(), data); // for distance calculation
258 features0.all() <<= my features.all();
259 weights0.all() <<= my weights.all();
260
261 if (! NUMfpp)
262 NUMmachar ();
263
264 const double eps = NUMfpp -> eps;
265 const double sqrteps = sqrt (eps);
266 const double maximum = NUMmax_e (data);
267 double dnorm0 = 0.0;
268 integer iter = 1;
269 bool convergence = false;
270
271 while (iter <= maximumNumberOfIterations && not convergence) {
272 /*
273 while iter < maxinter and not convergence
274 (1) W = W .* (F'*D) ./ (F'*F*W + 10^^−9^)
275 (2) F = F .* (D*W') ./ (F*W*W' + 10^^−9^)
276 (3) test for convergence
277 endwhile
278 */
279
280 // 1. Update W matrix
281 features0.all() <<= my features.all();
282 weights0.all() <<= my weights.all();
283 mul_MAT_out (productFtD.get(), features0.transpose(), data);
284 mul_MAT_out (productFtF.get(), features0.transpose(), features0.get());
285 mul_MAT_out (productFtFW.get(), productFtF.get(), weights0.get());
286 update (my weights.get(), weights0.get(), productFtD.get(), productFtFW.get(), eps, maximum);
287
288 // 2. Update F matrix
289 mul_MAT_out (productDWt.get(), data, my weights.transpose()); // productDWt = data*weights'
290 mul_MAT_out (productWWt.get(), my weights.get(), my weights.transpose()); // work1 = weights*weights'
291 mul_MAT_out (productFWWt.get(), features0.get(), productWWt.get()); // productFWWt = features0 * work1
292 update (my features.get(), features0.get(), productDWt.get(), productFWWt.get(), eps, maximum);
293
294 /* 3. Convergence test:
295 The Frobenius norm ||D-FW|| of a matrix can be written as
296 ||D-FW||=trace(D'D) − 2trace(W'F'D) + trace(W'F'FW)
297 =trace(D'D) - 2trace(W'(F'D))+trace((F'F)(WW'))
298 This saves us from explicitly calculating the reconstruction FW because we already have performed most of
299 the needed matrix multiplications in the update step.
300 */
301
302 const double traceWtFtD = NUMtrace2 (my weights.transpose(), productFtD.get());
303 const double traceWtFtFW = NUMtrace2 (productFtF.get(), productWWt.get());
304 const double distance = sqrt (std::max (traceDtD - 2.0 * traceWtFtD + traceWtFtFW, 0.0)); // just in case
305 const double dnorm = distance / (my numberOfRows * my numberOfColumns);
306 const double df = getMaximumChange (my features.get(), features0.get(), sqrteps);
307 const double dw = getMaximumChange (my weights.get(), weights0.get(), sqrteps);
308 const double delta = std::max (df, dw);
309 convergence = ( iter > 1 && (delta < changeTolerance || dnorm < dnorm0 * approximationTolerance) );
310 if (info)
311 MelderInfo_writeLine (U"Iteration: ", iter, U", dnorm: ", dnorm, U", delta: ", delta);
312
313 dnorm0 = dnorm;
314 ++ iter;
315 }
316 if (info)
317 MelderInfo_drain();
318 } catch (MelderError) {
319 Melder_throw (me, U" factorization cannot be improved.");
320 }
321 }
322
323 void NMF_improveFactorization_als (NMF me, constMATVU const& data, integer maximumNumberOfIterations, double changeTolerance, double approximationTolerance, bool info) {
324 try {
325 Melder_require (my numberOfColumns == data.ncol, U"The number of columns should be equal.");
326 Melder_require (my numberOfRows == data.nrow, U"The number of rows should be equal.");
327
328 autoMAT productFtD = zero_MAT (my numberOfFeatures, my numberOfColumns); // calculations of F'D
329 autoMAT productWDt = zero_MAT (my numberOfFeatures, my numberOfRows); // calculations of WD'
330
331 autoMAT weights0 = zero_MAT (my numberOfFeatures, my numberOfColumns);
332 autoMAT features0 = zero_MAT (my numberOfRows, my numberOfFeatures);
333
334 autoMAT productFtF = zero_MAT (my numberOfFeatures, my numberOfFeatures); // calculations of F'F
335 autoMAT productWWt = zero_MAT (my numberOfFeatures, my numberOfFeatures); // calculations of WW'
336
337 autoSVD svd_WWt = SVD_create (my numberOfFeatures, my numberOfFeatures); // solving W*W'*F' = W*D'
338 autoSVD svd_FtF = SVD_create (my numberOfFeatures, my numberOfFeatures); // solving F´*F*W = F'*D
339
340 const double traceDtD = NUMtrace2 (data.transpose(), data); // for distance calculation
341
342 if (! NUMfpp)
343 NUMmachar ();
344 const double eps = NUMfpp -> eps;
345 const double sqrteps = sqrt (eps);
346 double dnorm0 = 0.0;
347 integer iter = 1;
348 bool convergence = false;
349
350 while (iter <= maximumNumberOfIterations && not convergence) {
351 /*
352 for iter to maxiter
353 (1) W is solution of F´*F*W = F'*D.
354 Set all negative elements in W to 0.
355 (2) F is solution of W*W'*F' = W*D' .
356 Set all negative elements in F to 0.
357 (3) test for convergence
358 endfor
359 */
360
361 /*
362 1. Solve equations for new W: F´*F*W = F'*D
363 */
364 weights0.all() <<= my weights.all(); // save previous weights for convergence test
365 mul_MAT_out (productFtD.get(), my features.transpose(), data);
366 mul_MAT_out (productFtF.get(), my features.transpose(), my features.get());
367
368 svd_FtF -> u.all() <<= productFtF.all();
369 SVD_compute (svd_FtF.get());
370 SVD_solve_preallocated (svd_FtF.get(), productFtD.get(), my weights.get());
371 MATmakeElementsNonNegative (my weights.get(), 0);
372
373 /*
374 2. Solve equations for new F: W*W'*F' = W*D'
375 */
376 features0.all() <<= my features.all(); // save previous features for convergence test
377 mul_MAT_out (productWDt.get(), my weights.get(), data.transpose());
378 mul_MAT_out (productWWt.get(), my weights.get(), my weights.transpose());
379
380 svd_WWt -> u.all() <<= productWWt.all();
381 SVD_compute (svd_WWt.get());
382 SVD_solve_preallocated (svd_WWt.get(), productWDt.get(), my features.transpose());
383
384 /*
385 3. Convergence test.
386 */
387 const double traceWtFtD = NUMtrace2 (my weights.transpose(), productFtD.get());
388 const double traceWtFtFW = NUMtrace2 (productFtF.get(), productWWt.get());
389 const double distance = sqrt (std::max (traceDtD - 2.0 * traceWtFtD + traceWtFtFW, 0.0)); // just in case
390 const double dnorm = distance / (my numberOfRows * my numberOfColumns);
391 const double df = getMaximumChange (my features.get(), features0.get(), sqrteps);
392 const double dw = getMaximumChange (my weights.get(), weights0.get(), sqrteps);
393 const double delta = std::max (df, dw);
394
395 convergence = ( iter > 1 && (delta < changeTolerance || dnorm < dnorm0 * approximationTolerance) );
396 if (info)
397 MelderInfo_writeLine (U"Iteration: ", iter, U", dnorm: ", dnorm, U", delta: ", delta);
398 dnorm0 = dnorm;
399 ++ iter;
400 }
401 if (info)
402 MelderInfo_drain();
403 } catch (MelderError) {
404 Melder_throw (me, U" ALS factorization cannot be improved.");
405 }
406 }
407
408 static void VECinvertAndScale (VECVU const& target, constVECVU const& source, double scaleFactor) {
409 Melder_assert (target.size == source.size);
410 for (integer i = 1; i <= target.size; i ++)
411 target [i] = scaleFactor / source [i];
412 }
413
414 void NMF_improveFactorization_is (NMF me, constMATVU const& data, integer maximumNumberOfIterations, double changeTolerance, double approximationTolerance, bool info) {
415 try {
416 Melder_require (my numberOfColumns == data.ncol, U"The number of columns should be equal.");
417 Melder_require (my numberOfRows == data.nrow, U"The number of rows should be equal.");
418 Melder_require (NUMhasZeroElement (data) == false,
419 U"The data matrix should not have cells that are zero.");
420 autoMAT vk = raw_MAT (data.nrow, data.ncol);
421 autoMAT fw = raw_MAT (data.nrow, data.ncol);
422 autoMAT fcol_x_wrow = raw_MAT (data.nrow, data.ncol);
423 autoVEC fcolumn_inv = raw_VEC (data.nrow); // feature column
424 autoVEC wrow_inv = raw_VEC (data.ncol); // weight row
425 mul_MAT_out (fw.get(), my features.get(), my weights.get());
426 double divergence = MATgetDivergence_ItakuraSaito (data, fw.get());
427 const double divergence0 = divergence;
428 if (info)
429 MelderInfo_writeLine (U"Iteration: 0", U" divergence: ", divergence, U" delta: ", divergence);
430 integer iter = 1;
431 bool convergence = false;
432 while (iter <= maximumNumberOfIterations && not convergence) {
433 /*
434 C. Févotte, N. Berin & J.-L. Durrieu (2009), Nonnegative matrix facorization with the Itakura-Saito divergene: with
435 applications to music analysis, Neural Computation 21, 793--830.
436 algorithm 2, page 806
437 until convergence {
438 for k to numberOfFeateres {
439 G(k) = fcol(k) x wrow (k) / F.H (1)
440 V(k) = G(k)^(.2).V+(1-G(k)).(fcol(k) x wrow (k)) (2)
441 wrow (k) <-- (1/fcol(k))' . V(k) / numberOfRows (3)
442 fcol(k) <-- V(k).(1/wrow (k))' / numberOfColumns (4)
443 Normalize fcol(k) and wrow (k) (5)
444 F.H - old(fcol(k) x wrow (k)) + new(fcol(k) x wrow (k)) (6)
445 }
446 }
447 There is no need to calculate G(k) explicitly as in (1).
448 We can calculate the elements of G(k) while we are doing (2).
449 */
450 for (integer kf = 1; kf <= my numberOfFeatures; kf ++) {
451 // (1) and (2)
452 outer_MAT_out (fcol_x_wrow.get(), my features.column (kf), my weights.row (kf));
453 for (integer irow = 1; irow <= data.nrow; irow ++)
454 for (integer icol = 1; icol <= data.ncol; icol ++) {
455 double gk = fcol_x_wrow [irow] [icol] / fw [irow] [icol];
456 vk [irow] [icol] = gk * gk * data [irow] [icol] + (1.0 - gk) * fcol_x_wrow [irow] [icol];
457 }
458 // (3)
459 VECinvertAndScale (fcolumn_inv.get(), my features.column (kf), 1.0 / my numberOfRows);
460 mul_VEC_out (my weights.row (kf), fcolumn_inv.get(), vk.get());
461 // (4)
462 VECinvertAndScale (wrow_inv.get(), my weights.row (kf), 1.0 / my numberOfColumns);
463 mul_VEC_out (my features.column (kf), vk.get(), wrow_inv.get());
464 // (5)
465 double fcolumn_norm = NUMnorm (my features.column (kf), 2.0);
466 my features.column (kf) /= fcolumn_norm;
467 my weights.row (kf) *= fcolumn_norm;
468 // (6)
469 fw.get() -= fcol_x_wrow.get();
470 outer_MAT_out (fcol_x_wrow.get(), my features.column (kf), my weights.row (kf));
471 fw.get() += fcol_x_wrow.get();
472 }
473 const double divergence_update = MATgetDivergence_ItakuraSaito (data, fw.get());
474 const double delta = divergence - divergence_update;
475 convergence = ( iter > 1 && (fabs (delta) < changeTolerance || divergence_update < divergence0 * approximationTolerance) );
476 if (info)
477 MelderInfo_writeLine (U"Iteration: ", iter, U" divergence: ", divergence_update, U" delta: ", delta);
478 ++ iter;
479 divergence = divergence_update;
480 }
481 if (info)
482 MelderInfo_drain();
483
484 } catch (MelderError) {
485 Melder_throw (me, U" IS factorization cannot be improved.");
486 }
487 }
488
489 autoMAT NMF_synthesize (NMF me) {
490 try {
491 autoMAT result = mul_MAT (my features.get(), my weights.get());
492 return result;
493 } catch (MelderError) {
494 Melder_throw (me, U": No matrix created.");
495 }
496 }
497
498 /* End of file NMF.cpp */