Debian Codegraph @

ot/gromov/_partial.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Partial (Fused) Gromov-Wasserstein solvers.
4 """
5
6 # Author: Laetitia Chapel <[email protected]>
7 # Cédric Vincent-Cuaz <[email protected]>
8 # Yikun Bai < [email protected] >
9 #
10 # License: MIT License
11
12 from ..utils import list_to_array, unif
13 from ..backend import get_backend, NumpyBackend
14 from ..partial import entropic_partial_wasserstein
15 from ._utils import _transform_matrix, gwloss, gwggrad
16 from ..optim import partial_cg, solve_1d_linesearch_quad
17
18 import numpy as np
19 import warnings
20
21
22 def partial_gromov_wasserstein(
23 C1,
24 C2,
25 p=None,
26 q=None,
27 m=None,
28 loss_fun="square_loss",
29 nb_dummies=1,
30 G0=None,
31 thres=1,
32 numItermax=1e4,
33 tol=1e-8,
34 symmetric=None,
35 warn=True,
36 log=False,
37 verbose=False,
38 **kwargs,
39 ):
40 r"""
41 Returns the Partial Gromov-Wasserstein transport between :math:`(\mathbf{C_1}, \mathbf{p})`
42 and :math:`(\mathbf{C_2}, \mathbf{q})`.
43
44 The function solves the following optimization problem using Conditional Gradient:
45
46 .. math::
47 \mathbf{T}^* \in \mathop{\arg \min}_\mathbf{T} \quad \sum_{i,j,k,l}
48 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
49
50 s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p}
51
52 \mathbf{T}^T \mathbf{1} &= \mathbf{q}
53
54 \mathbf{T} &\geq 0
55
56 \mathbf{1}^T \mathbf{T}^T \mathbf{1} = m &\leq \min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}
57
58 where :
59
60 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space.
61 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space.
62 - :math:`\mathbf{p}`: Distribution in the source space.
63 - :math:`\mathbf{q}`: Distribution in the target space.
64 - `m` is the amount of mass to be transported
65 - `L`: Loss function to account for the misfit between the similarity matrices.
66
67 The formulation of the problem has been proposed in
68 :ref:`[29] <references-partial-gromov-wasserstein>`
69
70 .. note:: This function is backend-compatible and will work on arrays
71 from all compatible backends. But the algorithm uses the C++ CPU backend
72 which can lead to copy overhead on GPU arrays.
73 .. note:: All computations in the conjugate gradient solver are done with
74 numpy to limit memory overhead.
75 .. note:: This function will cast the computed transport plan to the data
76 type of the provided input :math:`\mathbf{C}_1`. Casting to an integer
77 tensor might result in a loss of precision. If this behaviour is
78 unwanted, please make sure to provide a floating point input.
79
80 Parameters
81 ----------
82 C1 : array-like, shape (ns, ns)
83 Metric cost matrix in the source space
84 C2 : array-like, shape (nt, nt)
85 Metric costfr matrix in the target space
86 p : array-like, shape (ns,), optional
87 Distribution in the source space.
88 If let to its default value None, uniform distribution is taken.
89 q : array-like, shape (nt,), optional
90 Distribution in the target space.
91 If let to its default value None, uniform distribution is taken.
92 m : float, optional
93 Amount of mass to be transported
94 (default: :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
95 loss_fun : str, optional
96 Loss function used for the solver either 'square_loss' or 'kl_loss'.
97 nb_dummies : int, optional
98 Number of dummy points to add (avoid instabilities in the EMD solver)
99 G0 : array-like, shape (ns, nt), optional
100 Initialization of the transportation matrix
101 thres : float, optional
102 quantile of the gradient matrix to populate the cost matrix when 0
103 (default: 1)
104 numItermax : int, optional
105 Max number of iterations
106 tol : float, optional
107 tolerance for stopping iterations
108 symmetric : bool, optional
109 Either C1 and C2 are to be assumed symmetric or not.
110 If let to its default None value, a symmetry test will be conducted.
111 Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric).
112 warn: bool, optional.
113 Whether to raise a warning when EMD did not converge.
114 log : bool, optional
115 return log if True
116 verbose : bool, optional
117 Print information along iterations
118 **kwargs : dict
119 parameters can be directly passed to the emd solver
120
121
122 Returns
123 -------
124 T : array-like, shape (`ns`, `nt`)
125 Optimal transport matrix between the two spaces.
126
127 log : dict
128 Convergence information and loss.
129
130 Examples
131 --------
132 >>> from ot.gromov import partial_gromov_wasserstein
133 >>> import scipy as sp
134 >>> a = np.array([0.25] * 4)
135 >>> b = np.array([0.25] * 4)
136 >>> x = np.array([1,2,100,200]).reshape((-1,1))
137 >>> y = np.array([3,2,98,199]).reshape((-1,1))
138 >>> C1 = sp.spatial.distance.cdist(x, x)
139 >>> C2 = sp.spatial.distance.cdist(y, y)
140 >>> np.round(partial_gromov_wasserstein(C1, C2, a, b),2)
141 array([[0. , 0.25, 0. , 0. ],
142 [0.25, 0. , 0. , 0. ],
143 [0. , 0. , 0.25, 0. ],
144 [0. , 0. , 0. , 0.25]])
145 >>> np.round(partial_gromov_wasserstein(C1, C2, a, b, m=0.25),2)
146 array([[0. , 0. , 0. , 0. ],
147 [0. , 0. , 0. , 0. ],
148 [0. , 0. , 0.25, 0. ],
149 [0. , 0. , 0. , 0. ]])
150
151
152 .. _references-partial-gromov-wasserstein:
153 References
154 ----------
155 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
156 Transport with Applications on Positive-Unlabeled Learning".
157 NeurIPS.
158
159 """
160 arr = [C1, C2]
161 if p is not None:
162 arr.append(list_to_array(p))
163 else:
164 p = unif(C1.shape[0], type_as=C1)
165 if q is not None:
166 arr.append(list_to_array(q))
167 else:
168 q = unif(C2.shape[0], type_as=C1)
169 if G0 is not None:
170 G0_ = G0
171 arr.append(G0)
172
173 nx = get_backend(*arr)
174 p0, q0, C10, C20 = p, q, C1, C2
175
176 p = nx.to_numpy(p0)
177 q = nx.to_numpy(q0)
178 C1 = nx.to_numpy(C10)
179 C2 = nx.to_numpy(C20)
180 if symmetric is None:
181 symmetric = np.allclose(C1, C1.T, atol=1e-10) and np.allclose(
182 C2, C2.T, atol=1e-10
183 )
184
185 if m is None:
186 m = min(np.sum(p), np.sum(q))
187 elif m < 0:
188 raise ValueError("Problem infeasible. Parameter m should be greater" " than 0.")
189 elif m > min(np.sum(p), np.sum(q)):
190 raise ValueError(
191 "Problem infeasible. Parameter m should lower or"
192 " equal than min(|a|_1, |b|_1)."
193 )
194
195 if G0 is None:
196 G0 = (
197 np.outer(p, q) * m / (np.sum(p) * np.sum(q))
198 ) # make sure |G0|=m, G01_m\leq p, G0.T1_n\leq q.
199
200 else:
201 G0 = nx.to_numpy(G0_)
202 # Check marginals of G0
203 assert np.all(G0.sum(1) <= p)
204 assert np.all(G0.sum(0) <= q)
205
206 q_extended = np.append(q, [(np.sum(p) - m) / nb_dummies] * nb_dummies)
207 p_extended = np.append(p, [(np.sum(q) - m) / nb_dummies] * nb_dummies)
208
209 # cg for GW is implemented using numpy on CPU
210 np_ = NumpyBackend()
211
212 fC1, fC2, hC1, hC2 = _transform_matrix(C1, C2, loss_fun, np_)
213 fC2t = fC2.T
214 if not symmetric:
215 fC1t, hC1t, hC2t = fC1.T, hC1.T, hC2.T
216
217 ones_p = np_.ones(p.shape[0], type_as=p)
218 ones_q = np_.ones(q.shape[0], type_as=q)
219
220 def f(G):
221 pG = G.sum(1)
222 qG = G.sum(0)
223 constC1 = np.outer(np.dot(fC1, pG), ones_q)
224 constC2 = np.outer(ones_p, np.dot(qG, fC2t))
225 return gwloss(constC1 + constC2, hC1, hC2, G, np_)
226
227 if symmetric:
228
229 def df(G):
230 pG = G.sum(1)
231 qG = G.sum(0)
232 constC1 = np.outer(np.dot(fC1, pG), ones_q)
233 constC2 = np.outer(ones_p, np.dot(qG, fC2t))
234 return gwggrad(constC1 + constC2, hC1, hC2, G, np_)
235 else:
236
237 def df(G):
238 pG = G.sum(1)
239 qG = G.sum(0)
240 constC1 = np.outer(np.dot(fC1, pG), ones_q)
241 constC2 = np.outer(ones_p, np.dot(qG, fC2t))
242 constC1t = np.outer(np.dot(fC1t, pG), ones_q)
243 constC2t = np.outer(ones_p, np.dot(qG, fC2))
244
245 return 0.5 * (
246 gwggrad(constC1 + constC2, hC1, hC2, G, np_)
247 + gwggrad(constC1t + constC2t, hC1t, hC2t, G, np_)
248 )
249
250 def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs):
251 df_Gc = df(deltaG + G)
252 return solve_partial_gromov_linesearch(
253 G, deltaG, cost_G, df_G, df_Gc, M=0.0, reg=1.0, nx=np_, **kwargs
254 )
255
256 if not nx.is_floating_point(C10):
257 warnings.warn(
258 "Input structure matrix consists of integers. The transport plan will be "
259 "casted accordingly, possibly resulting in a loss of precision. "
260 "If this behaviour is unwanted, please make sure your input "
261 "structure matrix consists of floating point elements.",
262 stacklevel=2,
263 )
264
265 if log:
266 res, log = partial_cg(
267 p,
268 q,
269 p_extended,
270 q_extended,
271 0.0,
272 1.0,
273 f,
274 df,
275 G0,
276 line_search,
277 log=True,
278 numItermax=numItermax,
279 stopThr=tol,
280 stopThr2=0.0,
281 warn=warn,
282 **kwargs,
283 )
284 log["partial_gw_dist"] = nx.from_numpy(log["loss"][-1], type_as=C10)
285 return nx.from_numpy(res, type_as=C10), log
286 else:
287 return nx.from_numpy(
288 partial_cg(
289 p,
290 q,
291 p_extended,
292 q_extended,
293 0.0,
294 1.0,
295 f,
296 df,
297 G0,
298 line_search,
299 log=False,
300 numItermax=numItermax,
301 stopThr=tol,
302 stopThr2=0.0,
303 **kwargs,
304 ),
305 type_as=C10,
306 )
307
308
309 def partial_gromov_wasserstein2(
310 C1,
311 C2,
312 p=None,
313 q=None,
314 m=None,
315 loss_fun="square_loss",
316 nb_dummies=1,
317 G0=None,
318 thres=1,
319 numItermax=1e4,
320 tol=1e-7,
321 symmetric=None,
322 warn=False,
323 log=False,
324 verbose=False,
325 **kwargs,
326 ):
327 r"""
328 Returns the Partial Gromov-Wasserstein discrepancy between
329 :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`.
330
331 The function solves the following optimization problem using Conditional Gradient:
332
333 .. math::
334 \mathbf{PGW} = \mathop{\min}_\mathbf{T} \quad \sum_{i,j,k,l}
335 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
336
337 s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p}
338
339 \mathbf{T}^T \mathbf{1} &= \mathbf{q}
340
341 \mathbf{T} &\geq 0
342
343 \mathbf{1}^T \mathbf{T}^T \mathbf{1} = m &\leq \min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}
344
345 where :
346
347 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space.
348 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space.
349 - :math:`\mathbf{p}`: Distribution in the source space.
350 - :math:`\mathbf{q}`: Distribution in the target space.
351 - `m` is the amount of mass to be transported
352 - `L`: Loss function to account for the misfit between the similarity matrices.
353
354
355 The formulation of the problem has been proposed in
356 :ref:`[29] <references-partial-gromov-wasserstein2>`
357
358 Note that when using backends, this loss function is differentiable wrt the
359 matrices (C1, C2).
360
361 .. note:: This function is backend-compatible and will work on arrays
362 from all compatible backends. But the algorithm uses the C++ CPU backend
363 which can lead to copy overhead on GPU arrays.
364 .. note:: All computations in the conjugate gradient solver are done with
365 numpy to limit memory overhead.
366 .. note:: This function will cast the computed transport plan to the data
367 type of the provided input :math:`\mathbf{C}_1`. Casting to an integer
368 tensor might result in a loss of precision. If this behaviour is
369 unwanted, please make sure to provide a floating point input.
370
371 Parameters
372 ----------
373 C1 : ndarray, shape (ns, ns)
374 Metric cost matrix in the source space
375 C2 : ndarray, shape (nt, nt)
376 Metric cost matrix in the target space
377 p : ndarray, shape (ns,)
378 Distribution in the source space
379 q : ndarray, shape (nt,)
380 Distribution in the target space
381 m : float, optional
382 Amount of mass to be transported
383 (default: :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
384 loss_fun : str, optional
385 Loss function used for the solver either 'square_loss' or 'kl_loss'.
386 nb_dummies : int, optional
387 Number of dummy points to add (avoid instabilities in the EMD solver)
388 G0 : ndarray, shape (ns, nt), optional
389 Initialization of the transportation matrix
390 thres : float, optional
391 quantile of the gradient matrix to populate the cost matrix when 0
392 (default: 1)
393 numItermax : int, optional
394 Max number of iterations
395 tol : float, optional
396 tolerance for stopping iterations
397 symmetric : bool, optional
398 Either C1 and C2 are to be assumed symmetric or not.
399 If let to its default None value, a symmetry test will be conducted.
400 Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric).
401 warn: bool, optional.
402 Whether to raise a warning when EMD did not converge.
403 log : bool, optional
404 return log if True
405 verbose : bool, optional
406 Print information along iterations
407 **kwargs : dict
408 parameters can be directly passed to the emd solver
409
410
411 .. warning::
412 When dealing with a large number of points, the EMD solver may face
413 some instabilities, especially when the mass associated to the dummy
414 point is large. To avoid them, increase the number of dummy points
415 (allows a smoother repartition of the mass over the points).
416
417
418 Returns
419 -------
420 partial_gw_dist : float
421 partial GW discrepancy
422 log : dict
423 log dictionary returned only if `log` is `True`
424
425
426 Examples
427 --------
428 >>> from ot.gromov import partial_gromov_wasserstein2
429 >>> import scipy as sp
430 >>> a = np.array([0.25] * 4)
431 >>> b = np.array([0.25] * 4)
432 >>> x = np.array([1,2,100,200]).reshape((-1,1))
433 >>> y = np.array([3,2,98,199]).reshape((-1,1))
434 >>> C1 = sp.spatial.distance.cdist(x, x)
435 >>> C2 = sp.spatial.distance.cdist(y, y)
436 >>> np.round(partial_gromov_wasserstein2(C1, C2, a, b),2)
437 3.38
438 >>> np.round(partial_gromov_wasserstein2(C1, C2, a, b, m=0.25),2)
439 0.0
440
441
442 .. _references-partial-gromov-wasserstein2:
443 References
444 ----------
445 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
446 Transport with Applications on Positive-Unlabeled Learning".
447 NeurIPS.
448
449 """
450 # simple get_backend as the full one will be handled in gromov_wasserstein
451 nx = get_backend(C1, C2)
452
453 # init marginals if set as None
454 if p is None:
455 p = unif(C1.shape[0], type_as=C1)
456 if q is None:
457 q = unif(C2.shape[0], type_as=C1)
458
459 T, log_pgw = partial_gromov_wasserstein(
460 C1,
461 C2,
462 p,
463 q,
464 m,
465 loss_fun,
466 nb_dummies,
467 G0,
468 thres,
469 numItermax,
470 tol,
471 symmetric,
472 warn,
473 True,
474 verbose,
475 **kwargs,
476 )
477
478 log_pgw["T"] = T
479 pgw = log_pgw["partial_gw_dist"]
480
481 if loss_fun == "square_loss":
482 gC1 = 2 * C1 * nx.outer(p, p) - 2 * nx.dot(T, nx.dot(C2, T.T))
483 gC2 = 2 * C2 * nx.outer(q, q) - 2 * nx.dot(T.T, nx.dot(C1, T))
484 elif loss_fun == "kl_loss":
485 gC1 = nx.log(C1 + 1e-15) * nx.outer(p, p) - nx.dot(
486 T, nx.dot(nx.log(C2 + 1e-15), T.T)
487 )
488 gC2 = -nx.dot(T.T, nx.dot(C1, T)) / (C2 + 1e-15) + nx.outer(q, q)
489
490 pgw = nx.set_gradients(pgw, (C1, C2), (gC1, gC2))
491
492 if log:
493 return pgw, log_pgw
494 else:
495 return pgw
496
497
498 def solve_partial_gromov_linesearch(
499 G,
500 deltaG,
501 cost_G,
502 df_G,
503 df_Gc,
504 M,
505 reg,
506 alpha_min=None,
507 alpha_max=None,
508 nx=None,
509 **kwargs,
510 ):
511 """
512 Solve the linesearch in the FW iterations of partial (F)GW following eq.5 of :ref:`[29]`.
513
514 Parameters
515 ----------
516
517 G : array-like, shape(ns,nt)
518 The transport map at a given iteration of the FW
519 deltaG : array-like (ns,nt)
520 Difference between the optimal map `Gc` found by linearization in the
521 FW algorithm and the value at a given iteration
522 cost_G : float
523 Value of the cost at `G`
524 df_G : array-like (ns,nt)
525 Gradient of the GW cost at `G`
526 df_Gc : array-like (ns,nt)
527 Gradient of the GW cost at `Gc`
528 M : array-like (ns,nt)
529 Cost matrix between the features.
530 reg : float
531 Regularization parameter.
532 alpha_min : float, optional
533 Minimum value for alpha
534 alpha_max : float, optional
535 Maximum value for alpha
536 nx : backend, optional
537 If let to its default value None, a backend test will be conducted.
538
539 Returns
540 -------
541 alpha : float
542 The optimal step size of the FW
543 fc : int
544 nb of function call. Useless here
545 cost_G : float
546 The value of the cost for the next iteration
547 df_G : array-like (ns,nt)
548 Updated gradient of the GW cost
549
550 References
551 ----------
552 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
553 Transport with Applications on Positive-Unlabeled Learning".
554 NeurIPS.
555
556 """
557 if nx is None:
558 if isinstance(M, int) or isinstance(M, float):
559 nx = get_backend(G, deltaG, df_G, df_Gc)
560 else:
561 nx = get_backend(G, deltaG, df_G, df_Gc, M)
562
563 df_deltaG = df_Gc - df_G
564 cost_deltaG = 0.5 * nx.sum(df_deltaG * deltaG)
565
566 a = reg * cost_deltaG
567 # formula to check for partial FGW
568 b = nx.sum(M * deltaG) + reg * nx.sum(df_G * deltaG)
569
570 alpha = solve_1d_linesearch_quad(a, b)
571 if alpha_min is not None or alpha_max is not None:
572 alpha = np.clip(alpha, alpha_min, alpha_max)
573
574 # the new cost is deduced from the line search quadratic function
575 cost_G = cost_G + a * (alpha**2) + b * alpha
576
577 # update the gradient for next cg iteration
578 df_G = df_G + alpha * df_deltaG
579 return alpha, 1, cost_G, df_G
580
581
582 def entropic_partial_gromov_wasserstein(
583 C1,
584 C2,
585 p=None,
586 q=None,
587 reg=1.0,
588 m=None,
589 loss_fun="square_loss",
590 G0=None,
591 numItermax=1000,
592 tol=1e-7,
593 symmetric=None,
594 log=False,
595 verbose=False,
596 ):
597 r"""
598 Returns the partial Gromov-Wasserstein transport between
599 :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`
600
601 The function solves the following optimization problem:
602
603 .. math::
604 \gamma = \mathop{\arg \min}_{\gamma} \quad \sum_{i,j,k,l}
605 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l})\cdot
606 \gamma_{i,j}\cdot\gamma_{k,l} + \mathrm{reg} \cdot\Omega(\gamma)
607
608 .. math::
609 s.t. \ \gamma &\geq 0
610
611 \gamma \mathbf{1} &\leq \mathbf{a}
612
613 \gamma^T \mathbf{1} &\leq \mathbf{b}
614
615 \mathbf{1}^T \gamma^T \mathbf{1} = m
616 &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
617
618 where :
619
620 - :math:`\mathbf{C_1}` is the metric cost matrix in the source space
621 - :math:`\mathbf{C_2}` is the metric cost matrix in the target space
622 - :math:`\mathbf{p}` and :math:`\mathbf{q}` are the sample weights
623 - `L`: quadratic loss function
624 - :math:`\Omega` is the entropic regularization term,
625 :math:`\Omega=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
626 - `m` is the amount of mass to be transported
627
628 The formulation of the GW problem has been proposed in
629 :ref:`[12] <references-entropic-partial-gromov-wasserstein>` and the
630 partial GW in :ref:`[29] <references-entropic-partial-gromov-wasserstein>`
631
632 Parameters
633 ----------
634 C1 : array-like, shape (ns, ns)
635 Metric cost matrix in the source space
636 C2 : array-like, shape (nt, nt)
637 Metric cost matrix in the target space
638 p : array-like, shape (ns,), optional
639 Distribution in the source space.
640 If let to its default value None, uniform distribution is taken.
641 q : array-like, shape (nt,), optional
642 Distribution in the target space.
643 If let to its default value None, uniform distribution is taken.
644 reg: float, optional. Default is 1.
645 entropic regularization parameter
646 m : float, optional
647 Amount of mass to be transported (default:
648 :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
649 loss_fun : str, optional
650 Loss function used for the solver either 'square_loss' or 'kl_loss'.
651 G0 : array-like, shape (ns, nt), optional
652 Initialization of the transportation matrix
653 numItermax : int, optional
654 Max number of iterations
655 tol : float, optional
656 Stop threshold on error (>0)
657 symmetric : bool, optional
658 Either C1 and C2 are to be assumed symmetric or not.
659 If let to its default None value, a symmetry test will be conducted.
660 Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric).
661 log : bool, optional
662 return log if True
663 verbose : bool, optional
664 Print information along iterations
665
666 Examples
667 --------
668 >>> from ot.gromov import entropic_partial_gromov_wasserstein
669 >>> import scipy as sp
670 >>> a = np.array([0.25] * 4)
671 >>> b = np.array([0.25] * 4)
672 >>> x = np.array([1,2,100,200]).reshape((-1,1))
673 >>> y = np.array([3,2,98,199]).reshape((-1,1))
674 >>> C1 = sp.spatial.distance.cdist(x, x)
675 >>> C2 = sp.spatial.distance.cdist(y, y)
676 >>> np.round(entropic_partial_gromov_wasserstein(C1, C2, a, b, 1e2), 2)
677 array([[0.12, 0.13, 0. , 0. ],
678 [0.13, 0.12, 0. , 0. ],
679 [0. , 0. , 0.25, 0. ],
680 [0. , 0. , 0. , 0.25]])
681 >>> np.round(entropic_partial_gromov_wasserstein(C1, C2, a, b, 1e2,0.25), 2)
682 array([[0.02, 0.03, 0. , 0.03],
683 [0.03, 0.03, 0. , 0.03],
684 [0. , 0. , 0.03, 0. ],
685 [0.02, 0.02, 0. , 0.03]])
686
687 Returns
688 -------
689 :math: `gamma` : (dim_a, dim_b) ndarray
690 Optimal transportation matrix for the given parameters
691 log : dict
692 log dictionary returned only if `log` is `True`
693
694
695 .. _references-entropic-partial-gromov-wasserstein:
696 References
697 ----------
698 .. [12] Peyré, Gabriel, Marco Cuturi, and Justin Solomon,
699 "Gromov-Wasserstein averaging of kernel and distance matrices."
700 International Conference on Machine Learning (ICML). 2016.
701
702 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
703 Transport with Applications on Positive-Unlabeled Learning".
704 NeurIPS.
705
706 See Also
707 --------
708 ot.partial.partial_gromov_wasserstein: exact Partial Gromov-Wasserstein
709 """
710
711 arr = [C1, C2, G0]
712 if p is not None:
713 p = list_to_array(p)
714 arr.append(p)
715 if q is not None:
716 q = list_to_array(q)
717 arr.append(q)
718
719 nx = get_backend(*arr)
720
721 if p is None:
722 p = nx.ones(C1.shape[0], type_as=C1) / C1.shape[0]
723 if q is None:
724 q = nx.ones(C2.shape[0], type_as=C2) / C2.shape[0]
725
726 if m is None:
727 m = min(nx.sum(p), nx.sum(q))
728 elif m < 0:
729 raise ValueError("Problem infeasible. Parameter m should be greater" " than 0.")
730 elif m > min(nx.sum(p), nx.sum(q)):
731 raise ValueError(
732 "Problem infeasible. Parameter m should lower or"
733 " equal than min(|a|_1, |b|_1)."
734 )
735
736 if G0 is None:
737 G0 = (
738 nx.outer(p, q) * m / (nx.sum(p) * nx.sum(q))
739 ) # make sure |G0|=m, G01_m\leq p, G0.T1_n\leq q.
740
741 else:
742 # Check marginals of G0
743 assert nx.any(nx.sum(G0, 1) <= p)
744 assert nx.any(nx.sum(G0, 0) <= q)
745
746 if symmetric is None:
747 symmetric = np.allclose(C1, C1.T, atol=1e-10) and np.allclose(
748 C2, C2.T, atol=1e-10
749 )
750
751 # Setup gradient computation
752 fC1, fC2, hC1, hC2 = _transform_matrix(C1, C2, loss_fun, nx)
753 fC2t = fC2.T
754 if not symmetric:
755 fC1t, hC1t, hC2t = fC1.T, hC1.T, hC2.T
756
757 ones_p = nx.ones(p.shape[0], type_as=p)
758 ones_q = nx.ones(q.shape[0], type_as=q)
759
760 def f(G):
761 pG = nx.sum(G, 1)
762 qG = nx.sum(G, 0)
763 constC1 = nx.outer(nx.dot(fC1, pG), ones_q)
764 constC2 = nx.outer(ones_p, nx.dot(qG, fC2t))
765 return gwloss(constC1 + constC2, hC1, hC2, G, nx)
766
767 if symmetric:
768
769 def df(G):
770 pG = nx.sum(G, 1)
771 qG = nx.sum(G, 0)
772 constC1 = nx.outer(nx.dot(fC1, pG), ones_q)
773 constC2 = nx.outer(ones_p, nx.dot(qG, fC2t))
774 return gwggrad(constC1 + constC2, hC1, hC2, G, nx)
775 else:
776
777 def df(G):
778 pG = nx.sum(G, 1)
779 qG = nx.sum(G, 0)
780 constC1 = nx.outer(nx.dot(fC1, pG), ones_q)
781 constC2 = nx.outer(ones_p, nx.dot(qG, fC2t))
782 constC1t = nx.outer(nx.dot(fC1t, pG), ones_q)
783 constC2t = nx.outer(ones_p, nx.dot(qG, fC2))
784
785 return 0.5 * (
786 gwggrad(constC1 + constC2, hC1, hC2, G, nx)
787 + gwggrad(constC1t + constC2t, hC1t, hC2t, G, nx)
788 )
789
790 cpt = 0
791 err = 1
792
793 loge = {"err": []}
794
795 while err > tol and cpt < numItermax:
796 Gprev = G0
797 M_entr = df(G0)
798 G0 = entropic_partial_wasserstein(p, q, M_entr, reg, m)
799 if cpt % 10 == 0: # to speed up the computations
800 err = np.linalg.norm(G0 - Gprev)
801 if log:
802 loge["err"].append(err)
803 if verbose:
804 if cpt % 200 == 0:
805 print(
806 "{:5s}|{:12s}|{:12s}".format("It.", "Err", "Loss")
807 + "\n"
808 + "-" * 31
809 )
810 print("{:5d}|{:8e}|{:8e}".format(cpt, err, f(G0)))
811
812 cpt += 1
813
814 if log:
815 loge["partial_gw_dist"] = f(G0)
816 return G0, loge
817 else:
818 return G0
819
820
821 def entropic_partial_gromov_wasserstein2(
822 C1,
823 C2,
824 p=None,
825 q=None,
826 reg=1.0,
827 m=None,
828 loss_fun="square_loss",
829 G0=None,
830 numItermax=1000,
831 tol=1e-7,
832 symmetric=None,
833 log=False,
834 verbose=False,
835 ):
836 r"""
837 Returns the partial Gromov-Wasserstein discrepancy between
838 :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`
839
840 The function solves the following optimization problem:
841
842 .. math::
843 PGW = \min_{\gamma} \quad \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k},
844 \mathbf{C_2}_{j,l})\cdot
845 \gamma_{i,j}\cdot\gamma_{k,l} + \mathrm{reg} \cdot\Omega(\gamma)
846
847 .. math::
848 s.t. \ \gamma &\geq 0
849
850 \gamma \mathbf{1} &\leq \mathbf{a}
851
852 \gamma^T \mathbf{1} &\leq \mathbf{b}
853
854 \mathbf{1}^T \gamma^T \mathbf{1} = m &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
855
856 where :
857
858 - :math:`\mathbf{C_1}` is the metric cost matrix in the source space
859 - :math:`\mathbf{C_2}` is the metric cost matrix in the target space
860 - :math:`\mathbf{p}` and :math:`\mathbf{q}` are the sample weights
861 - `L`: Loss function to account for the misfit between the similarity matrices.
862 - :math:`\Omega` is the entropic regularization term,
863 :math:`\Omega=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
864 - `m` is the amount of mass to be transported
865
866 The formulation of the GW problem has been proposed in
867 :ref:`[12] <references-entropic-partial-gromov-wasserstein2>` and the
868 partial GW in :ref:`[29] <references-entropic-partial-gromov-wasserstein2>`
869
870
871 Parameters
872 ----------
873 C1 : ndarray, shape (ns, ns)
874 Metric cost matrix in the source space
875 C2 : ndarray, shape (nt, nt)
876 Metric cost matrix in the target space
877 p : array-like, shape (ns,), optional
878 Distribution in the source space.
879 If let to its default value None, uniform distribution is taken.
880 q : array-like, shape (nt,), optional
881 Distribution in the target space.
882 If let to its default value None, uniform distribution is taken.
883 reg: float
884 entropic regularization parameter
885 m : float, optional
886 Amount of mass to be transported (default:
887 :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
888 loss_fun : str, optional
889 Loss function used for the solver either 'square_loss' or 'kl_loss'.
890 G0 : ndarray, shape (ns, nt), optional
891 Initialization of the transportation matrix
892 numItermax : int, optional
893 Max number of iterations
894 tol : float, optional
895 Stop threshold on error (>0)
896 symmetric : bool, optional
897 Either C1 and C2 are to be assumed symmetric or not.
898 If let to its default None value, a symmetry test will be conducted.
899 Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric).
900 log : bool, optional
901 return log if True
902 verbose : bool, optional
903 Print information along iterations
904
905
906 Returns
907 -------
908 partial_gw_dist: float
909 Partial Gromov-Wasserstein distance
910 log : dict
911 log dictionary returned only if `log` is `True`
912
913 Examples
914 --------
915 >>> from ot.gromov import entropic_partial_gromov_wasserstein2
916 >>> import scipy as sp
917 >>> a = np.array([0.25] * 4)
918 >>> b = np.array([0.25] * 4)
919 >>> x = np.array([1,2,100,200]).reshape((-1,1))
920 >>> y = np.array([3,2,98,199]).reshape((-1,1))
921 >>> C1 = sp.spatial.distance.cdist(x, x)
922 >>> C2 = sp.spatial.distance.cdist(y, y)
923 >>> np.round(entropic_partial_gromov_wasserstein2(C1, C2, a, b, 1e2), 2)
924 3.75
925
926
927 .. _references-entropic-partial-gromov-wasserstein2:
928 References
929 ----------
930 .. [12] Peyré, Gabriel, Marco Cuturi, and Justin Solomon,
931 "Gromov-Wasserstein averaging of kernel and distance matrices."
932 International Conference on Machine Learning (ICML). 2016.
933
934 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
935 Transport with Applications on Positive-Unlabeled Learning".
936 NeurIPS.
937 """
938
939 partial_gw, log_gw = entropic_partial_gromov_wasserstein(
940 C1, C2, p, q, reg, m, loss_fun, G0, numItermax, tol, symmetric, True, verbose
941 )
942
943 log_gw["T"] = partial_gw
944
945 if log:
946 return log_gw["partial_gw_dist"], log_gw
947 else:
948 return log_gw["partial_gw_dist"]