Debian Codegraph @

ot/partial.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Partial OT solvers
4 """
5
6 # Author: Laetitia Chapel <[email protected]>
7 # Yikun Bai < [email protected] >
8 # Cédric Vincent-Cuaz <[email protected]>
9
10 from .utils import list_to_array
11 from .backend import get_backend
12 from .lp import emd
13 import numpy as np
14 import warnings
15
16 # License: MIT License
17
18
19 def partial_wasserstein_lagrange(
20 a, b, M, reg_m=None, nb_dummies=1, log=False, **kwargs
21 ):
22 r"""
23 Solves the partial optimal transport problem for the quadratic cost
24 and returns the OT plan
25
26 The function considers the following problem:
27
28 .. math::
29 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, (\mathbf{M} - \lambda) \rangle_F
30
31 .. math::
32 s.t. \ \gamma \mathbf{1} &\leq \mathbf{a}
33
34 \gamma^T \mathbf{1} &\leq \mathbf{b}
35
36 \gamma &\geq 0
37
38 \mathbf{1}^T \gamma^T \mathbf{1} = m &
39 \leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
40
41
42 or equivalently (see Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X.
43 (2018). An interpolating distance between optimal transport and Fisher–Rao
44 metrics. Foundations of Computational Mathematics, 18(1), 1-44.)
45
46 .. math::
47 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
48 \sqrt{\frac{\lambda}{2} (\|\gamma \mathbf{1} - \mathbf{a}\|_1 + \|\gamma^T \mathbf{1} - \mathbf{b}\|_1)}
49
50 s.t. \ \gamma \geq 0
51
52
53 where :
54
55 - :math:`\mathbf{M}` is the metric cost matrix
56 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
57 - :math:`\lambda` is the lagrangian cost. Tuning its value allows attaining
58 a given mass to be transported `m`
59
60 The formulation of the problem has been proposed in
61 :ref:`[28] <references-partial-wasserstein-lagrange>`
62
63
64 Parameters
65 ----------
66 a : np.ndarray (dim_a,)
67 Unnormalized histogram of dimension `dim_a`
68 b : np.ndarray (dim_b,)
69 Unnormalized histograms of dimension `dim_b`
70 M : np.ndarray (dim_a, dim_b)
71 cost matrix for the quadratic cost
72 reg_m : float, optional
73 Lagrangian cost
74 nb_dummies : int, optional, default:1
75 number of reservoir points to be added (to avoid numerical
76 instabilities, increase its value if an error is raised)
77 log : bool, optional
78 record log if True
79 **kwargs : dict
80 parameters can be directly passed to the emd solver
81
82
83 .. warning::
84 When dealing with a large number of points, the EMD solver may face
85 some instabilities, especially when the mass associated to the dummy
86 point is large. To avoid them, increase the number of dummy points
87 (allows a smoother repartition of the mass over the points).
88
89 Returns
90 -------
91 gamma : (dim_a, dim_b) ndarray
92 Optimal transportation matrix for the given parameters
93 log : dict
94 log dictionary returned only if `log` is `True`
95
96
97 Examples
98 --------
99
100 >>> import ot
101 >>> a = [.1, .2]
102 >>> b = [.1, .1]
103 >>> M = [[0., 1.], [2., 3.]]
104 >>> np.round(partial_wasserstein_lagrange(a,b,M), 2)
105 array([[0.1, 0. ],
106 [0. , 0.1]])
107 >>> np.round(partial_wasserstein_lagrange(a,b,M,reg_m=2), 2)
108 array([[0.1, 0. ],
109 [0. , 0. ]])
110
111
112 .. _references-partial-wasserstein-lagrange:
113 References
114 ----------
115 .. [28] Caffarelli, L. A., & McCann, R. J. (2010) Free boundaries in
116 optimal transport and Monge-Ampere obstacle problems. Annals of
117 mathematics, 673-730.
118
119 See Also
120 --------
121 ot.partial.partial_wasserstein : Partial Wasserstein with fixed mass
122 """
123
124 a, b, M = list_to_array(a, b, M)
125
126 nx = get_backend(a, b, M)
127
128 if nx.sum(a) > 1 + 1e-15 or nx.sum(b) > 1 + 1e-15: # 1e-15 for numerical errors
129 raise ValueError("Problem infeasible. Check that a and b are in the " "simplex")
130
131 if reg_m is None:
132 reg_m = float(nx.max(M)) + 1
133 if reg_m < -nx.max(M):
134 return nx.zeros((len(a), len(b)), type_as=M)
135
136 a0, b0, M0 = a, b, M
137 # convert to humpy
138 a, b, M = nx.to_numpy(a, b, M)
139
140 eps = 1e-20
141 M = np.asarray(M, dtype=np.float64)
142 b = np.asarray(b, dtype=np.float64)
143 a = np.asarray(a, dtype=np.float64)
144
145 M_star = M - reg_m # modified cost matrix
146
147 # trick to fasten the computation: select only the subset of columns/lines
148 # that can have marginals greater than 0 (that is to say M < 0)
149 idx_x = np.where(np.min(M_star, axis=1) < eps)[0]
150 idx_y = np.where(np.min(M_star, axis=0) < eps)[0]
151
152 # extend a, b, M with "reservoir" or "dummy" points
153 M_extended = np.zeros((len(idx_x) + nb_dummies, len(idx_y) + nb_dummies))
154 M_extended[: len(idx_x), : len(idx_y)] = M_star[np.ix_(idx_x, idx_y)]
155
156 a_extended = np.append(
157 a[idx_x], [(np.sum(a) - np.sum(a[idx_x]) + np.sum(b)) / nb_dummies] * nb_dummies
158 )
159 b_extended = np.append(
160 b[idx_y], [(np.sum(b) - np.sum(b[idx_y]) + np.sum(a)) / nb_dummies] * nb_dummies
161 )
162
163 gamma_extended, log_emd = emd(
164 a_extended, b_extended, M_extended, log=True, **kwargs
165 )
166 gamma = np.zeros((len(a), len(b)))
167 gamma[np.ix_(idx_x, idx_y)] = gamma_extended[:-nb_dummies, :-nb_dummies]
168
169 # convert back to backend
170 gamma = nx.from_numpy(gamma, type_as=M0)
171
172 if log_emd["warning"] is not None:
173 raise ValueError(
174 "Error in the EMD resolution: try to increase the" " number of dummy points"
175 )
176 log_emd["cost"] = nx.sum(gamma * M0)
177 log_emd["u"] = nx.from_numpy(log_emd["u"], type_as=a0)
178 log_emd["v"] = nx.from_numpy(log_emd["v"], type_as=b0)
179
180 if log:
181 return gamma, log_emd
182 else:
183 return gamma
184
185
186 def partial_wasserstein(a, b, M, m=None, nb_dummies=1, log=False, **kwargs):
187 r"""
188 Solves the partial optimal transport problem for the quadratic cost
189 and returns the OT plan
190
191 The function considers the following problem:
192
193 .. math::
194 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F
195
196 .. math::
197 s.t. \ \gamma \mathbf{1} &\leq \mathbf{a}
198
199 \gamma^T \mathbf{1} &\leq \mathbf{b}
200
201 \gamma &\geq 0
202
203 \mathbf{1}^T \gamma^T \mathbf{1} = m &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
204
205
206 where :
207
208 - :math:`\mathbf{M}` is the metric cost matrix
209 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
210 - `m` is the amount of mass to be transported
211
212 Parameters
213 ----------
214 a : np.ndarray (dim_a,)
215 Unnormalized histogram of dimension `dim_a`
216 b : np.ndarray (dim_b,)
217 Unnormalized histograms of dimension `dim_b`
218 M : np.ndarray (dim_a, dim_b)
219 cost matrix for the quadratic cost
220 m : float, optional
221 amount of mass to be transported
222 nb_dummies : int, optional, default:1
223 number of reservoir points to be added (to avoid numerical
224 instabilities, increase its value if an error is raised)
225 log : bool, optional
226 record log if True
227 **kwargs : dict
228 parameters can be directly passed to the emd solver
229
230
231 .. warning::
232 When dealing with a large number of points, the EMD solver may face
233 some instabilities, especially when the mass associated to the dummy
234 point is large. To avoid them, increase the number of dummy points
235 (allows a smoother repartition of the mass over the points).
236
237
238 Returns
239 -------
240 gamma : (dim_a, dim_b) ndarray
241 Optimal transportation matrix for the given parameters
242 log : dict
243 log dictionary returned only if `log` is `True`
244
245
246 Examples
247 --------
248
249 >>> import ot
250 >>> a = [.1, .2]
251 >>> b = [.1, .1]
252 >>> M = [[0., 1.], [2., 3.]]
253 >>> np.round(partial_wasserstein(a,b,M), 2)
254 array([[0.1, 0. ],
255 [0. , 0.1]])
256 >>> np.round(partial_wasserstein(a,b,M,m=0.1), 2)
257 array([[0.1, 0. ],
258 [0. , 0. ]])
259
260 References
261 ----------
262 .. [28] Caffarelli, L. A., & McCann, R. J. (2010) Free boundaries in
263 optimal transport and Monge-Ampere obstacle problems. Annals of
264 mathematics, 673-730.
265 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
266 Transport with Applications on Positive-Unlabeled Learning".
267 NeurIPS.
268
269 See Also
270 --------
271 ot.partial.partial_wasserstein_lagrange: Partial Wasserstein with
272 regularization on the marginals
273 ot.partial.entropic_partial_wasserstein: Partial Wasserstein with a
274 entropic regularization parameter
275 """
276
277 a, b, M = list_to_array(a, b, M)
278
279 nx = get_backend(a, b, M)
280
281 dim_a, dim_b = M.shape
282 if len(a) == 0:
283 a = nx.ones(dim_a, type_as=a) / dim_a
284 if len(b) == 0:
285 b = nx.ones(dim_b, type_as=b) / dim_b
286
287 if m is None:
288 return partial_wasserstein_lagrange(a, b, M, log=log, **kwargs)
289 elif m < 0:
290 raise ValueError("Problem infeasible. Parameter m should be greater" " than 0.")
291 elif m > nx.min(nx.stack((nx.sum(a), nx.sum(b)))):
292 raise ValueError(
293 "Problem infeasible. Parameter m should lower or"
294 " equal than min(|a|_1, |b|_1)."
295 )
296
297 b_extension = nx.ones(nb_dummies, type_as=b) * (nx.sum(a) - m) / nb_dummies
298 b_extended = nx.concatenate((b, b_extension))
299 a_extension = nx.ones(nb_dummies, type_as=a) * (nx.sum(b) - m) / nb_dummies
300 a_extended = nx.concatenate((a, a_extension))
301 M_extension = nx.ones((nb_dummies, nb_dummies), type_as=M) * nx.max(M) * 2
302 M_extended = nx.concatenate(
303 (
304 nx.concatenate((M, nx.zeros((M.shape[0], M_extension.shape[1]))), axis=1),
305 nx.concatenate(
306 (nx.zeros((M_extension.shape[0], M.shape[1])), M_extension), axis=1
307 ),
308 ),
309 axis=0,
310 )
311
312 gamma, log_emd = emd(a_extended, b_extended, M_extended, log=True, **kwargs)
313
314 gamma = gamma[: len(a), : len(b)]
315
316 if log_emd["warning"] is not None:
317 raise ValueError(
318 "Error in the EMD resolution: try to increase the" " number of dummy points"
319 )
320 log_emd["partial_w_dist"] = nx.sum(M * gamma)
321 log_emd["u"] = log_emd["u"][: len(a)]
322 log_emd["v"] = log_emd["v"][: len(b)]
323
324 if log:
325 return gamma, log_emd
326 else:
327 return gamma
328
329
330 def partial_wasserstein2(a, b, M, m=None, nb_dummies=1, log=False, **kwargs):
331 r"""
332 Solves the partial optimal transport problem for the quadratic cost
333 and returns the partial GW discrepancy
334
335 The function considers the following problem:
336
337 .. math::
338 \gamma = \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F
339
340 .. math::
341 s.t. \ \gamma \mathbf{1} &\leq \mathbf{a}
342
343 \gamma^T \mathbf{1} &\leq \mathbf{b}
344
345 \gamma &\geq 0
346
347 \mathbf{1}^T \gamma^T \mathbf{1} = m &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
348
349
350 where :
351
352 - :math:`\mathbf{M}` is the metric cost matrix
353 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
354 - `m` is the amount of mass to be transported
355
356 Parameters
357 ----------
358 a : np.ndarray (dim_a,)
359 Unnormalized histogram of dimension `dim_a`
360 b : np.ndarray (dim_b,)
361 Unnormalized histograms of dimension `dim_b`
362 M : np.ndarray (dim_a, dim_b)
363 cost matrix for the quadratic cost
364 m : float, optional
365 amount of mass to be transported
366 nb_dummies : int, optional, default:1
367 number of reservoir points to be added (to avoid numerical
368 instabilities, increase its value if an error is raised)
369 log : bool, optional
370 record log if True
371 **kwargs : dict
372 parameters can be directly passed to the emd solver
373
374
375 .. warning::
376 When dealing with a large number of points, the EMD solver may face
377 some instabilities, especially when the mass associated to the dummy
378 point is large. To avoid them, increase the number of dummy points
379 (allows a smoother repartition of the mass over the points).
380
381
382 Returns
383 -------
384 GW: float
385 partial GW discrepancy
386 log : dict
387 log dictionary returned only if `log` is `True`
388
389
390 Examples
391 --------
392
393 >>> import ot
394 >>> a=[.1, .2]
395 >>> b=[.1, .1]
396 >>> M=[[0., 1.], [2., 3.]]
397 >>> np.round(partial_wasserstein2(a, b, M), 1)
398 0.3
399 >>> np.round(partial_wasserstein2(a,b,M,m=0.1), 1)
400 0.0
401
402 References
403 ----------
404 .. [28] Caffarelli, L. A., & McCann, R. J. (2010) Free boundaries in
405 optimal transport and Monge-Ampere obstacle problems. Annals of
406 mathematics, 673-730.
407 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
408 Transport with Applications on Positive-Unlabeled Learning".
409 NeurIPS.
410 """
411
412 a, b, M = list_to_array(a, b, M)
413
414 nx = get_backend(a, b, M)
415
416 partial_gw, log_w = partial_wasserstein(a, b, M, m, nb_dummies, log=True, **kwargs)
417 log_w["T"] = partial_gw
418
419 if log:
420 return nx.sum(partial_gw * M), log_w
421 else:
422 return nx.sum(partial_gw * M)
423
424
425 def entropic_partial_wasserstein(
426 a, b, M, reg, m=None, numItermax=1000, stopThr=1e-100, verbose=False, log=False
427 ):
428 r"""
429 Solves the partial optimal transport problem
430 and returns the OT plan
431
432 The function considers the following problem:
433
434 .. math::
435 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma,
436 \mathbf{M} \rangle_F + \mathrm{reg} \cdot\Omega(\gamma)
437
438 s.t. \gamma \mathbf{1} &\leq \mathbf{a} \\
439 \gamma^T \mathbf{1} &\leq \mathbf{b} \\
440 \gamma &\geq 0 \\
441 \mathbf{1}^T \gamma^T \mathbf{1} = m
442 &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\} \\
443
444 where :
445
446 - :math:`\mathbf{M}` is the metric cost matrix
447 - :math:`\Omega` is the entropic regularization term,
448 :math:`\Omega=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
449 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are the sample weights
450 - `m` is the amount of mass to be transported
451
452 The formulation of the problem has been proposed in
453 :ref:`[3] <references-entropic-partial-wasserstein>` (prop. 5)
454
455
456 Parameters
457 ----------
458 a : np.ndarray (dim_a,)
459 Unnormalized histogram of dimension `dim_a`
460 b : np.ndarray (dim_b,)
461 Unnormalized histograms of dimension `dim_b`
462 M : np.ndarray (dim_a, dim_b)
463 cost matrix
464 reg : float
465 Regularization term > 0
466 m : float, optional
467 Amount of mass to be transported
468 numItermax : int, optional
469 Max number of iterations
470 stopThr : float, optional
471 Stop threshold on error (>0)
472 verbose : bool, optional
473 Print information along iterations
474 log : bool, optional
475 record log if True
476
477
478 Returns
479 -------
480 gamma : (dim_a, dim_b) ndarray
481 Optimal transportation matrix for the given parameters
482 log : dict
483 log dictionary returned only if `log` is `True`
484
485
486 Examples
487 --------
488 >>> import ot
489 >>> a = [.1, .2]
490 >>> b = [.1, .1]
491 >>> M = [[0., 1.], [2., 3.]]
492 >>> np.round(entropic_partial_wasserstein(a, b, M, 1, 0.1), 2)
493 array([[0.06, 0.02],
494 [0.01, 0. ]])
495
496
497 .. _references-entropic-partial-wasserstein:
498 References
499 ----------
500 .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G.
501 (2015). Iterative Bregman projections for regularized transportation
502 problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
503
504 See Also
505 --------
506 ot.partial.partial_wasserstein: exact Partial Wasserstein
507 """
508
509 a, b, M = list_to_array(a, b, M)
510
511 nx = get_backend(a, b, M)
512
513 dim_a, dim_b = M.shape
514 dx = nx.ones(dim_a, type_as=a)
515 dy = nx.ones(dim_b, type_as=b)
516
517 if len(a) == 0:
518 a = nx.ones(dim_a, type_as=a) / dim_a
519 if len(b) == 0:
520 b = nx.ones(dim_b, type_as=b) / dim_b
521
522 if m is None:
523 m = nx.min(nx.stack((nx.sum(a), nx.sum(b)))) * 1.0
524 if m < 0:
525 raise ValueError("Problem infeasible. Parameter m should be greater" " than 0.")
526 if m > nx.min(nx.stack((nx.sum(a), nx.sum(b)))):
527 raise ValueError(
528 "Problem infeasible. Parameter m should lower or"
529 " equal than min(|a|_1, |b|_1)."
530 )
531
532 log_e = {"err": []}
533
534 if nx.__name__ == "numpy":
535 # Next 3 lines equivalent to K=nx.exp(-M/reg), but faster to compute
536 K = np.empty(M.shape, dtype=M.dtype)
537 np.divide(M, -reg, out=K)
538 np.exp(K, out=K)
539 np.multiply(K, m / np.sum(K), out=K)
540 else:
541 K = nx.exp(-M / reg)
542 K = K * m / nx.sum(K)
543
544 err, cpt = 1, 0
545 q1 = nx.ones(K.shape, type_as=K)
546 q2 = nx.ones(K.shape, type_as=K)
547 q3 = nx.ones(K.shape, type_as=K)
548
549 while err > stopThr and cpt < numItermax:
550 Kprev = K
551 K = K * q1
552 K1 = nx.dot(nx.diag(nx.minimum(a / nx.sum(K, axis=1), dx)), K)
553 q1 = q1 * Kprev / K1
554 K1prev = K1
555 K1 = K1 * q2
556 K2 = nx.dot(K1, nx.diag(nx.minimum(b / nx.sum(K1, axis=0), dy)))
557 q2 = q2 * K1prev / K2
558 K2prev = K2
559 K2 = K2 * q3
560 K = K2 * (m / nx.sum(K2))
561 q3 = q3 * K2prev / K
562
563 if nx.any(nx.isnan(K)) or nx.any(nx.isinf(K)):
564 print("Warning: numerical errors at iteration", cpt)
565 break
566 if cpt % 10 == 0:
567 err = nx.norm(Kprev - K)
568 if log:
569 log_e["err"].append(err)
570 if verbose:
571 if cpt % 200 == 0:
572 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 11)
573 print("{:5d}|{:8e}|".format(cpt, err))
574
575 cpt = cpt + 1
576 log_e["partial_w_dist"] = nx.sum(M * K)
577 if log:
578 return K, log_e
579 else:
580 return K
581
582
583 def gwgrad_partial(C1, C2, T):
584 """Compute the GW gradient. Note: we can not use the trick in :ref:`[12] <references-gwgrad-partial>`
585 as the marginals may not sum to 1.
586
587 .. note:: This function will be deprecated in a near future, please use
588 `ot.gromov.gwggrad` instead.
589
590 Parameters
591 ----------
592 C1: array of shape (n_p,n_p)
593 intra-source (P) cost matrix
594
595 C2: array of shape (n_u,n_u)
596 intra-target (U) cost matrix
597
598 T : array of shape(n_p+nb_dummies, n_u) (default: None)
599 Transport matrix
600
601 Returns
602 -------
603 numpy.array of shape (n_p+nb_dummies, n_u)
604 gradient
605
606
607 .. _references-gwgrad-partial:
608 References
609 ----------
610 .. [12] Peyré, Gabriel, Marco Cuturi, and Justin Solomon,
611 "Gromov-Wasserstein averaging of kernel and distance matrices."
612 International Conference on Machine Learning (ICML). 2016.
613 """
614 warnings.warn(
615 "This function will be deprecated in a near future, please use "
616 "ot.gromov.gwggrad` instead.",
617 stacklevel=2,
618 )
619 cC1 = np.dot(C1**2 / 2, np.dot(T, np.ones(C2.shape[0]).reshape(-1, 1)))
620 cC2 = np.dot(np.dot(np.ones(C1.shape[0]).reshape(1, -1), T), C2**2 / 2)
621 constC = cC1 + cC2
622 A = -np.dot(C1, T).dot(C2.T)
623 tens = constC + A
624 return tens * 2
625
626
627 def gwloss_partial(C1, C2, T):
628 """Compute the GW loss.
629
630 .. note:: This function will be deprecated in a near future, please use
631 `ot.gromov.gwloss` instead.
632
633 Parameters
634 ----------
635 C1: array of shape (n_p,n_p)
636 intra-source (P) cost matrix
637
638 C2: array of shape (n_u,n_u)
639 intra-target (U) cost matrix
640
641 T : array of shape(n_p+nb_dummies, n_u) (default: None)
642 Transport matrix
643
644 Returns
645 -------
646 GW loss
647 """
648 warnings.warn(
649 "This function will be deprecated in a near future, please use "
650 "ot.gromov.gwloss` instead.",
651 stacklevel=2,
652 )
653
654 g = gwgrad_partial(C1, C2, T) * 0.5
655 return np.sum(g * T)
656
657
658 def partial_gromov_wasserstein(
659 C1,
660 C2,
661 p,
662 q,
663 m=None,
664 nb_dummies=1,
665 G0=None,
666 thres=1,
667 numItermax=1000,
668 tol=1e-7,
669 log=False,
670 verbose=False,
671 **kwargs,
672 ):
673 r"""
674 Solves the partial optimal transport problem
675 and returns the OT plan
676
677 The function considers the following problem:
678
679 .. math::
680 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F
681
682 .. math::
683 s.t. \ \gamma \mathbf{1} &\leq \mathbf{a}
684
685 \gamma^T \mathbf{1} &\leq \mathbf{b}
686
687 \gamma &\geq 0
688
689 \mathbf{1}^T \gamma^T \mathbf{1} = m &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
690
691 where :
692
693 - :math:`\mathbf{M}` is the metric cost matrix
694 - :math:`\Omega` is the entropic regularization term, :math:`\Omega(\gamma) = \sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
695 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are the sample weights
696 - `m` is the amount of mass to be transported
697
698 The formulation of the problem has been proposed in
699 :ref:`[29] <references-partial-gromov-wasserstein>`
700
701 .. note:: This function will be deprecated in a near future, please use
702 `ot.gromov.partial_gromov_wasserstein` instead.
703
704 Parameters
705 ----------
706 C1 : ndarray, shape (ns, ns)
707 Metric cost matrix in the source space
708 C2 : ndarray, shape (nt, nt)
709 Metric costfr matrix in the target space
710 p : ndarray, shape (ns,)
711 Distribution in the source space
712 q : ndarray, shape (nt,)
713 Distribution in the target space
714 m : float, optional
715 Amount of mass to be transported
716 (default: :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
717 nb_dummies : int, optional
718 Number of dummy points to add (avoid instabilities in the EMD solver)
719 G0 : ndarray, shape (ns, nt), optional
720 Initialization of the transportation matrix
721 thres : float, optional
722 quantile of the gradient matrix to populate the cost matrix when 0
723 (default: 1)
724 numItermax : int, optional
725 Max number of iterations
726 tol : float, optional
727 tolerance for stopping iterations
728 log : bool, optional
729 return log if True
730 verbose : bool, optional
731 Print information along iterations
732 **kwargs : dict
733 parameters can be directly passed to the emd solver
734
735
736 Returns
737 -------
738 gamma : (dim_a, dim_b) ndarray
739 Optimal transportation matrix for the given parameters
740 log : dict
741 log dictionary returned only if `log` is `True`
742
743
744 Examples
745 --------
746 >>> import ot
747 >>> import scipy as sp
748 >>> a = np.array([0.25] * 4)
749 >>> b = np.array([0.25] * 4)
750 >>> x = np.array([1,2,100,200]).reshape((-1,1))
751 >>> y = np.array([3,2,98,199]).reshape((-1,1))
752 >>> C1 = sp.spatial.distance.cdist(x, x)
753 >>> C2 = sp.spatial.distance.cdist(y, y)
754 >>> np.round(partial_gromov_wasserstein(C1, C2, a, b),2)
755 array([[0. , 0.25, 0. , 0. ],
756 [0.25, 0. , 0. , 0. ],
757 [0. , 0. , 0.25, 0. ],
758 [0. , 0. , 0. , 0.25]])
759 >>> np.round(partial_gromov_wasserstein(C1, C2, a, b, m=0.25),2)
760 array([[0. , 0. , 0. , 0. ],
761 [0. , 0. , 0. , 0. ],
762 [0. , 0. , 0.25, 0. ],
763 [0. , 0. , 0. , 0. ]])
764
765
766 .. _references-partial-gromov-wasserstein:
767 References
768 ----------
769 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
770 Transport with Applications on Positive-Unlabeled Learning".
771 NeurIPS.
772
773 """
774 warnings.warn(
775 "This function will be deprecated in a near future, please use "
776 "ot.gromov.partial_gromov_wasserstein` instead.",
777 stacklevel=2,
778 )
779
780 if m is None:
781 m = np.min((np.sum(p), np.sum(q)))
782 elif m < 0:
783 raise ValueError("Problem infeasible. Parameter m should be greater" " than 0.")
784 elif m > np.min((np.sum(p), np.sum(q))):
785 raise ValueError(
786 "Problem infeasible. Parameter m should lower or"
787 " equal than min(|a|_1, |b|_1)."
788 )
789
790 if G0 is None:
791 G0 = (
792 np.outer(p, q) * m / (np.sum(p) * np.sum(q))
793 ) # make sure |G0|=m, G01_m\leq p, G0.T1_n\leq q.
794
795 dim_G_extended = (len(p) + nb_dummies, len(q) + nb_dummies)
796 q_extended = np.append(q, [(np.sum(p) - m) / nb_dummies] * nb_dummies)
797 p_extended = np.append(p, [(np.sum(q) - m) / nb_dummies] * nb_dummies)
798
799 cpt = 0
800 err = 1
801
802 if log:
803 log = {"err": []}
804
805 while err > tol and cpt < numItermax:
806 Gprev = np.copy(G0)
807
808 M = 0.5 * gwgrad_partial(
809 C1, C2, G0
810 ) # rescaling the gradient with 0.5 for line-search while not changing Gc
811 M_emd = np.zeros(dim_G_extended)
812 M_emd[: len(p), : len(q)] = M
813 M_emd[-nb_dummies:, -nb_dummies:] = np.max(M) * 1e2
814 M_emd = np.asarray(M_emd, dtype=np.float64)
815
816 Gc, logemd = emd(p_extended, q_extended, M_emd, log=True, **kwargs)
817
818 if logemd["warning"] is not None:
819 raise ValueError(
820 "Error in the EMD resolution: try to increase the"
821 " number of dummy points"
822 )
823
824 G0 = Gc[: len(p), : len(q)]
825
826 if cpt % 10 == 0: # to speed up the computations
827 err = np.linalg.norm(G0 - Gprev)
828 if log:
829 log["err"].append(err)
830 if verbose:
831 if cpt % 200 == 0:
832 print(
833 "{:5s}|{:12s}|{:12s}".format("It.", "Err", "Loss")
834 + "\n"
835 + "-" * 31
836 )
837 print("{:5d}|{:8e}|{:8e}".format(cpt, err, gwloss_partial(C1, C2, G0)))
838
839 deltaG = G0 - Gprev
840 a = gwloss_partial(C1, C2, deltaG)
841 b = 2 * np.sum(M * deltaG)
842 if b > 0: # due to numerical precision
843 gamma = 0
844 cpt = numItermax
845 elif a > 0:
846 gamma = min(1, np.divide(-b, 2.0 * a))
847 else:
848 if (a + b) < 0:
849 gamma = 1
850 else:
851 gamma = 0
852 cpt = numItermax
853
854 G0 = Gprev + gamma * deltaG
855 cpt += 1
856
857 if log:
858 log["partial_gw_dist"] = gwloss_partial(C1, C2, G0)
859 return G0[: len(p), : len(q)], log
860 else:
861 return G0[: len(p), : len(q)]
862
863
864 def partial_gromov_wasserstein2(
865 C1,
866 C2,
867 p,
868 q,
869 m=None,
870 nb_dummies=1,
871 G0=None,
872 thres=1,
873 numItermax=1000,
874 tol=1e-7,
875 log=False,
876 verbose=False,
877 **kwargs,
878 ):
879 r"""
880 Solves the partial optimal transport problem
881 and returns the partial Gromov-Wasserstein discrepancy
882
883 The function considers the following problem:
884
885 .. math::
886 GW = \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F
887
888 .. math::
889 s.t. \ \gamma \mathbf{1} &\leq \mathbf{a}
890
891 \gamma^T \mathbf{1} &\leq \mathbf{b}
892
893 \gamma &\geq 0
894
895 \mathbf{1}^T \gamma^T \mathbf{1} = m
896 &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
897
898 where :
899
900 - :math:`\mathbf{M}` is the metric cost matrix
901 - :math:`\Omega` is the entropic regularization term,
902 :math:`\Omega(\gamma) = \sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
903 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are the sample weights
904 - `m` is the amount of mass to be transported
905
906 The formulation of the problem has been proposed in
907 :ref:`[29] <references-partial-gromov-wasserstein2>`
908
909 .. note:: This function will be deprecated in a near future, please use
910 `ot.gromov.partial_gromov_wasserstein2` instead.
911
912 Parameters
913 ----------
914 C1 : ndarray, shape (ns, ns)
915 Metric cost matrix in the source space
916 C2 : ndarray, shape (nt, nt)
917 Metric cost matrix in the target space
918 p : ndarray, shape (ns,)
919 Distribution in the source space
920 q : ndarray, shape (nt,)
921 Distribution in the target space
922 m : float, optional
923 Amount of mass to be transported
924 (default: :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
925 nb_dummies : int, optional
926 Number of dummy points to add (avoid instabilities in the EMD solver)
927 G0 : ndarray, shape (ns, nt), optional
928 Initialization of the transportation matrix
929 thres : float, optional
930 quantile of the gradient matrix to populate the cost matrix when 0
931 (default: 1)
932 numItermax : int, optional
933 Max number of iterations
934 tol : float, optional
935 tolerance for stopping iterations
936 log : bool, optional
937 return log if True
938 verbose : bool, optional
939 Print information along iterations
940 **kwargs : dict
941 parameters can be directly passed to the emd solver
942
943
944 .. warning::
945 When dealing with a large number of points, the EMD solver may face
946 some instabilities, especially when the mass associated to the dummy
947 point is large. To avoid them, increase the number of dummy points
948 (allows a smoother repartition of the mass over the points).
949
950
951 Returns
952 -------
953 partial_gw_dist : float
954 partial GW discrepancy
955 log : dict
956 log dictionary returned only if `log` is `True`
957
958
959 Examples
960 --------
961 >>> import ot
962 >>> import scipy as sp
963 >>> a = np.array([0.25] * 4)
964 >>> b = np.array([0.25] * 4)
965 >>> x = np.array([1,2,100,200]).reshape((-1,1))
966 >>> y = np.array([3,2,98,199]).reshape((-1,1))
967 >>> C1 = sp.spatial.distance.cdist(x, x)
968 >>> C2 = sp.spatial.distance.cdist(y, y)
969 >>> np.round(partial_gromov_wasserstein2(C1, C2, a, b),2)
970 1.69
971 >>> np.round(partial_gromov_wasserstein2(C1, C2, a, b, m=0.25),2)
972 0.0
973
974
975 .. _references-partial-gromov-wasserstein2:
976 References
977 ----------
978 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
979 Transport with Applications on Positive-Unlabeled Learning".
980 NeurIPS.
981
982 """
983 warnings.warn(
984 "This function will be deprecated in a near future, please use "
985 "ot.gromov.partial_gromov_wasserstein2` instead.",
986 stacklevel=2,
987 )
988
989 partial_gw, log_gw = partial_gromov_wasserstein(
990 C1, C2, p, q, m, nb_dummies, G0, thres, numItermax, tol, True, verbose, **kwargs
991 )
992
993 log_gw["T"] = partial_gw
994
995 if log:
996 return log_gw["partial_gw_dist"], log_gw
997 else:
998 return log_gw["partial_gw_dist"]
999
1000
1001 def entropic_partial_gromov_wasserstein(
1002 C1,
1003 C2,
1004 p,
1005 q,
1006 reg,
1007 m=None,
1008 G0=None,
1009 numItermax=1000,
1010 tol=1e-7,
1011 log=False,
1012 verbose=False,
1013 ):
1014 r"""
1015 Returns the partial Gromov-Wasserstein transport between
1016 :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`
1017
1018 The function solves the following optimization problem:
1019
1020 .. math::
1021 \gamma = \mathop{\arg \min}_{\gamma} \quad \sum_{i,j,k,l}
1022 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l})\cdot
1023 \gamma_{i,j}\cdot\gamma_{k,l} + \mathrm{reg} \cdot\Omega(\gamma)
1024
1025 .. math::
1026 s.t. \ \gamma &\geq 0
1027
1028 \gamma \mathbf{1} &\leq \mathbf{a}
1029
1030 \gamma^T \mathbf{1} &\leq \mathbf{b}
1031
1032 \mathbf{1}^T \gamma^T \mathbf{1} = m
1033 &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
1034
1035 where :
1036
1037 - :math:`\mathbf{C_1}` is the metric cost matrix in the source space
1038 - :math:`\mathbf{C_2}` is the metric cost matrix in the target space
1039 - :math:`\mathbf{p}` and :math:`\mathbf{q}` are the sample weights
1040 - `L`: quadratic loss function
1041 - :math:`\Omega` is the entropic regularization term,
1042 :math:`\Omega=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
1043 - `m` is the amount of mass to be transported
1044
1045 The formulation of the GW problem has been proposed in
1046 :ref:`[12] <references-entropic-partial-gromov-wasserstein>` and the
1047 partial GW in :ref:`[29] <references-entropic-partial-gromov-wasserstein>`
1048
1049 .. note:: This function will be deprecated in a near future, please use
1050 `ot.gromov.entropic_partial_gromov_wasserstein` instead.
1051
1052 Parameters
1053 ----------
1054 C1 : ndarray, shape (ns, ns)
1055 Metric cost matrix in the source space
1056 C2 : ndarray, shape (nt, nt)
1057 Metric cost matrix in the target space
1058 p : ndarray, shape (ns,)
1059 Distribution in the source space
1060 q : ndarray, shape (nt,)
1061 Distribution in the target space
1062 reg: float
1063 entropic regularization parameter
1064 m : float, optional
1065 Amount of mass to be transported (default:
1066 :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
1067 G0 : ndarray, shape (ns, nt), optional
1068 Initialization of the transportation matrix
1069 numItermax : int, optional
1070 Max number of iterations
1071 tol : float, optional
1072 Stop threshold on error (>0)
1073 log : bool, optional
1074 return log if True
1075 verbose : bool, optional
1076 Print information along iterations
1077
1078 Examples
1079 --------
1080 >>> import ot
1081 >>> import scipy as sp
1082 >>> a = np.array([0.25] * 4)
1083 >>> b = np.array([0.25] * 4)
1084 >>> x = np.array([1,2,100,200]).reshape((-1,1))
1085 >>> y = np.array([3,2,98,199]).reshape((-1,1))
1086 >>> C1 = sp.spatial.distance.cdist(x, x)
1087 >>> C2 = sp.spatial.distance.cdist(y, y)
1088 >>> np.round(entropic_partial_gromov_wasserstein(C1, C2, a, b, 50), 2)
1089 array([[0.12, 0.13, 0. , 0. ],
1090 [0.13, 0.12, 0. , 0. ],
1091 [0. , 0. , 0.25, 0. ],
1092 [0. , 0. , 0. , 0.25]])
1093 >>> np.round(entropic_partial_gromov_wasserstein(C1, C2, a, b, 50,0.25), 2)
1094 array([[0.02, 0.03, 0. , 0.03],
1095 [0.03, 0.03, 0. , 0.03],
1096 [0. , 0. , 0.03, 0. ],
1097 [0.02, 0.02, 0. , 0.03]])
1098
1099 Returns
1100 -------
1101 :math: `gamma` : (dim_a, dim_b) ndarray
1102 Optimal transportation matrix for the given parameters
1103 log : dict
1104 log dictionary returned only if `log` is `True`
1105
1106
1107 .. _references-entropic-partial-gromov-wasserstein:
1108 References
1109 ----------
1110 .. [12] Peyré, Gabriel, Marco Cuturi, and Justin Solomon,
1111 "Gromov-Wasserstein averaging of kernel and distance matrices."
1112 International Conference on Machine Learning (ICML). 2016.
1113
1114 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
1115 Transport with Applications on Positive-Unlabeled Learning".
1116 NeurIPS.
1117
1118 See Also
1119 --------
1120 ot.partial.partial_gromov_wasserstein: exact Partial Gromov-Wasserstein
1121 """
1122
1123 warnings.warn(
1124 "This function will be deprecated in a near future, please use "
1125 "ot.gromov.entropic_partial_gromov_wasserstein` instead.",
1126 stacklevel=2,
1127 )
1128
1129 if G0 is None:
1130 G0 = np.outer(p, q)
1131
1132 if m is None:
1133 m = np.min((np.sum(p), np.sum(q)))
1134 elif m < 0:
1135 raise ValueError("Problem infeasible. Parameter m should be greater" " than 0.")
1136 elif m > np.min((np.sum(p), np.sum(q))):
1137 raise ValueError(
1138 "Problem infeasible. Parameter m should lower or"
1139 " equal than min(|a|_1, |b|_1)."
1140 )
1141
1142 cpt = 0
1143 err = 1
1144
1145 loge = {"err": []}
1146
1147 while err > tol and cpt < numItermax:
1148 Gprev = G0
1149 M_entr = gwgrad_partial(C1, C2, G0)
1150 G0 = entropic_partial_wasserstein(p, q, M_entr, reg, m)
1151 if cpt % 10 == 0: # to speed up the computations
1152 err = np.linalg.norm(G0 - Gprev)
1153 if log:
1154 loge["err"].append(err)
1155 if verbose:
1156 if cpt % 200 == 0:
1157 print(
1158 "{:5s}|{:12s}|{:12s}".format("It.", "Err", "Loss")
1159 + "\n"
1160 + "-" * 31
1161 )
1162 print("{:5d}|{:8e}|{:8e}".format(cpt, err, gwloss_partial(C1, C2, G0)))
1163
1164 cpt += 1
1165
1166 if log:
1167 loge["partial_gw_dist"] = gwloss_partial(C1, C2, G0)
1168 return G0, loge
1169 else:
1170 return G0
1171
1172
1173 def entropic_partial_gromov_wasserstein2(
1174 C1,
1175 C2,
1176 p,
1177 q,
1178 reg,
1179 m=None,
1180 G0=None,
1181 numItermax=1000,
1182 tol=1e-7,
1183 log=False,
1184 verbose=False,
1185 ):
1186 r"""
1187 Returns the partial Gromov-Wasserstein discrepancy between
1188 :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`
1189
1190 The function solves the following optimization problem:
1191
1192 .. math::
1193 GW = \min_{\gamma} \quad \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k},
1194 \mathbf{C_2}_{j,l})\cdot
1195 \gamma_{i,j}\cdot\gamma_{k,l} + \mathrm{reg} \cdot\Omega(\gamma)
1196
1197 .. math::
1198 s.t. \ \gamma &\geq 0
1199
1200 \gamma \mathbf{1} &\leq \mathbf{a}
1201
1202 \gamma^T \mathbf{1} &\leq \mathbf{b}
1203
1204 \mathbf{1}^T \gamma^T \mathbf{1} = m &\leq \min\{\|\mathbf{a}\|_1, \|\mathbf{b}\|_1\}
1205
1206 where :
1207
1208 - :math:`\mathbf{C_1}` is the metric cost matrix in the source space
1209 - :math:`\mathbf{C_2}` is the metric cost matrix in the target space
1210 - :math:`\mathbf{p}` and :math:`\mathbf{q}` are the sample weights
1211 - `L` : quadratic loss function
1212 - :math:`\Omega` is the entropic regularization term,
1213 :math:`\Omega=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
1214 - `m` is the amount of mass to be transported
1215
1216 The formulation of the GW problem has been proposed in
1217 :ref:`[12] <references-entropic-partial-gromov-wasserstein2>` and the
1218 partial GW in :ref:`[29] <references-entropic-partial-gromov-wasserstein2>`
1219
1220 .. note:: This function will be deprecated in a near future, please use
1221 `ot.gromov.entropic_partial_gromov_wasserstein2` instead.
1222
1223 Parameters
1224 ----------
1225 C1 : ndarray, shape (ns, ns)
1226 Metric cost matrix in the source space
1227 C2 : ndarray, shape (nt, nt)
1228 Metric cost matrix in the target space
1229 p : ndarray, shape (ns,)
1230 Distribution in the source space
1231 q : ndarray, shape (nt,)
1232 Distribution in the target space
1233 reg: float
1234 entropic regularization parameter
1235 m : float, optional
1236 Amount of mass to be transported (default:
1237 :math:`\min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\}`)
1238 G0 : ndarray, shape (ns, nt), optional
1239 Initialization of the transportation matrix
1240 numItermax : int, optional
1241 Max number of iterations
1242 tol : float, optional
1243 Stop threshold on error (>0)
1244 log : bool, optional
1245 return log if True
1246 verbose : bool, optional
1247 Print information along iterations
1248
1249
1250 Returns
1251 -------
1252 partial_gw_dist: float
1253 Gromov-Wasserstein distance
1254 log : dict
1255 log dictionary returned only if `log` is `True`
1256
1257 Examples
1258 --------
1259 >>> import ot
1260 >>> import scipy as sp
1261 >>> a = np.array([0.25] * 4)
1262 >>> b = np.array([0.25] * 4)
1263 >>> x = np.array([1,2,100,200]).reshape((-1,1))
1264 >>> y = np.array([3,2,98,199]).reshape((-1,1))
1265 >>> C1 = sp.spatial.distance.cdist(x, x)
1266 >>> C2 = sp.spatial.distance.cdist(y, y)
1267 >>> np.round(entropic_partial_gromov_wasserstein2(C1, C2, a, b,50), 2)
1268 1.87
1269
1270
1271 .. _references-entropic-partial-gromov-wasserstein2:
1272 References
1273 ----------
1274 .. [12] Peyré, Gabriel, Marco Cuturi, and Justin Solomon,
1275 "Gromov-Wasserstein averaging of kernel and distance matrices."
1276 International Conference on Machine Learning (ICML). 2016.
1277
1278 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal
1279 Transport with Applications on Positive-Unlabeled Learning".
1280 NeurIPS.
1281 """
1282 warnings.warn(
1283 "This function will be deprecated in a near future, please use "
1284 "ot.gromov.entropic_partial_gromov_wasserstein2` instead.",
1285 stacklevel=2,
1286 )
1287
1288 partial_gw, log_gw = entropic_partial_gromov_wasserstein(
1289 C1, C2, p, q, reg, m, G0, numItermax, tol, True, verbose
1290 )
1291
1292 log_gw["T"] = partial_gw
1293
1294 if log:
1295 return log_gw["partial_gw_dist"], log_gw
1296 else:
1297 return log_gw["partial_gw_dist"]