Debian Codegraph @

ot/gromov/_dictionary.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 (Fused) Gromov-Wasserstein dictionary learning.
4 """
5
6 # Author: Rémi Flamary <[email protected]>
7 # Cédric Vincent-Cuaz <[email protected]>
8 #
9 # License: MIT License
10
11 import numpy as np
12
13
14 from ..utils import unif, check_random_state
15 from ..backend import get_backend
16 from ._gw import gromov_wasserstein, fused_gromov_wasserstein
17
18
19 def gromov_wasserstein_dictionary_learning(
20 Cs,
21 D,
22 nt,
23 reg=0.0,
24 ps=None,
25 q=None,
26 epochs=20,
27 batch_size=32,
28 learning_rate=1.0,
29 Cdict_init=None,
30 projection="nonnegative_symmetric",
31 use_log=True,
32 tol_outer=10 ** (-5),
33 tol_inner=10 ** (-5),
34 max_iter_outer=20,
35 max_iter_inner=200,
36 use_adam_optimizer=True,
37 verbose=False,
38 random_state=None,
39 **kwargs,
40 ):
41 r"""
42 Infer Gromov-Wasserstein linear dictionary :math:`\{ (\mathbf{C_{dict}[d]}, q) \}_{d \in [D]}` from the list of structures :math:`\{ (\mathbf{C_s},\mathbf{p_s}) \}_s`
43
44 .. math::
45 \min_{\mathbf{C_{dict}}, \{\mathbf{w_s} \}_{s \leq S}} \sum_{s=1}^S GW_2(\mathbf{C_s}, \sum_{d=1}^D w_{s,d}\mathbf{C_{dict}[d]}, \mathbf{p_s}, \mathbf{q}) - reg\| \mathbf{w_s} \|_2^2
46
47 such that, :math:`\forall s \leq S` :
48
49 - :math:`\mathbf{w_s}^\top \mathbf{1}_D = 1`
50 - :math:`\mathbf{w_s} \geq \mathbf{0}_D`
51
52 Where :
53
54 - :math:`\forall s \leq S, \mathbf{C_s}` is a (ns,ns) pairwise similarity matrix of variable size ns.
55 - :math:`\mathbf{C_{dict}}` is a (D, nt, nt) tensor of D pairwise similarity matrix of fixed size nt.
56 - :math:`\forall s \leq S, \mathbf{p_s}` is the source distribution corresponding to :math:`\mathbf{C_s}`
57 - :math:`\mathbf{q}` is the target distribution assigned to every structures in the embedding space.
58 - reg is the regularization coefficient.
59
60 The stochastic algorithm used for estimating the graph dictionary atoms as proposed in [38]_
61
62 Parameters
63 ----------
64 Cs : list of S symmetric array-like, shape (ns, ns)
65 List of Metric/Graph cost matrices of variable size (ns, ns).
66 D: int
67 Number of dictionary atoms to learn
68 nt: int
69 Number of samples within each dictionary atoms
70 reg : float, optional
71 Coefficient of the negative quadratic regularization used to promote sparsity of w. The default is 0.
72 ps : list of S array-like, shape (ns,), optional
73 Distribution in each source space C of Cs. Default is None and corresponds to uniform distributions.
74 q : array-like, shape (nt,), optional
75 Distribution in the embedding space whose structure will be learned. Default is None and corresponds to uniform distributions.
76 epochs: int, optional
77 Number of epochs used to learn the dictionary. Default is 32.
78 batch_size: int, optional
79 Batch size for each stochastic gradient update of the dictionary. Set to the dataset size if the provided batch_size is higher than the dataset size. Default is 32.
80 learning_rate: float, optional
81 Learning rate used for the stochastic gradient descent. Default is 1.
82 Cdict_init: list of D array-like with shape (nt, nt), optional
83 Used to initialize the dictionary.
84 If set to None (Default), the dictionary will be initialized randomly.
85 Else Cdict must have shape (D, nt, nt) i.e match provided shape features.
86 projection: str , optional
87 If 'nonnegative' and/or 'symmetric' is in projection, the corresponding projection will be performed at each stochastic update of the dictionary
88 Else the set of atoms is :math:`R^{nt * nt}`. Default is 'nonnegative_symmetric'
89 log: bool, optional
90 If set to True, losses evolution by batches and epochs are tracked. Default is False.
91 use_adam_optimizer: bool, optional
92 If set to True, adam optimizer with default settings is used as adaptative learning rate strategy.
93 Else perform SGD with fixed learning rate. Default is True.
94 tol_outer : float, optional
95 Solver precision for the BCD algorithm, measured by absolute relative error on consecutive losses. Default is :math:`10^{-5}`.
96 tol_inner : float, optional
97 Solver precision for the Conjugate Gradient algorithm used to get optimal w at a fixed transport, measured by absolute relative error on consecutive losses. Default is :math:`10^{-5}`.
98 max_iter_outer : int, optional
99 Maximum number of iterations for the BCD. Default is 20.
100 max_iter_inner : int, optional
101 Maximum number of iterations for the Conjugate Gradient. Default is 200.
102 verbose : bool, optional
103 Print the reconstruction loss every epoch. Default is False.
104 random_state : int, RandomState instance or None, default=None
105 Determines random number generation. Pass an int for reproducible
106 output across multiple function calls.
107
108 Returns
109 -------
110
111 Cdict_best_state : D array-like, shape (D,nt,nt)
112 Metric/Graph cost matrices composing the dictionary.
113 The dictionary leading to the best loss over an epoch is saved and returned.
114 log: dict
115 If use_log is True, contains loss evolutions by batches and epochs.
116
117 References
118 -------
119 .. [38] C. Vincent-Cuaz, T. Vayer, R. Flamary, M. Corneli, N. Courty, Online
120 Graph Dictionary Learning, International Conference on Machine Learning
121 (ICML), 2021.
122 """
123 # Handle backend of non-optional arguments
124 Cs0 = Cs
125 nx = get_backend(*Cs0)
126 Cs = [nx.to_numpy(C) for C in Cs0]
127 dataset_size = len(Cs)
128 # Handle backend of optional arguments
129 if ps is None:
130 ps = [unif(C.shape[0]) for C in Cs]
131 else:
132 ps = [nx.to_numpy(p) for p in ps]
133 if q is None:
134 q = unif(nt)
135 else:
136 q = nx.to_numpy(q)
137 rng = check_random_state(random_state)
138 if Cdict_init is None:
139 # Initialize randomly structures of dictionary atoms based on samples
140 dataset_means = [C.mean() for C in Cs]
141 Cdict = rng.normal(
142 loc=np.mean(dataset_means), scale=np.std(dataset_means), size=(D, nt, nt)
143 )
144 else:
145 Cdict = nx.to_numpy(Cdict_init).copy()
146 assert Cdict.shape == (D, nt, nt)
147
148 if "symmetric" in projection:
149 Cdict = 0.5 * (Cdict + Cdict.transpose((0, 2, 1)))
150 symmetric = True
151 else:
152 symmetric = False
153 if "nonnegative" in projection:
154 Cdict[Cdict < 0.0] = 0
155 if use_adam_optimizer:
156 adam_moments = _initialize_adam_optimizer(Cdict)
157
158 log = {"loss_batches": [], "loss_epochs": []}
159 const_q = q[:, None] * q[None, :]
160 Cdict_best_state = Cdict.copy()
161 loss_best_state = np.inf
162 if batch_size > dataset_size:
163 batch_size = dataset_size
164 iter_by_epoch = dataset_size // batch_size + int((dataset_size % batch_size) > 0)
165
166 for epoch in range(epochs):
167 cumulated_loss_over_epoch = 0.0
168
169 for _ in range(iter_by_epoch):
170 # batch sampling
171 batch = rng.choice(range(dataset_size), size=batch_size, replace=False)
172 cumulated_loss_over_batch = 0.0
173 unmixings = np.zeros((batch_size, D))
174 Cs_embedded = np.zeros((batch_size, nt, nt))
175 Ts = [None] * batch_size
176
177 for batch_idx, C_idx in enumerate(batch):
178 # BCD solver for Gromov-Wasserstein linear unmixing used independently on each structure of the sampled batch
179 (
180 unmixings[batch_idx],
181 Cs_embedded[batch_idx],
182 Ts[batch_idx],
183 current_loss,
184 ) = gromov_wasserstein_linear_unmixing(
185 Cs[C_idx],
186 Cdict,
187 reg=reg,
188 p=ps[C_idx],
189 q=q,
190 tol_outer=tol_outer,
191 tol_inner=tol_inner,
192 max_iter_outer=max_iter_outer,
193 max_iter_inner=max_iter_inner,
194 symmetric=symmetric,
195 **kwargs,
196 )
197 cumulated_loss_over_batch += current_loss
198 cumulated_loss_over_epoch += cumulated_loss_over_batch
199
200 if use_log:
201 log["loss_batches"].append(cumulated_loss_over_batch)
202
203 # Stochastic projected gradient step over dictionary atoms
204 grad_Cdict = np.zeros_like(Cdict)
205 for batch_idx, C_idx in enumerate(batch):
206 shared_term_structures = Cs_embedded[batch_idx] * const_q - (
207 Cs[C_idx].dot(Ts[batch_idx])
208 ).T.dot(Ts[batch_idx])
209 grad_Cdict += (
210 unmixings[batch_idx][:, None, None]
211 * shared_term_structures[None, :, :]
212 )
213 grad_Cdict *= 2 / batch_size
214 if use_adam_optimizer:
215 Cdict, adam_moments = _adam_stochastic_updates(
216 Cdict, grad_Cdict, learning_rate, adam_moments
217 )
218 else:
219 Cdict -= learning_rate * grad_Cdict
220 if "symmetric" in projection:
221 Cdict = 0.5 * (Cdict + Cdict.transpose((0, 2, 1)))
222 if "nonnegative" in projection:
223 Cdict[Cdict < 0.0] = 0.0
224
225 if use_log:
226 log["loss_epochs"].append(cumulated_loss_over_epoch)
227 if loss_best_state > cumulated_loss_over_epoch:
228 loss_best_state = cumulated_loss_over_epoch
229 Cdict_best_state = Cdict.copy()
230 if verbose:
231 print(
232 "--- epoch =",
233 epoch,
234 " cumulated reconstruction error: ",
235 cumulated_loss_over_epoch,
236 )
237
238 return nx.from_numpy(Cdict_best_state), log
239
240
241 def _initialize_adam_optimizer(variable):
242 # Initialization for our numpy implementation of adam optimizer
243 atoms_adam_m = np.zeros_like(variable) # Initialize first moment tensor
244 atoms_adam_v = np.zeros_like(variable) # Initialize second moment tensor
245 atoms_adam_count = 1
246
247 return {"mean": atoms_adam_m, "var": atoms_adam_v, "count": atoms_adam_count}
248
249
250 def _adam_stochastic_updates(
251 variable, grad, learning_rate, adam_moments, beta_1=0.9, beta_2=0.99, eps=1e-09
252 ):
253 adam_moments["mean"] = beta_1 * adam_moments["mean"] + (1 - beta_1) * grad
254 adam_moments["var"] = beta_2 * adam_moments["var"] + (1 - beta_2) * (grad**2)
255 unbiased_m = adam_moments["mean"] / (1 - beta_1 ** adam_moments["count"])
256 unbiased_v = adam_moments["var"] / (1 - beta_2 ** adam_moments["count"])
257 variable -= learning_rate * unbiased_m / (np.sqrt(unbiased_v) + eps)
258 adam_moments["count"] += 1
259
260 return variable, adam_moments
261
262
263 def gromov_wasserstein_linear_unmixing(
264 C,
265 Cdict,
266 reg=0.0,
267 p=None,
268 q=None,
269 tol_outer=10 ** (-5),
270 tol_inner=10 ** (-5),
271 max_iter_outer=20,
272 max_iter_inner=200,
273 symmetric=None,
274 **kwargs,
275 ):
276 r"""
277 Returns the Gromov-Wasserstein linear unmixing of :math:`(\mathbf{C},\mathbf{p})` onto the dictionary :math:`\{ (\mathbf{C_{dict}[d]}, \mathbf{q}) \}_{d \in [D]}`.
278
279 .. math::
280 \min_{ \mathbf{w}} GW_2(\mathbf{C}, \sum_{d=1}^D w_d\mathbf{C_{dict}[d]}, \mathbf{p}, \mathbf{q}) - reg \| \mathbf{w} \|_2^2
281
282 such that:
283
284 - :math:`\mathbf{w}^\top \mathbf{1}_D = 1`
285 - :math:`\mathbf{w} \geq \mathbf{0}_D`
286
287 Where :
288
289 - :math:`\mathbf{C}` is the (ns,ns) pairwise similarity matrix.
290 - :math:`\mathbf{C_{dict}}` is a (D, nt, nt) tensor of D pairwise similarity matrices of size nt.
291 - :math:`\mathbf{p}` and :math:`\mathbf{q}` are source and target weights.
292 - reg is the regularization coefficient.
293
294 The algorithm used for solving the problem is a Block Coordinate Descent as discussed in [38]_ , algorithm 1.
295
296 Parameters
297 ----------
298 C : array-like, shape (ns, ns)
299 Metric/Graph cost matrix.
300 Cdict : D array-like, shape (D,nt,nt)
301 Metric/Graph cost matrices composing the dictionary on which to embed C.
302 reg : float, optional.
303 Coefficient of the negative quadratic regularization used to promote sparsity of w. Default is 0.
304 p : array-like, shape (ns,), optional
305 Distribution in the source space C. Default is None and corresponds to uniform distribution.
306 q : array-like, shape (nt,), optional
307 Distribution in the space depicted by the dictionary. Default is None and corresponds to uniform distribution.
308 tol_outer : float, optional
309 Solver precision for the BCD algorithm.
310 tol_inner : float, optional
311 Solver precision for the Conjugate Gradient algorithm used to get optimal w at a fixed transport. Default is :math:`10^{-5}`.
312 max_iter_outer : int, optional
313 Maximum number of iterations for the BCD. Default is 20.
314 max_iter_inner : int, optional
315 Maximum number of iterations for the Conjugate Gradient. Default is 200.
316
317 Returns
318 -------
319 w: array-like, shape (D,)
320 Gromov-Wasserstein linear unmixing of :math:`(\mathbf{C},\mathbf{p})` onto the span of the dictionary.
321 Cembedded: array-like, shape (nt,nt)
322 embedded structure of :math:`(\mathbf{C},\mathbf{p})` onto the dictionary, :math:`\sum_d w_d\mathbf{C_{dict}[d]}`.
323 T: array-like (ns, nt)
324 Gromov-Wasserstein transport plan between :math:`(\mathbf{C},\mathbf{p})` and :math:`(\sum_d w_d\mathbf{C_{dict}[d]}, \mathbf{q})`
325 current_loss: float
326 reconstruction error
327 References
328 -------
329 .. [38] C. Vincent-Cuaz, T. Vayer, R. Flamary, M. Corneli, N. Courty, Online
330 Graph Dictionary Learning, International Conference on Machine Learning
331 (ICML), 2021.
332 """
333 C0, Cdict0 = C, Cdict
334 nx = get_backend(C0, Cdict0)
335 C = nx.to_numpy(C0)
336 Cdict = nx.to_numpy(Cdict0)
337 if p is None:
338 p = unif(C.shape[0])
339 else:
340 p = nx.to_numpy(p)
341
342 if q is None:
343 q = unif(Cdict.shape[-1])
344 else:
345 q = nx.to_numpy(q)
346
347 T = p[:, None] * q[None, :]
348 D = len(Cdict)
349
350 w = unif(D) # Initialize uniformly the unmixing w
351 Cembedded = np.sum(w[:, None, None] * Cdict, axis=0)
352
353 const_q = q[:, None] * q[None, :]
354 # Trackers for BCD convergence
355 convergence_criterion = np.inf
356 current_loss = 10**15
357 outer_count = 0
358
359 while (convergence_criterion > tol_outer) and (outer_count < max_iter_outer):
360 previous_loss = current_loss
361 # 1. Solve GW transport between (C,p) and (\sum_d Cdictionary[d],q) fixing the unmixing w
362 T, log = gromov_wasserstein(
363 C1=C,
364 C2=Cembedded,
365 p=p,
366 q=q,
367 loss_fun="square_loss",
368 G0=T,
369 max_iter=max_iter_inner,
370 tol_rel=tol_inner,
371 tol_abs=0.0,
372 log=True,
373 armijo=False,
374 symmetric=symmetric,
375 **kwargs,
376 )
377 current_loss = log["gw_dist"]
378 if reg != 0:
379 current_loss -= reg * np.sum(w**2)
380
381 # 2. Solve linear unmixing problem over w with a fixed transport plan T
382 w, Cembedded, current_loss = _cg_gromov_wasserstein_unmixing(
383 C=C,
384 Cdict=Cdict,
385 Cembedded=Cembedded,
386 w=w,
387 const_q=const_q,
388 T=T,
389 starting_loss=current_loss,
390 reg=reg,
391 tol=tol_inner,
392 max_iter=max_iter_inner,
393 **kwargs,
394 )
395
396 if previous_loss != 0:
397 convergence_criterion = abs(previous_loss - current_loss) / abs(
398 previous_loss
399 )
400 else: # handle numerical issues around 0
401 convergence_criterion = abs(previous_loss - current_loss) / 10 ** (-15)
402 outer_count += 1
403
404 return (
405 nx.from_numpy(w),
406 nx.from_numpy(Cembedded),
407 nx.from_numpy(T),
408 nx.from_numpy(current_loss),
409 )
410
411
412 def _cg_gromov_wasserstein_unmixing(
413 C,
414 Cdict,
415 Cembedded,
416 w,
417 const_q,
418 T,
419 starting_loss,
420 reg=0.0,
421 tol=10 ** (-5),
422 max_iter=200,
423 **kwargs,
424 ):
425 r"""
426 Returns for a fixed admissible transport plan,
427 the linear unmixing w minimizing the Gromov-Wasserstein cost between :math:`(\mathbf{C},\mathbf{p})` and :math:`(\sum_d w[d]*\mathbf{C_{dict}[d]}, \mathbf{q})`
428
429 .. math::
430 \min_{\mathbf{w}} \sum_{ijkl} (C_{i,j} - \sum_{d=1}^D w_d*C_{dict}[d]_{k,l} )^2 T_{i,k}T_{j,l} - reg* \| \mathbf{w} \|_2^2
431
432
433 Such that:
434
435 - :math:`\mathbf{w}^\top \mathbf{1}_D = 1`
436 - :math:`\mathbf{w} \geq \mathbf{0}_D`
437
438 Where :
439
440 - :math:`\mathbf{C}` is the (ns,ns) pairwise similarity matrix.
441 - :math:`\mathbf{C_{dict}}` is a (D, nt, nt) tensor of D pairwise similarity matrices of nt points.
442 - :math:`\mathbf{p}` and :math:`\mathbf{q}` are source and target weights.
443 - :math:`\mathbf{w}` is the linear unmixing of :math:`(\mathbf{C}, \mathbf{p})` onto :math:`(\sum_d w_d \mathbf{Cdict[d]}, \mathbf{q})`.
444 - :math:`\mathbf{T}` is the optimal transport plan conditioned by the current state of :math:`\mathbf{w}`.
445 - reg is the regularization coefficient.
446
447 The algorithm used for solving the problem is a Conditional Gradient Descent as discussed in [38]_
448
449 Parameters
450 ----------
451
452 C : array-like, shape (ns, ns)
453 Metric/Graph cost matrix.
454 Cdict : list of D array-like, shape (nt,nt)
455 Metric/Graph cost matrices composing the dictionary on which to embed C.
456 Each matrix in the dictionary must have the same size (nt,nt).
457 Cembedded: array-like, shape (nt,nt)
458 Embedded structure :math:`(\sum_d w[d]*Cdict[d],q)` of :math:`(\mathbf{C},\mathbf{p})` onto the dictionary. Used to avoid redundant computations.
459 w: array-like, shape (D,)
460 Linear unmixing of the input structure onto the dictionary
461 const_q: array-like, shape (nt,nt)
462 product matrix :math:`\mathbf{q}\mathbf{q}^\top` where q is the target space distribution. Used to avoid redundant computations.
463 T: array-like, shape (ns,nt)
464 fixed transport plan between the input structure and its representation in the dictionary.
465 p : array-like, shape (ns,)
466 Distribution in the source space.
467 q : array-like, shape (nt,)
468 Distribution in the embedding space depicted by the dictionary.
469 reg : float, optional.
470 Coefficient of the negative quadratic regularization used to promote sparsity of w. Default is 0.
471
472 Returns
473 -------
474 w: ndarray (D,)
475 optimal unmixing of :math:`(\mathbf{C},\mathbf{p})` onto the dictionary span given OT starting from previously optimal unmixing.
476 """
477 convergence_criterion = np.inf
478 current_loss = starting_loss
479 count = 0
480 const_TCT = np.transpose(C.dot(T)).dot(T)
481
482 while (convergence_criterion > tol) and (count < max_iter):
483 previous_loss = current_loss
484 # 1) Compute gradient at current point w
485 grad_w = 2 * np.sum(
486 Cdict
487 * (Cembedded[None, :, :] * const_q[None, :, :] - const_TCT[None, :, :]),
488 axis=(1, 2),
489 )
490 grad_w -= 2 * reg * w
491
492 # 2) Conditional gradient direction finding: x= \argmin_x x^T.grad_w
493 min_ = np.min(grad_w)
494 x = (grad_w == min_).astype(np.float64)
495 x /= np.sum(x)
496
497 # 3) Line-search step: solve \argmin_{\gamma \in [0,1]} a*gamma^2 + b*gamma + c
498 gamma, a, b, Cembedded_diff = _linesearch_gromov_wasserstein_unmixing(
499 w, grad_w, x, Cdict, Cembedded, const_q, const_TCT, reg
500 )
501
502 # 4) Updates: w <-- (1-gamma)*w + gamma*x
503 w += gamma * (x - w)
504 Cembedded += gamma * Cembedded_diff
505 current_loss += a * (gamma**2) + b * gamma
506
507 if previous_loss != 0: # not that the loss can be negative if reg >0
508 convergence_criterion = abs(previous_loss - current_loss) / abs(
509 previous_loss
510 )
511 else: # handle numerical issues around 0
512 convergence_criterion = abs(previous_loss - current_loss) / 10 ** (-15)
513 count += 1
514
515 return w, Cembedded, current_loss
516
517
518 def _linesearch_gromov_wasserstein_unmixing(
519 w, grad_w, x, Cdict, Cembedded, const_q, const_TCT, reg, **kwargs
520 ):
521 r"""
522 Compute optimal steps for the line search problem of Gromov-Wasserstein linear unmixing
523 .. math::
524 \min_{\gamma \in [0,1]} \sum_{ijkl} (C_{i,j} - \sum_{d=1}^D z_d(\gamma)C_{dict}[d]_{k,l} )^2 T_{i,k}T_{j,l} - reg\| \mathbf{z}(\gamma) \|_2^2
525
526
527 Such that:
528
529 - :math:`\mathbf{z}(\gamma) = (1- \gamma)\mathbf{w} + \gamma \mathbf{x}`
530
531 Parameters
532 ----------
533
534 w : array-like, shape (D,)
535 Unmixing.
536 grad_w : array-like, shape (D, D)
537 Gradient of the reconstruction loss with respect to w.
538 x: array-like, shape (D,)
539 Conditional gradient direction.
540 Cdict : list of D array-like, shape (nt,nt)
541 Metric/Graph cost matrices composing the dictionary on which to embed C.
542 Each matrix in the dictionary must have the same size (nt,nt).
543 Cembedded: array-like, shape (nt,nt)
544 Embedded structure :math:`(\sum_d w_dCdict[d],q)` of :math:`(\mathbf{C},\mathbf{p})` onto the dictionary. Used to avoid redundant computations.
545 const_q: array-like, shape (nt,nt)
546 product matrix :math:`\mathbf{q}\mathbf{q}^\top` where q is the target space distribution. Used to avoid redundant computations.
547 const_TCT: array-like, shape (nt, nt)
548 :math:`\mathbf{T}^\top \mathbf{C}^\top \mathbf{T}`. Used to avoid redundant computations.
549 Returns
550 -------
551 gamma: float
552 Optimal value for the line-search step
553 a: float
554 Constant factor appearing in the factorization :math:`a \gamma^2 + b \gamma +c` of the reconstruction loss
555 b: float
556 Constant factor appearing in the factorization :math:`a \gamma^2 + b \gamma +c` of the reconstruction loss
557 Cembedded_diff: numpy array, shape (nt, nt)
558 Difference between models evaluated in :math:`\mathbf{w}` and in :math:`\mathbf{w}`.
559 reg : float, optional.
560 Coefficient of the negative quadratic regularization used to promote sparsity of :math:`\mathbf{w}`.
561 """
562
563 # 3) Line-search step: solve \argmin_{\gamma \in [0,1]} a*gamma^2 + b*gamma + c
564 Cembedded_x = np.sum(x[:, None, None] * Cdict, axis=0)
565 Cembedded_diff = Cembedded_x - Cembedded
566 trace_diffx = np.sum(Cembedded_diff * Cembedded_x * const_q)
567 trace_diffw = np.sum(Cembedded_diff * Cembedded * const_q)
568 a = trace_diffx - trace_diffw
569 b = 2 * (trace_diffw - np.sum(Cembedded_diff * const_TCT))
570 if reg != 0:
571 a -= reg * np.sum((x - w) ** 2)
572 b -= 2 * reg * np.sum(w * (x - w))
573
574 if a > 0:
575 gamma = min(1, max(0, -b / (2 * a)))
576 elif a + b < 0:
577 gamma = 1
578 else:
579 gamma = 0
580
581 return gamma, a, b, Cembedded_diff
582
583
584 def fused_gromov_wasserstein_dictionary_learning(
585 Cs,
586 Ys,
587 D,
588 nt,
589 alpha,
590 reg=0.0,
591 ps=None,
592 q=None,
593 epochs=20,
594 batch_size=32,
595 learning_rate_C=1.0,
596 learning_rate_Y=1.0,
597 Cdict_init=None,
598 Ydict_init=None,
599 projection="nonnegative_symmetric",
600 use_log=False,
601 tol_outer=10 ** (-5),
602 tol_inner=10 ** (-5),
603 max_iter_outer=20,
604 max_iter_inner=200,
605 use_adam_optimizer=True,
606 verbose=False,
607 random_state=None,
608 **kwargs,
609 ):
610 r"""
611 Infer Fused Gromov-Wasserstein linear dictionary :math:`\{ (\mathbf{C_{dict}[d]}, \mathbf{Y_{dict}[d]}, \mathbf{q}) \}_{d \in [D]}` from the list of S attributed structures :math:`\{ (\mathbf{C_s}, \mathbf{Y_s},\mathbf{p_s}) \}_s`
612
613 .. math::
614 \min_{\mathbf{C_{dict}},\mathbf{Y_{dict}}, \{\mathbf{w_s}\}_{s}} \sum_{s=1}^S FGW_{2,\alpha}(\mathbf{C_s}, \mathbf{Y_s}, \sum_{d=1}^D w_{s,d}\mathbf{C_{dict}[d]},\sum_{d=1}^D w_{s,d}\mathbf{Y_{dict}[d]}, \mathbf{p_s}, \mathbf{q}) \\ - reg\| \mathbf{w_s} \|_2^2
615
616
617 Such that :math:`\forall s \leq S` :
618
619 - :math:`\mathbf{w_s}^\top \mathbf{1}_D = 1`
620 - :math:`\mathbf{w_s} \geq \mathbf{0}_D`
621
622 Where :
623
624 - :math:`\forall s \leq S, \mathbf{C_s}` is a (ns,ns) pairwise similarity matrix of variable size ns.
625 - :math:`\forall s \leq S, \mathbf{Y_s}` is a (ns,d) features matrix of variable size ns and fixed dimension d.
626 - :math:`\mathbf{C_{dict}}` is a (D, nt, nt) tensor of D pairwise similarity matrix of fixed size nt.
627 - :math:`\mathbf{Y_{dict}}` is a (D, nt, d) tensor of D features matrix of fixed size nt and fixed dimension d.
628 - :math:`\forall s \leq S, \mathbf{p_s}` is the source distribution corresponding to :math:`\mathbf{C_s}`
629 - :math:`\mathbf{q}` is the target distribution assigned to every structures in the embedding space.
630 - :math:`\alpha` is the trade-off parameter of Fused Gromov-Wasserstein
631 - reg is the regularization coefficient.
632
633
634 The stochastic algorithm used for estimating the attributed graph dictionary atoms as proposed in [38]_
635
636 Parameters
637 ----------
638 Cs : list of S symmetric array-like, shape (ns, ns)
639 List of Metric/Graph cost matrices of variable size (ns,ns).
640 Ys : list of S array-like, shape (ns, d)
641 List of feature matrix of variable size (ns,d) with d fixed.
642 D: int
643 Number of dictionary atoms to learn
644 nt: int
645 Number of samples within each dictionary atoms
646 alpha : float
647 Trade-off parameter of Fused Gromov-Wasserstein
648 reg : float, optional
649 Coefficient of the negative quadratic regularization used to promote sparsity of w. The default is 0.
650 ps : list of S array-like, shape (ns,), optional
651 Distribution in each source space C of Cs. Default is None and corresponds to uniform distributions.
652 q : array-like, shape (nt,), optional
653 Distribution in the embedding space whose structure will be learned. Default is None and corresponds to uniform distributions.
654 epochs: int, optional
655 Number of epochs used to learn the dictionary. Default is 32.
656 batch_size: int, optional
657 Batch size for each stochastic gradient update of the dictionary. Set to the dataset size if the provided batch_size is higher than the dataset size. Default is 32.
658 learning_rate_C: float, optional
659 Learning rate used for the stochastic gradient descent on Cdict. Default is 1.
660 learning_rate_Y: float, optional
661 Learning rate used for the stochastic gradient descent on Ydict. Default is 1.
662 Cdict_init: list of D array-like with shape (nt, nt), optional
663 Used to initialize the dictionary structures Cdict.
664 If set to None (Default), the dictionary will be initialized randomly.
665 Else Cdict must have shape (D, nt, nt) i.e match provided shape features.
666 Ydict_init: list of D array-like with shape (nt, d), optional
667 Used to initialize the dictionary features Ydict.
668 If set to None, the dictionary features will be initialized randomly.
669 Else Ydict must have shape (D, nt, d) where d is the features dimension of inputs Ys and also match provided shape features.
670 projection: str, optional
671 If 'nonnegative' and/or 'symmetric' is in projection, the corresponding projection will be performed at each stochastic update of the dictionary
672 Else the set of atoms is :math:`R^{nt * nt}`. Default is 'nonnegative_symmetric'
673 log: bool, optional
674 If set to True, losses evolution by batches and epochs are tracked. Default is False.
675 use_adam_optimizer: bool, optional
676 If set to True, adam optimizer with default settings is used as adaptative learning rate strategy.
677 Else perform SGD with fixed learning rate. Default is True.
678 tol_outer : float, optional
679 Solver precision for the BCD algorithm, measured by absolute relative error on consecutive losses. Default is :math:`10^{-5}`.
680 tol_inner : float, optional
681 Solver precision for the Conjugate Gradient algorithm used to get optimal w at a fixed transport, measured by absolute relative error on consecutive losses. Default is :math:`10^{-5}`.
682 max_iter_outer : int, optional
683 Maximum number of iterations for the BCD. Default is 20.
684 max_iter_inner : int, optional
685 Maximum number of iterations for the Conjugate Gradient. Default is 200.
686 verbose : bool, optional
687 Print the reconstruction loss every epoch. Default is False.
688 random_state : int, RandomState instance or None, default=None
689 Determines random number generation. Pass an int for reproducible
690 output across multiple function calls.
691
692 Returns
693 -------
694
695 Cdict_best_state : D array-like, shape (D,nt,nt)
696 Metric/Graph cost matrices composing the dictionary.
697 The dictionary leading to the best loss over an epoch is saved and returned.
698 Ydict_best_state : D array-like, shape (D,nt,d)
699 Feature matrices composing the dictionary.
700 The dictionary leading to the best loss over an epoch is saved and returned.
701 log: dict
702 If use_log is True, contains loss evolutions by batches and epochs.
703
704 References
705 -------
706 .. [38] C. Vincent-Cuaz, T. Vayer, R. Flamary, M. Corneli, N. Courty, Online
707 Graph Dictionary Learning, International Conference on Machine Learning
708 (ICML), 2021.
709 """
710 Cs0, Ys0 = Cs, Ys
711 nx = get_backend(*Cs0, *Ys0)
712 Cs = [nx.to_numpy(C) for C in Cs0]
713 Ys = [nx.to_numpy(Y) for Y in Ys0]
714
715 d = Ys[0].shape[-1]
716 dataset_size = len(Cs)
717
718 if ps is None:
719 ps = [unif(C.shape[0]) for C in Cs]
720 else:
721 ps = [nx.to_numpy(p) for p in ps]
722 if q is None:
723 q = unif(nt)
724 else:
725 q = nx.to_numpy(q)
726
727 rng = check_random_state(random_state)
728 if Cdict_init is None:
729 # Initialize randomly structures of dictionary atoms based on samples
730 dataset_means = [C.mean() for C in Cs]
731 Cdict = rng.normal(
732 loc=np.mean(dataset_means), scale=np.std(dataset_means), size=(D, nt, nt)
733 )
734 else:
735 Cdict = nx.to_numpy(Cdict_init).copy()
736 assert Cdict.shape == (D, nt, nt)
737 if Ydict_init is None:
738 # Initialize randomly features of dictionary atoms based on samples distribution by feature component
739 dataset_feature_means = np.stack([F.mean(axis=0) for F in Ys])
740 Ydict = rng.normal(
741 loc=dataset_feature_means.mean(axis=0),
742 scale=dataset_feature_means.std(axis=0),
743 size=(D, nt, d),
744 )
745 else:
746 Ydict = nx.to_numpy(Ydict_init).copy()
747 assert Ydict.shape == (D, nt, d)
748
749 if "symmetric" in projection:
750 Cdict = 0.5 * (Cdict + Cdict.transpose((0, 2, 1)))
751 symmetric = True
752 else:
753 symmetric = False
754 if "nonnegative" in projection:
755 Cdict[Cdict < 0.0] = 0.0
756
757 if use_adam_optimizer:
758 adam_moments_C = _initialize_adam_optimizer(Cdict)
759 adam_moments_Y = _initialize_adam_optimizer(Ydict)
760
761 log = {"loss_batches": [], "loss_epochs": []}
762 const_q = q[:, None] * q[None, :]
763 diag_q = np.diag(q)
764 Cdict_best_state = Cdict.copy()
765 Ydict_best_state = Ydict.copy()
766 loss_best_state = np.inf
767 if batch_size > dataset_size:
768 batch_size = dataset_size
769 iter_by_epoch = dataset_size // batch_size + int((dataset_size % batch_size) > 0)
770
771 for epoch in range(epochs):
772 cumulated_loss_over_epoch = 0.0
773
774 for _ in range(iter_by_epoch):
775 # Batch iterations
776 batch = rng.choice(range(dataset_size), size=batch_size, replace=False)
777 cumulated_loss_over_batch = 0.0
778 unmixings = np.zeros((batch_size, D))
779 Cs_embedded = np.zeros((batch_size, nt, nt))
780 Ys_embedded = np.zeros((batch_size, nt, d))
781 Ts = [None] * batch_size
782
783 for batch_idx, C_idx in enumerate(batch):
784 # BCD solver for Gromov-Wasserstein linear unmixing used independently on each structure of the sampled batch
785 (
786 unmixings[batch_idx],
787 Cs_embedded[batch_idx],
788 Ys_embedded[batch_idx],
789 Ts[batch_idx],
790 current_loss,
791 ) = fused_gromov_wasserstein_linear_unmixing(
792 Cs[C_idx],
793 Ys[C_idx],
794 Cdict,
795 Ydict,
796 alpha,
797 reg=reg,
798 p=ps[C_idx],
799 q=q,
800 tol_outer=tol_outer,
801 tol_inner=tol_inner,
802 max_iter_outer=max_iter_outer,
803 max_iter_inner=max_iter_inner,
804 symmetric=symmetric,
805 **kwargs,
806 )
807 cumulated_loss_over_batch += current_loss
808 cumulated_loss_over_epoch += cumulated_loss_over_batch
809 if use_log:
810 log["loss_batches"].append(cumulated_loss_over_batch)
811
812 # Stochastic projected gradient step over dictionary atoms
813 grad_Cdict = np.zeros_like(Cdict)
814 grad_Ydict = np.zeros_like(Ydict)
815
816 for batch_idx, C_idx in enumerate(batch):
817 shared_term_structures = Cs_embedded[batch_idx] * const_q - (
818 Cs[C_idx].dot(Ts[batch_idx])
819 ).T.dot(Ts[batch_idx])
820 shared_term_features = diag_q.dot(Ys_embedded[batch_idx]) - Ts[
821 batch_idx
822 ].T.dot(Ys[C_idx])
823 grad_Cdict += (
824 alpha
825 * unmixings[batch_idx][:, None, None]
826 * shared_term_structures[None, :, :]
827 )
828 grad_Ydict += (
829 (1 - alpha)
830 * unmixings[batch_idx][:, None, None]
831 * shared_term_features[None, :, :]
832 )
833 grad_Cdict *= 2 / batch_size
834 grad_Ydict *= 2 / batch_size
835
836 if use_adam_optimizer:
837 Cdict, adam_moments_C = _adam_stochastic_updates(
838 Cdict, grad_Cdict, learning_rate_C, adam_moments_C
839 )
840 Ydict, adam_moments_Y = _adam_stochastic_updates(
841 Ydict, grad_Ydict, learning_rate_Y, adam_moments_Y
842 )
843 else:
844 Cdict -= learning_rate_C * grad_Cdict
845 Ydict -= learning_rate_Y * grad_Ydict
846
847 if "symmetric" in projection:
848 Cdict = 0.5 * (Cdict + Cdict.transpose((0, 2, 1)))
849 if "nonnegative" in projection:
850 Cdict[Cdict < 0.0] = 0.0
851
852 if use_log:
853 log["loss_epochs"].append(cumulated_loss_over_epoch)
854 if loss_best_state > cumulated_loss_over_epoch:
855 loss_best_state = cumulated_loss_over_epoch
856 Cdict_best_state = Cdict.copy()
857 Ydict_best_state = Ydict.copy()
858 if verbose:
859 print(
860 "--- epoch: ",
861 epoch,
862 " cumulated reconstruction error: ",
863 cumulated_loss_over_epoch,
864 )
865
866 return nx.from_numpy(Cdict_best_state), nx.from_numpy(Ydict_best_state), log
867
868
869 def fused_gromov_wasserstein_linear_unmixing(
870 C,
871 Y,
872 Cdict,
873 Ydict,
874 alpha,
875 reg=0.0,
876 p=None,
877 q=None,
878 tol_outer=10 ** (-5),
879 tol_inner=10 ** (-5),
880 max_iter_outer=20,
881 max_iter_inner=200,
882 symmetric=True,
883 **kwargs,
884 ):
885 r"""
886 Returns the Fused Gromov-Wasserstein linear unmixing of :math:`(\mathbf{C},\mathbf{Y},\mathbf{p})` onto the attributed dictionary atoms :math:`\{ (\mathbf{C_{dict}[d]},\mathbf{Y_{dict}[d]}, \mathbf{q}) \}_{d \in [D]}`
887
888 .. math::
889 \min_{\mathbf{w}} FGW_{2,\alpha}(\mathbf{C},\mathbf{Y}, \sum_{d=1}^D w_d\mathbf{C_{dict}[d]},\sum_{d=1}^D w_d\mathbf{Y_{dict}[d]}, \mathbf{p}, \mathbf{q}) - reg \| \mathbf{w} \|_2^2
890
891 such that, :math:`\forall s \leq S` :
892
893 - :math:`\mathbf{w_s}^\top \mathbf{1}_D = 1`
894 - :math:`\mathbf{w_s} \geq \mathbf{0}_D`
895
896 Where :
897
898 - :math:`\mathbf{C}` is a (ns,ns) pairwise similarity matrix of variable size ns.
899 - :math:`\mathbf{Y}` is a (ns,d) features matrix of variable size ns and fixed dimension d.
900 - :math:`\mathbf{C_{dict}}` is a (D, nt, nt) tensor of D pairwise similarity matrix of fixed size nt.
901 - :math:`\mathbf{Y_{dict}}` is a (D, nt, d) tensor of D features matrix of fixed size nt and fixed dimension d.
902 - :math:`\mathbf{p}` is the source distribution corresponding to :math:`\mathbf{C_s}`
903 - :math:`\mathbf{q}` is the target distribution assigned to every structures in the embedding space.
904 - :math:`\alpha` is the trade-off parameter of Fused Gromov-Wasserstein
905 - reg is the regularization coefficient.
906
907 The algorithm used for solving the problem is a Block Coordinate Descent as discussed in [38]_, algorithm 6.
908
909 Parameters
910 ----------
911 C : array-like, shape (ns, ns)
912 Metric/Graph cost matrix.
913 Y : array-like, shape (ns, d)
914 Feature matrix.
915 Cdict : D array-like, shape (D,nt,nt)
916 Metric/Graph cost matrices composing the dictionary on which to embed (C,Y).
917 Ydict : D array-like, shape (D,nt,d)
918 Feature matrices composing the dictionary on which to embed (C,Y).
919 alpha: float,
920 Trade-off parameter of Fused Gromov-Wasserstein.
921 reg : float, optional
922 Coefficient of the negative quadratic regularization used to promote sparsity of w. The default is 0.
923 p : array-like, shape (ns,), optional
924 Distribution in the source space C. Default is None and corresponds to uniform distribution.
925 q : array-like, shape (nt,), optional
926 Distribution in the space depicted by the dictionary. Default is None and corresponds to uniform distribution.
927 tol_outer : float, optional
928 Solver precision for the BCD algorithm.
929 tol_inner : float, optional
930 Solver precision for the Conjugate Gradient algorithm used to get optimal w at a fixed transport. Default is :math:`10^{-5}`.
931 max_iter_outer : int, optional
932 Maximum number of iterations for the BCD. Default is 20.
933 max_iter_inner : int, optional
934 Maximum number of iterations for the Conjugate Gradient. Default is 200.
935
936 Returns
937 -------
938 w: array-like, shape (D,)
939 fused Gromov-Wasserstein linear unmixing of (C,Y,p) onto the span of the dictionary.
940 Cembedded: array-like, shape (nt,nt)
941 embedded structure of :math:`(\mathbf{C},\mathbf{Y}, \mathbf{p})` onto the dictionary, :math:`\sum_d w_d\mathbf{C_{dict}[d]}`.
942 Yembedded: array-like, shape (nt,d)
943 embedded features of :math:`(\mathbf{C},\mathbf{Y}, \mathbf{p})` onto the dictionary, :math:`\sum_d w_d\mathbf{Y_{dict}[d]}`.
944 T: array-like (ns,nt)
945 Fused Gromov-Wasserstein transport plan between :math:`(\mathbf{C},\mathbf{p})` and :math:`(\sum_d w_d\mathbf{C_{dict}[d]}, \sum_d w_d\mathbf{Y_{dict}[d]},\mathbf{q})`.
946 current_loss: float
947 reconstruction error
948 References
949 -------
950 .. [38] C. Vincent-Cuaz, T. Vayer, R. Flamary, M. Corneli, N. Courty, Online
951 Graph Dictionary Learning, International Conference on Machine Learning
952 (ICML), 2021.
953 """
954 C0, Y0, Cdict0, Ydict0 = C, Y, Cdict, Ydict
955 nx = get_backend(C0, Y0, Cdict0, Ydict0)
956 C = nx.to_numpy(C0)
957 Y = nx.to_numpy(Y0)
958 Cdict = nx.to_numpy(Cdict0)
959 Ydict = nx.to_numpy(Ydict0)
960
961 if p is None:
962 p = unif(C.shape[0])
963 else:
964 p = nx.to_numpy(p)
965 if q is None:
966 q = unif(Cdict.shape[-1])
967 else:
968 q = nx.to_numpy(q)
969
970 T = p[:, None] * q[None, :]
971 D = len(Cdict)
972 d = Y.shape[-1]
973 w = unif(D) # Initialize with uniform weights
974 ns = C.shape[-1]
975 nt = Cdict.shape[-1]
976
977 # modeling (C,Y)
978 Cembedded = np.sum(w[:, None, None] * Cdict, axis=0)
979 Yembedded = np.sum(w[:, None, None] * Ydict, axis=0)
980
981 # constants depending on q
982 const_q = q[:, None] * q[None, :]
983 diag_q = np.diag(q)
984 # Trackers for BCD convergence
985 convergence_criterion = np.inf
986 current_loss = 10**15
987 outer_count = 0
988 Ys_constM = (Y**2).dot(
989 np.ones((d, nt))
990 ) # constant in computing euclidean pairwise feature matrix
991
992 while (convergence_criterion > tol_outer) and (outer_count < max_iter_outer):
993 previous_loss = current_loss
994
995 # 1. Solve GW transport between (C,p) and (\sum_d Cdictionary[d],q) fixing the unmixing w
996 Yt_varM = (np.ones((ns, d))).dot((Yembedded**2).T)
997 M = (
998 Ys_constM + Yt_varM - 2 * Y.dot(Yembedded.T)
999 ) # euclidean distance matrix between features
1000 T, log = fused_gromov_wasserstein(
1001 M,
1002 C,
1003 Cembedded,
1004 p,
1005 q,
1006 loss_fun="square_loss",
1007 alpha=alpha,
1008 max_iter=max_iter_inner,
1009 tol_rel=tol_inner,
1010 tol_abs=0.0,
1011 armijo=False,
1012 G0=T,
1013 log=True,
1014 symmetric=symmetric,
1015 **kwargs,
1016 )
1017 current_loss = log["fgw_dist"]
1018 if reg != 0:
1019 current_loss -= reg * np.sum(w**2)
1020
1021 # 2. Solve linear unmixing problem over w with a fixed transport plan T
1022 w, Cembedded, Yembedded, current_loss = _cg_fused_gromov_wasserstein_unmixing(
1023 C,
1024 Y,
1025 Cdict,
1026 Ydict,
1027 Cembedded,
1028 Yembedded,
1029 w,
1030 T,
1031 p,
1032 q,
1033 const_q,
1034 diag_q,
1035 current_loss,
1036 alpha,
1037 reg,
1038 tol=tol_inner,
1039 max_iter=max_iter_inner,
1040 **kwargs,
1041 )
1042 if previous_loss != 0:
1043 convergence_criterion = abs(previous_loss - current_loss) / abs(
1044 previous_loss
1045 )
1046 else:
1047 convergence_criterion = abs(previous_loss - current_loss) / 10 ** (-12)
1048 outer_count += 1
1049
1050 return (
1051 nx.from_numpy(w),
1052 nx.from_numpy(Cembedded),
1053 nx.from_numpy(Yembedded),
1054 nx.from_numpy(T),
1055 nx.from_numpy(current_loss),
1056 )
1057
1058
1059 def _cg_fused_gromov_wasserstein_unmixing(
1060 C,
1061 Y,
1062 Cdict,
1063 Ydict,
1064 Cembedded,
1065 Yembedded,
1066 w,
1067 T,
1068 p,
1069 q,
1070 const_q,
1071 diag_q,
1072 starting_loss,
1073 alpha,
1074 reg,
1075 tol=10 ** (-6),
1076 max_iter=200,
1077 **kwargs,
1078 ):
1079 r"""
1080 Returns for a fixed admissible transport plan,
1081 the optimal linear unmixing :math:`\mathbf{w}` minimizing the Fused Gromov-Wasserstein cost between :math:`(\mathbf{C},\mathbf{Y},\mathbf{p})` and :math:`(\sum_d w_d \mathbf{C_{dict}[d]},\sum_d w_d*\mathbf{Y_{dict}[d]}, \mathbf{q})`
1082
1083 .. math::
1084 \min_{\mathbf{w}} \alpha \sum_{ijkl} (C_{i,j} - \sum_{d=1}^D w_d C_{dict}[d]_{k,l} )^2 T_{i,k}T_{j,l} \\+ (1-\alpha) \sum_{ij} \| \mathbf{Y_i} - \sum_d w_d \mathbf{Y_{dict}[d]_j} \|_2^2 T_{ij}- reg \| \mathbf{w} \|_2^2
1085
1086 Such that :
1087
1088 - :math:`\mathbf{w}^\top \mathbf{1}_D = 1`
1089 - :math:`\mathbf{w} \geq \mathbf{0}_D`
1090
1091 Where :
1092
1093 - :math:`\mathbf{C}` is a (ns,ns) pairwise similarity matrix of variable size ns.
1094 - :math:`\mathbf{Y}` is a (ns,d) features matrix of variable size ns and fixed dimension d.
1095 - :math:`\mathbf{C_{dict}}` is a (D, nt, nt) tensor of D pairwise similarity matrix of fixed size nt.
1096 - :math:`\mathbf{Y_{dict}}` is a (D, nt, d) tensor of D features matrix of fixed size nt and fixed dimension d.
1097 - :math:`\mathbf{p}` is the source distribution corresponding to :math:`\mathbf{C_s}`
1098 - :math:`\mathbf{q}` is the target distribution assigned to every structures in the embedding space.
1099 - :math:`\mathbf{T}` is the optimal transport plan conditioned by the previous state of :math:`\mathbf{w}`
1100 - :math:`\alpha` is the trade-off parameter of Fused Gromov-Wasserstein
1101 - reg is the regularization coefficient.
1102
1103 The algorithm used for solving the problem is a Conditional Gradient Descent as discussed in [38]_, algorithm 7.
1104
1105 Parameters
1106 ----------
1107
1108 C : array-like, shape (ns, ns)
1109 Metric/Graph cost matrix.
1110 Y : array-like, shape (ns, d)
1111 Feature matrix.
1112 Cdict : list of D array-like, shape (nt,nt)
1113 Metric/Graph cost matrices composing the dictionary on which to embed (C,Y).
1114 Each matrix in the dictionary must have the same size (nt,nt).
1115 Ydict : list of D array-like, shape (nt,d)
1116 Feature matrices composing the dictionary on which to embed (C,Y).
1117 Each matrix in the dictionary must have the same size (nt,d).
1118 Cembedded: array-like, shape (nt,nt)
1119 Embedded structure of (C,Y) onto the dictionary
1120 Yembedded: array-like, shape (nt,d)
1121 Embedded features of (C,Y) onto the dictionary
1122 w: array-like, shape (n_D,)
1123 Linear unmixing of (C,Y) onto (Cdict,Ydict)
1124 const_q: array-like, shape (nt,nt)
1125 product matrix :math:`\mathbf{qq}^\top` where :math:`\mathbf{q}` is the target space distribution.
1126 diag_q: array-like, shape (nt,nt)
1127 diagonal matrix with values of q on the diagonal.
1128 T: array-like, shape (ns,nt)
1129 fixed transport plan between (C,Y) and its model
1130 p : array-like, shape (ns,)
1131 Distribution in the source space (C,Y).
1132 q : array-like, shape (nt,)
1133 Distribution in the embedding space depicted by the dictionary.
1134 alpha: float,
1135 Trade-off parameter of Fused Gromov-Wasserstein.
1136 reg : float, optional
1137 Coefficient of the negative quadratic regularization used to promote sparsity of w.
1138
1139 Returns
1140 -------
1141 w: ndarray (D,)
1142 linear unmixing of :math:`(\mathbf{C},\mathbf{Y},\mathbf{p})` onto the span of :math:`(C_{dict},Y_{dict})` given OT corresponding to previous unmixing.
1143 """
1144 convergence_criterion = np.inf
1145 current_loss = starting_loss
1146 count = 0
1147 const_TCT = np.transpose(C.dot(T)).dot(T)
1148 ones_ns_d = np.ones(Y.shape)
1149
1150 while (convergence_criterion > tol) and (count < max_iter):
1151 previous_loss = current_loss
1152
1153 # 1) Compute gradient at current point w
1154 # structure
1155 grad_w = alpha * np.sum(
1156 Cdict
1157 * (Cembedded[None, :, :] * const_q[None, :, :] - const_TCT[None, :, :]),
1158 axis=(1, 2),
1159 )
1160 # feature
1161 grad_w += (1 - alpha) * np.sum(
1162 Ydict * (diag_q.dot(Yembedded)[None, :, :] - T.T.dot(Y)[None, :, :]),
1163 axis=(1, 2),
1164 )
1165 grad_w -= reg * w
1166 grad_w *= 2
1167
1168 # 2) Conditional gradient direction finding: x= \argmin_x x^T.grad_w
1169 min_ = np.min(grad_w)
1170 x = (grad_w == min_).astype(np.float64)
1171 x /= np.sum(x)
1172
1173 # 3) Line-search step: solve \argmin_{\gamma \in [0,1]} a*gamma^2 + b*gamma + c
1174 gamma, a, b, Cembedded_diff, Yembedded_diff = (
1175 _linesearch_fused_gromov_wasserstein_unmixing(
1176 w,
1177 grad_w,
1178 x,
1179 Y,
1180 Cdict,
1181 Ydict,
1182 Cembedded,
1183 Yembedded,
1184 T,
1185 const_q,
1186 const_TCT,
1187 ones_ns_d,
1188 alpha,
1189 reg,
1190 )
1191 )
1192
1193 # 4) Updates: w <-- (1-gamma)*w + gamma*x
1194 w += gamma * (x - w)
1195 Cembedded += gamma * Cembedded_diff
1196 Yembedded += gamma * Yembedded_diff
1197 current_loss += a * (gamma**2) + b * gamma
1198
1199 if previous_loss != 0:
1200 convergence_criterion = abs(previous_loss - current_loss) / abs(
1201 previous_loss
1202 )
1203 else:
1204 convergence_criterion = abs(previous_loss - current_loss) / 10 ** (-12)
1205 count += 1
1206
1207 return w, Cembedded, Yembedded, current_loss
1208
1209
1210 def _linesearch_fused_gromov_wasserstein_unmixing(
1211 w,
1212 grad_w,
1213 x,
1214 Y,
1215 Cdict,
1216 Ydict,
1217 Cembedded,
1218 Yembedded,
1219 T,
1220 const_q,
1221 const_TCT,
1222 ones_ns_d,
1223 alpha,
1224 reg,
1225 **kwargs,
1226 ):
1227 r"""
1228 Compute optimal steps for the line search problem of Fused Gromov-Wasserstein linear unmixing
1229 .. math::
1230 \min_{\gamma \in [0,1]} \alpha \sum_{ijkl} (C_{i,j} - \sum_{d=1}^D z_d(\gamma)C_{dict}[d]_{k,l} )^2 T_{i,k}T_{j,l} \\ + (1-\alpha) \sum_{ij} \| \mathbf{Y_i} - \sum_d z_d(\gamma) \mathbf{Y_{dict}[d]_j} \|_2^2 - reg\| \mathbf{z}(\gamma) \|_2^2
1231
1232
1233 Such that :
1234
1235 - :math:`\mathbf{z}(\gamma) = (1- \gamma)\mathbf{w} + \gamma \mathbf{x}`
1236
1237 Parameters
1238 ----------
1239
1240 w : array-like, shape (D,)
1241 Unmixing.
1242 grad_w : array-like, shape (D, D)
1243 Gradient of the reconstruction loss with respect to w.
1244 x: array-like, shape (D,)
1245 Conditional gradient direction.
1246 Y: arrat-like, shape (ns,d)
1247 Feature matrix of the input space
1248 Cdict : list of D array-like, shape (nt, nt)
1249 Metric/Graph cost matrices composing the dictionary on which to embed (C,Y).
1250 Each matrix in the dictionary must have the same size (nt,nt).
1251 Ydict : list of D array-like, shape (nt, d)
1252 Feature matrices composing the dictionary on which to embed (C,Y).
1253 Each matrix in the dictionary must have the same size (nt,d).
1254 Cembedded: array-like, shape (nt, nt)
1255 Embedded structure of (C,Y) onto the dictionary
1256 Yembedded: array-like, shape (nt, d)
1257 Embedded features of (C,Y) onto the dictionary
1258 T: array-like, shape (ns, nt)
1259 Fixed transport plan between (C,Y) and its current model.
1260 const_q: array-like, shape (nt,nt)
1261 product matrix :math:`\mathbf{q}\mathbf{q}^\top` where q is the target space distribution. Used to avoid redundant computations.
1262 const_TCT: array-like, shape (nt, nt)
1263 :math:`\mathbf{T}^\top \mathbf{C}^\top \mathbf{T}`. Used to avoid redundant computations.
1264 ones_ns_d: array-like, shape (ns, d)
1265 :math:`\mathbf{1}_{ ns \times d}`. Used to avoid redundant computations.
1266 alpha: float,
1267 Trade-off parameter of Fused Gromov-Wasserstein.
1268 reg : float, optional
1269 Coefficient of the negative quadratic regularization used to promote sparsity of w.
1270
1271 Returns
1272 -------
1273 gamma: float
1274 Optimal value for the line-search step
1275 a: float
1276 Constant factor appearing in the factorization :math:`a \gamma^2 + b \gamma +c` of the reconstruction loss
1277 b: float
1278 Constant factor appearing in the factorization :math:`a \gamma^2 + b \gamma +c` of the reconstruction loss
1279 Cembedded_diff: numpy array, shape (nt, nt)
1280 Difference between structure matrix of models evaluated in :math:`\mathbf{w}` and in :math:`\mathbf{w}`.
1281 Yembedded_diff: numpy array, shape (nt, nt)
1282 Difference between feature matrix of models evaluated in :math:`\mathbf{w}` and in :math:`\mathbf{w}`.
1283 """
1284 # polynomial coefficients from quadratic objective (with respect to w) on structures
1285 Cembedded_x = np.sum(x[:, None, None] * Cdict, axis=0)
1286 Cembedded_diff = Cembedded_x - Cembedded
1287 trace_diffx = np.sum(Cembedded_diff * Cembedded_x * const_q)
1288 trace_diffw = np.sum(Cembedded_diff * Cembedded * const_q)
1289 # Constant factor appearing in the factorization a*gamma^2 + b*g + c of the Gromov-Wasserstein reconstruction loss
1290 a_gw = trace_diffx - trace_diffw
1291 b_gw = 2 * (trace_diffw - np.sum(Cembedded_diff * const_TCT))
1292
1293 # polynomial coefficient from quadratic objective (with respect to w) on features
1294 Yembedded_x = np.sum(x[:, None, None] * Ydict, axis=0)
1295 Yembedded_diff = Yembedded_x - Yembedded
1296 # Constant factor appearing in the factorization a*gamma^2 + b*g + c of the Gromov-Wasserstein reconstruction loss
1297 a_w = np.sum(ones_ns_d.dot((Yembedded_diff**2).T) * T)
1298 b_w = 2 * np.sum(
1299 T * (ones_ns_d.dot((Yembedded * Yembedded_diff).T) - Y.dot(Yembedded_diff.T))
1300 )
1301
1302 a = alpha * a_gw + (1 - alpha) * a_w
1303 b = alpha * b_gw + (1 - alpha) * b_w
1304 if reg != 0:
1305 a -= reg * np.sum((x - w) ** 2)
1306 b -= 2 * reg * np.sum(w * (x - w))
1307 if a > 0:
1308 gamma = min(1, max(0, -b / (2 * a)))
1309 elif a + b < 0:
1310 gamma = 1
1311 else:
1312 gamma = 0
1313
1314 return gamma, a, b, Cembedded_diff, Yembedded_diff