Debian Codegraph @

ot/solvers.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 General OT solvers with unified API
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 #
8 # License: MIT License
9
10 from .utils import OTResult, dist
11 from .lp import emd2, wasserstein_1d
12 from .backend import get_backend
13 from .unbalanced import mm_unbalanced, sinkhorn_knopp_unbalanced, lbfgsb_unbalanced
14 from .bregman import sinkhorn_log, empirical_sinkhorn2, empirical_sinkhorn2_geomloss
15 from .smooth import smooth_ot_dual
16 from .gromov import (
17 gromov_wasserstein2,
18 fused_gromov_wasserstein2,
19 entropic_gromov_wasserstein2,
20 entropic_fused_gromov_wasserstein2,
21 semirelaxed_gromov_wasserstein2,
22 semirelaxed_fused_gromov_wasserstein2,
23 entropic_semirelaxed_fused_gromov_wasserstein2,
24 entropic_semirelaxed_gromov_wasserstein2,
25 partial_gromov_wasserstein2,
26 entropic_partial_gromov_wasserstein2,
27 )
28 from .gaussian import empirical_bures_wasserstein_distance
29 from .factored import factored_optimal_transport
30 from .lowrank import lowrank_sinkhorn
31 from .optim import cg
32
33 lst_method_lazy = [
34 "1d",
35 "gaussian",
36 "lowrank",
37 "factored",
38 "geomloss",
39 "geomloss_auto",
40 "geomloss_tensorized",
41 "geomloss_online",
42 "geomloss_multiscale",
43 ]
44
45
46 def solve(
47 M,
48 a=None,
49 b=None,
50 reg=None,
51 c=None,
52 reg_type="KL",
53 unbalanced=None,
54 unbalanced_type="KL",
55 method=None,
56 n_threads=1,
57 max_iter=None,
58 plan_init=None,
59 potentials_init=None,
60 tol=None,
61 verbose=False,
62 grad="autodiff",
63 ):
64 r"""Solve the discrete optimal transport problem and return :any:`OTResult` object
65
66 The function solves the following general optimal transport problem
67
68 .. math::
69 \min_{\mathbf{T}\geq 0} \quad \sum_{i,j} T_{i,j}M_{i,j} + \lambda_r R(\mathbf{T}) +
70 \lambda_1 U(\mathbf{T}\mathbf{1},\mathbf{a}) +
71 \lambda_2 U(\mathbf{T}^T\mathbf{1},\mathbf{b})
72
73 The regularization is selected with `reg` (:math:`\lambda_r`) and `reg_type`. By
74 default ``reg=None`` and there is no regularization. The unbalanced marginal
75 penalization can be selected with `unbalanced` (:math:`(\lambda_1, \lambda_2)`) and
76 `unbalanced_type`. By default ``unbalanced=None`` and the function
77 solves the exact optimal transport problem (respecting the marginals).
78
79 Parameters
80 ----------
81 M : array_like, shape (dim_a, dim_b)
82 Loss matrix
83 a : array-like, shape (dim_a,), optional
84 Samples weights in the source domain (default is uniform)
85 b : array-like, shape (dim_b,), optional
86 Samples weights in the source domain (default is uniform)
87 reg : float, optional
88 Regularization weight :math:`\lambda_r`, by default None (no reg., exact
89 OT)
90 c : array-like (dim_a, dim_b), optional (default=None)
91 Reference measure for the regularization.
92 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
93 If :math:`\texttt{reg_type}='entropy'`, then :math:`\mathbf{c} = 1_{dim_a} 1_{dim_b}^T`.
94 reg_type : str, optional
95 Type of regularization :math:`R` either "KL", "L2", "entropy",
96 by default "KL". a tuple of functions can be provided for general
97 solver (see :any:`cg`). This is only used when ``reg!=None``.
98 unbalanced : float or indexable object of length 1 or 2
99 Marginal relaxation term.
100 If it is a scalar or an indexable object of length 1,
101 then the same relaxation is applied to both marginal relaxations.
102 The balanced OT can be recovered using :math:`unbalanced=float("inf")`.
103 For semi-relaxed case, use either
104 :math:`unbalanced=(float("inf"), scalar)` or
105 :math:`unbalanced=(scalar, float("inf"))`.
106 If unbalanced is an array,
107 it must have the same backend as input arrays `(a, b, M)`.
108 unbalanced_type : str, optional
109 Type of unbalanced penalization function :math:`U` either "KL", "L2",
110 "TV", by default "KL".
111 method : str, optional
112 Method for solving the problem when multiple algorithms are available,
113 default None for automatic selection.
114 n_threads : int, optional
115 Number of OMP threads for exact OT solver, by default 1
116 max_iter : int, optional
117 Maximum number of iterations, by default None (default values in each solvers)
118 plan_init : array_like, shape (dim_a, dim_b), optional
119 Initialization of the OT plan for iterative methods, by default None
120 potentials_init : (array_like(dim_a,),array_like(dim_b,)), optional
121 Initialization of the OT dual potentials for iterative methods, by default None
122 tol : _type_, optional
123 Tolerance for solution precision, by default None (default values in each solvers)
124 verbose : bool, optional
125 Print information in the solver, by default False
126 grad : str, optional
127 Type of gradient computation, either or 'autodiff' or 'envelope' used only for
128 Sinkhorn solver. By default 'autodiff' provides gradients wrt all
129 outputs (`plan, value, value_linear`) but with important memory cost.
130 'envelope' provides gradients only for `value` and and other outputs are
131 detached. This is useful for memory saving when only the value is needed.
132
133 Returns
134 -------
135 res : OTResult()
136 Result of the optimization problem. The information can be obtained as follows:
137
138 - res.plan : OT plan :math:`\mathbf{T}`
139 - res.potentials : OT dual potentials
140 - res.value : Optimal value of the optimization problem
141 - res.value_linear : Linear OT loss with the optimal OT plan
142
143 See :any:`OTResult` for more information.
144
145 Notes
146 -----
147
148 The following methods are available for solving the OT problems:
149
150 - **Classical exact OT problem [1]** (default parameters) :
151
152 .. math::
153 \min_\mathbf{T} \quad \langle \mathbf{T}, \mathbf{M} \rangle_F
154
155 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
156
157 \mathbf{T}^T \mathbf{1} = \mathbf{b}
158
159 \mathbf{T} \geq 0
160
161 can be solved with the following code:
162
163 .. code-block:: python
164
165 res = ot.solve(M, a, b)
166
167 - **Entropic regularized OT [2]** (when ``reg!=None``):
168
169 .. math::
170 \min_\mathbf{T} \quad \langle \mathbf{T}, \mathbf{M} \rangle_F + \lambda R(\mathbf{T})
171
172 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
173
174 \mathbf{T}^T \mathbf{1} = \mathbf{b}
175
176 \mathbf{T} \geq 0
177
178 can be solved with the following code:
179
180 .. code-block:: python
181
182 # default is ``"KL"`` regularization (``reg_type="KL"``)
183 res = ot.solve(M, a, b, reg=1.0)
184 # or for original Sinkhorn paper formulation [2]
185 res = ot.solve(M, a, b, reg=1.0, reg_type='entropy')
186
187 # Use envelope theorem differentiation for memory saving
188 res = ot.solve(M, a, b, reg=1.0, grad='envelope') # M, a, b are torch tensors
189 res.value.backward() # only the value is differentiable
190
191 Note that by default the Sinkhorn solver uses automatic differentiation to
192 compute the gradients of the values and plan. This can be changed with the
193 `grad` parameter. The `envelope` mode computes the gradients only
194 for the value and the other outputs are detached. This is useful for
195 memory saving when only the gradient of value is needed.
196
197 - **Quadratic regularized OT [17]** (when ``reg!=None`` and ``reg_type="L2"``):
198
199 .. math::
200 \min_\mathbf{T} \quad \langle \mathbf{T}, \mathbf{M} \rangle_F + \lambda R(\mathbf{T})
201
202 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
203
204 \mathbf{T}^T \mathbf{1} = \mathbf{b}
205
206 \mathbf{T} \geq 0
207
208 can be solved with the following code:
209
210 .. code-block:: python
211
212 res = ot.solve(M,a,b,reg=1.0,reg_type='L2')
213
214 - **Unbalanced OT [41]** (when ``unbalanced!=None``):
215
216 .. math::
217 \min_{\mathbf{T}\geq 0} \quad \sum_{i,j} T_{i,j}M_{i,j} +
218 \lambda_1 U(\mathbf{T}\mathbf{1},\mathbf{a}) +
219 \lambda_2 U(\mathbf{T}^T\mathbf{1},\mathbf{b})
220
221 can be solved with the following code:
222
223 .. code-block:: python
224
225 # default is ``"KL"``
226 res = ot.solve(M,a,b,unbalanced=1.0)
227 # quadratic unbalanced OT
228 res = ot.solve(M,a,b,unbalanced=1.0,unbalanced_type='L2')
229 # TV = partial OT
230 res = ot.solve(M,a,b,unbalanced=1.0,unbalanced_type='TV')
231
232
233 - **Regularized unbalanced regularized OT [34]** (when ``unbalanced!=None`` and ``reg!=None``):
234
235 .. math::
236 \min_{\mathbf{T}\geq 0} \quad \sum_{i,j} T_{i,j}M_{i,j} + \lambda_r R(\mathbf{T}) +
237 \lambda_1 U(\mathbf{T}\mathbf{1},\mathbf{a}) +
238 \lambda_2 U(\mathbf{T}^T\mathbf{1},\mathbf{b})
239
240 can be solved with the following code:
241
242 .. code-block:: python
243
244 # default is ``"KL"`` for both
245 res = ot.solve(M,a,b,reg=1.0,unbalanced=1.0)
246 # quadratic unbalanced OT with KL regularization
247 res = ot.solve(M,a,b,reg=1.0,unbalanced=1.0,unbalanced_type='L2')
248 # both quadratic
249 res = ot.solve(M,a,b,reg=1.0, reg_type='L2',unbalanced=1.0,unbalanced_type='L2')
250
251
252 .. _references-solve:
253 References
254 ----------
255
256 .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
257 (2011, December). Displacement interpolation using Lagrangian mass
258 transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
259 158). ACM.
260
261 .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation
262 of Optimal Transport, Advances in Neural Information Processing
263 Systems (NIPS) 26, 2013
264
265 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
266 Scaling algorithms for unbalanced transport problems.
267 arXiv preprint arXiv:1607.05816.
268
269 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse
270 Optimal Transport. Proceedings of the Twenty-First International
271 Conference on Artificial Intelligence and Statistics (AISTATS).
272
273 .. [34] Feydy, J., Séjourné, T., Vialard, F. X., Amari, S. I., Trouvé,
274 A., & Peyré, G. (2019, April). Interpolating between optimal transport
275 and MMD using Sinkhorn divergences. In The 22nd International Conference
276 on Artificial Intelligence and Statistics (pp. 2681-2690). PMLR.
277
278 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
279 Unbalanced optimal transport through non-negative penalized
280 linear regression. NeurIPS.
281
282 """
283
284 # detect backend
285 nx = get_backend(M, a, b, c)
286
287 # create uniform weights if not given
288 if a is None:
289 a = nx.ones(M.shape[0], type_as=M) / M.shape[0]
290 if b is None:
291 b = nx.ones(M.shape[1], type_as=M) / M.shape[1]
292 if c is None:
293 c = a[:, None] * b[None, :]
294
295 if reg is None:
296 reg = 0
297
298 # default values for solutions
299 potentials = None
300 value = None
301 value_linear = None
302 plan = None
303 status = None
304
305 if reg == 0: # exact OT
306 if unbalanced is None: # Exact balanced OT
307 # default values for EMD solver
308 if max_iter is None:
309 max_iter = 1000000
310
311 value_linear, log = emd2(
312 a,
313 b,
314 M,
315 numItermax=max_iter,
316 log=True,
317 return_matrix=True,
318 numThreads=n_threads,
319 )
320
321 value = value_linear
322 potentials = (log["u"], log["v"])
323 plan = log["G"]
324 status = log["warning"] if log["warning"] is not None else "Converged"
325
326 elif unbalanced_type.lower() in ["kl", "l2"]: # unbalanced exact OT
327 # default values for exact unbalanced OT
328 if max_iter is None:
329 max_iter = 1000
330 if tol is None:
331 tol = 1e-12
332
333 plan, log = mm_unbalanced(
334 a,
335 b,
336 M,
337 reg_m=unbalanced,
338 c=c,
339 reg=reg,
340 div=unbalanced_type,
341 numItermax=max_iter,
342 stopThr=tol,
343 log=True,
344 verbose=verbose,
345 G0=plan_init,
346 )
347
348 value_linear = log["cost"]
349 value = log["total_cost"]
350
351 elif unbalanced_type.lower() == "tv":
352 if max_iter is None:
353 max_iter = 1000
354 if tol is None:
355 tol = 1e-12
356 if isinstance(reg_type, str):
357 reg_type = reg_type.lower()
358
359 plan, log = lbfgsb_unbalanced(
360 a,
361 b,
362 M,
363 reg=reg,
364 reg_m=unbalanced,
365 c=c,
366 reg_div=reg_type,
367 regm_div=unbalanced_type,
368 numItermax=max_iter,
369 stopThr=tol,
370 verbose=verbose,
371 log=True,
372 G0=plan_init,
373 )
374
375 value_linear = log["cost"]
376 value = log["total_cost"]
377
378 else:
379 raise (
380 NotImplementedError(
381 'Unknown unbalanced_type="{}"'.format(unbalanced_type)
382 )
383 )
384
385 else: # regularized OT
386 if unbalanced is None: # Balanced regularized OT
387 if isinstance(reg_type, tuple): # general solver
388 f, df = reg_type
389
390 if max_iter is None:
391 max_iter = 1000
392 if tol is None:
393 tol = 1e-9
394
395 plan, log = cg(
396 a,
397 b,
398 M,
399 reg=reg,
400 f=f,
401 df=df,
402 numItermax=max_iter,
403 stopThr=tol,
404 log=True,
405 verbose=verbose,
406 G0=plan_init,
407 )
408
409 value_linear = nx.sum(M * plan)
410 value = log["loss"][-1]
411 potentials = (log["u"], log["v"])
412
413 elif reg_type.lower() in ["entropy", "kl"]:
414 if grad == "envelope": # if envelope then detach the input
415 M0, a0, b0 = M, a, b
416 M, a, b = nx.detach(M, a, b)
417
418 # default values for sinkhorn
419 if max_iter is None:
420 max_iter = 1000
421 if tol is None:
422 tol = 1e-9
423
424 plan, log = sinkhorn_log(
425 a,
426 b,
427 M,
428 reg=reg,
429 numItermax=max_iter,
430 stopThr=tol,
431 log=True,
432 verbose=verbose,
433 )
434
435 value_linear = nx.sum(M * plan)
436
437 if reg_type.lower() == "entropy":
438 value = value_linear + reg * nx.sum(plan * nx.log(plan + 1e-16))
439 else:
440 value = value_linear + reg * nx.kl_div(
441 plan, a[:, None] * b[None, :]
442 )
443
444 potentials = (log["log_u"], log["log_v"])
445
446 if grad == "envelope": # set the gradient at convergence
447 value = nx.set_gradients(
448 value,
449 (M0, a0, b0),
450 (
451 plan,
452 reg * (potentials[0] - potentials[0].mean()),
453 reg * (potentials[1] - potentials[1].mean()),
454 ),
455 )
456
457 elif reg_type.lower() == "l2":
458 if max_iter is None:
459 max_iter = 1000
460 if tol is None:
461 tol = 1e-9
462
463 plan, log = smooth_ot_dual(
464 a,
465 b,
466 M,
467 reg=reg,
468 numItermax=max_iter,
469 stopThr=tol,
470 log=True,
471 verbose=verbose,
472 )
473
474 value_linear = nx.sum(M * plan)
475 value = value_linear + reg * nx.sum(plan**2)
476 potentials = (log["alpha"], log["beta"])
477
478 else:
479 raise (
480 NotImplementedError(
481 'Not implemented reg_type="{}"'.format(reg_type)
482 )
483 )
484
485 else: # unbalanced AND regularized OT
486 if (
487 not isinstance(reg_type, tuple)
488 and reg_type.lower() in ["kl"]
489 and unbalanced_type.lower() == "kl"
490 ):
491 if max_iter is None:
492 max_iter = 1000
493 if tol is None:
494 tol = 1e-9
495
496 plan, log = sinkhorn_knopp_unbalanced(
497 a,
498 b,
499 M,
500 reg=reg,
501 reg_m=unbalanced,
502 method=method,
503 reg_type=reg_type,
504 c=c,
505 warmstart=potentials_init,
506 numItermax=max_iter,
507 stopThr=tol,
508 verbose=verbose,
509 log=True,
510 )
511
512 value_linear = log["cost"]
513 value = log["total_cost"]
514
515 potentials = (log["logu"], log["logv"])
516
517 elif (
518 isinstance(reg_type, tuple)
519 or reg_type.lower() in ["kl", "l2", "entropy"]
520 ) and unbalanced_type.lower() in ["kl", "l2", "tv"]:
521 if max_iter is None:
522 max_iter = 1000
523 if tol is None:
524 tol = 1e-12
525 if isinstance(reg_type, str):
526 reg_type = reg_type.lower()
527
528 plan, log = lbfgsb_unbalanced(
529 a,
530 b,
531 M,
532 reg=reg,
533 reg_m=unbalanced,
534 c=c,
535 reg_div=reg_type,
536 regm_div=unbalanced_type,
537 numItermax=max_iter,
538 stopThr=tol,
539 verbose=verbose,
540 log=True,
541 G0=plan_init,
542 )
543
544 value_linear = log["cost"]
545 value = log["total_cost"]
546
547 else:
548 raise (
549 NotImplementedError(
550 'Not implemented reg_type="{}" and unbalanced_type="{}"'.format(
551 reg_type, unbalanced_type
552 )
553 )
554 )
555
556 res = OTResult(
557 potentials=potentials,
558 value=value,
559 value_linear=value_linear,
560 plan=plan,
561 status=status,
562 backend=nx,
563 )
564
565 return res
566
567
568 def solve_gromov(
569 Ca,
570 Cb,
571 M=None,
572 a=None,
573 b=None,
574 loss="L2",
575 symmetric=None,
576 alpha=0.5,
577 reg=None,
578 reg_type="entropy",
579 unbalanced=None,
580 unbalanced_type="KL",
581 n_threads=1,
582 method=None,
583 max_iter=None,
584 plan_init=None,
585 tol=None,
586 verbose=False,
587 ):
588 r"""Solve the discrete (Fused) Gromov-Wasserstein and return :any:`OTResult` object
589
590 The function solves the following optimization problem:
591
592 .. math::
593 \min_{\mathbf{T}\geq 0} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F +
594 \alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} + \lambda_r R(\mathbf{T}) + \lambda_u U(\mathbf{T}\mathbf{1},\mathbf{a}) + \lambda_u U(\mathbf{T}^T\mathbf{1},\mathbf{b})
595
596 The regularization is selected with `reg` (:math:`\lambda_r`) and
597 `reg_type`. By default ``reg=None`` and there is no regularization. The
598 unbalanced marginal penalization can be selected with `unbalanced`
599 (:math:`\lambda_u`) and `unbalanced_type`. By default ``unbalanced=None``
600 and the function solves the exact optimal transport problem (respecting the
601 marginals).
602
603 Parameters
604 ----------
605 Ca : array_like, shape (dim_a, dim_a)
606 Cost matrix in the source domain
607 Cb : array_like, shape (dim_b, dim_b)
608 Cost matrix in the target domain
609 M : array_like, shape (dim_a, dim_b), optional
610 Linear cost matrix for Fused Gromov-Wasserstein (default is None).
611 a : array-like, shape (dim_a,), optional
612 Samples weights in the source domain (default is uniform)
613 b : array-like, shape (dim_b,), optional
614 Samples weights in the source domain (default is uniform)
615 loss : str, optional
616 Type of loss function, either ``"L2"`` or ``"KL"``, by default ``"L2"``
617 symmetric : bool, optional
618 Use symmetric version of the Gromov-Wasserstein problem, by default None
619 tests whether the matrices are symmetric or True/False to avoid the test.
620 reg : float, optional
621 Regularization weight :math:`\lambda_r`, by default None (no reg., exact
622 OT)
623 reg_type : str, optional
624 Type of regularization :math:`R`, by default "entropy" (only used when
625 ``reg!=None``)
626 alpha : float, optional
627 Weight the quadratic term (alpha*Gromov) and the linear term
628 ((1-alpha)*Wass) in the Fused Gromov-Wasserstein problem. Not used for
629 Gromov problem (when M is not provided). By default ``alpha=None``
630 corresponds to ``alpha=1`` for Gromov problem (``M==None``) and
631 ``alpha=0.5`` for Fused Gromov-Wasserstein problem (``M!=None``)
632 unbalanced : float, optional
633 Unbalanced penalization weight :math:`\lambda_u`, by default None
634 (balanced OT), Not implemented yet
635 unbalanced_type : str, optional
636 Type of unbalanced penalization function :math:`U` either "KL", "semirelaxed",
637 "partial", by default "KL" but note that it is not implemented yet.
638 n_threads : int, optional
639 Number of OMP threads for exact OT solver, by default 1
640 method : str, optional
641 Method for solving the problem when multiple algorithms are available,
642 default None for automatic selection.
643 max_iter : int, optional
644 Maximum number of iterations, by default None (default values in each
645 solvers)
646 plan_init : array_like, shape (dim_a, dim_b), optional
647 Initialization of the OT plan for iterative methods, by default None
648 tol : float, optional
649 Tolerance for solution precision, by default None (default values in
650 each solvers)
651 verbose : bool, optional
652 Print information in the solver, by default False
653
654 Returns
655 -------
656 res : OTResult()
657 Result of the optimization problem. The information can be obtained as follows:
658
659 - res.plan : OT plan :math:`\mathbf{T}`
660 - res.potentials : OT dual potentials
661 - res.value : Optimal value of the optimization problem
662 - res.value_linear : Linear OT loss with the optimal OT plan
663 - res.value_quad : Quadratic (GW) part of the OT loss with the optimal OT plan
664
665 See :any:`OTResult` for more information.
666
667 Notes
668 -----
669 The following methods are available for solving the Gromov-Wasserstein
670 problem:
671
672 - **Classical Gromov-Wasserstein (GW) problem [3]** (default parameters):
673
674 .. math::
675 \min_{\mathbf{T}\geq 0} \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j}\mathbf{T}_{k,l}
676
677 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
678
679 \mathbf{T}^T \mathbf{1} = \mathbf{b}
680
681 \mathbf{T} \geq 0
682
683 can be solved with the following code:
684
685 .. code-block:: python
686
687 res = ot.solve_gromov(Ca, Cb) # uniform weights
688 res = ot.solve_gromov(Ca, Cb, a=a, b=b) # given weights
689 res = ot.solve_gromov(Ca, Cb, loss='KL') # KL loss
690
691 plan = res.plan # GW plan
692 value = res.value # GW value
693
694 - **Fused Gromov-Wasserstein (FGW) problem [24]** (when ``M!=None``):
695
696 .. math::
697 \min_{\mathbf{T}\geq 0} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F +
698 \alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j}\mathbf{T}_{k,l}
699
700 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
701
702 \mathbf{T}^T \mathbf{1} = \mathbf{b}
703
704 \mathbf{T} \geq 0
705
706 can be solved with the following code:
707
708 .. code-block:: python
709
710 res = ot.solve_gromov(Ca, Cb, M) # uniform weights, alpha=0.5 (default)
711 res = ot.solve_gromov(Ca, Cb, M, a=a, b=b, alpha=0.1) # given weights and alpha
712
713 plan = res.plan # FGW plan
714 loss_linear_term = res.value_linear # Wasserstein part of the loss
715 loss_quad_term = res.value_quad # Gromov part of the loss
716 loss = res.value # FGW value
717
718 - **Regularized (Fused) Gromov-Wasserstein (GW) problem [12]** (when ``reg!=None``):
719
720 .. math::
721 \min_{\mathbf{T}\geq 0} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F +
722 \alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j}\mathbf{T}_{k,l} + \lambda_r R(\mathbf{T})
723
724 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
725
726 \mathbf{T}^T \mathbf{1} = \mathbf{b}
727
728 \mathbf{T} \geq 0
729
730 can be solved with the following code:
731
732 .. code-block:: python
733
734 res = ot.solve_gromov(Ca, Cb, reg=1.0) # GW entropy regularization (default)
735 res = ot.solve_gromov(Ca, Cb, M, a=a, b=b, reg=10, alpha=0.1) # FGW with entropy
736
737 plan = res.plan # FGW plan
738 loss_linear_term = res.value_linear # Wasserstein part of the loss
739 loss_quad_term = res.value_quad # Gromov part of the loss
740 loss = res.value # FGW value (including regularization)
741
742 - **Semi-relaxed (Fused) Gromov-Wasserstein (GW) [48]** (when ``unbalanced='semirelaxed'``):
743
744 .. math::
745 \min_{\mathbf{T}\geq 0} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F +
746 \alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j}\mathbf{T}_{k,l}
747
748 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
749
750 \mathbf{T} \geq 0
751
752 can be solved with the following code:
753
754 .. code-block:: python
755
756 res = ot.solve_gromov(Ca, Cb, unbalanced='semirelaxed') # semirelaxed GW
757 res = ot.solve_gromov(Ca, Cb, unbalanced='semirelaxed', reg=1) # entropic semirelaxed GW
758 res = ot.solve_gromov(Ca, Cb, M, unbalanced='semirelaxed', alpha=0.1) # semirelaxed FGW
759
760 plan = res.plan # FGW plan
761 right_marginal = res.marginal_b # right marginal of the plan
762
763 - **Partial (Fused) Gromov-Wasserstein (GW) problem [29]** (when ``unbalanced='partial'``):
764
765 .. math::
766 \min_{\mathbf{T}\geq 0} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F +
767 \alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j}\mathbf{T}_{k,l}
768
769 s.t. \ \mathbf{T} \mathbf{1} \leq \mathbf{a}
770
771 \mathbf{T}^T \mathbf{1} \leq \mathbf{b}
772
773 \mathbf{T} \geq 0
774
775 \mathbf{1}^T\mathbf{T}\mathbf{1} = m
776
777 can be solved with the following code:
778
779 .. code-block:: python
780
781 res = ot.solve_gromov(Ca, Cb, unbalanced_type='partial', unbalanced=0.8) # partial GW with m=0.8
782
783
784 .. _references-solve-gromov:
785 References
786 ----------
787
788 .. [3] Mémoli, F. (2011). Gromov–Wasserstein distances and the metric
789 approach to object matching. Foundations of computational mathematics,
790 11(4), 417-487.
791
792 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon (2016),
793 Gromov-Wasserstein averaging of kernel and distance matrices
794 International Conference on Machine Learning (ICML).
795
796 .. [24] Vayer, T., Chapel, L., Flamary, R., Tavenard, R. and Courty, N.
797 (2019). Optimal Transport for structured data with application on graphs
798 Proceedings of the 36th International Conference on Machine Learning
799 (ICML).
800
801 .. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer,
802 Nicolas Courty (2022). Semi-relaxed Gromov-Wasserstein divergence and
803 applications on graphs. International Conference on Learning
804 Representations (ICLR), 2022.
805
806 .. [29] Chapel, L., Alaya, M., Gasso, G. (2020). Partial Optimal Transport
807 with Applications on Positive-Unlabeled Learning, Advances in Neural
808 Information Processing Systems (NeurIPS), 2020.
809
810 """
811
812 # detect backend
813 nx = get_backend(Ca, Cb, M, a, b)
814
815 # create uniform weights if not given
816 if a is None:
817 a = nx.ones(Ca.shape[0], type_as=Ca) / Ca.shape[0]
818 if b is None:
819 b = nx.ones(Cb.shape[1], type_as=Cb) / Cb.shape[1]
820
821 # default values for solutions
822 potentials = None
823 value = None
824 value_linear = None
825 value_quad = None
826 plan = None
827 status = None
828 log = None
829
830 loss_dict = {"l2": "square_loss", "kl": "kl_loss"}
831
832 if loss.lower() not in loss_dict.keys():
833 raise (NotImplementedError('Not implemented GW loss="{}"'.format(loss)))
834 loss_fun = loss_dict[loss.lower()]
835
836 if reg is None or reg == 0: # exact OT
837 if unbalanced is None and unbalanced_type.lower() not in [
838 "semirelaxed"
839 ]: # Exact balanced OT
840 if M is None or alpha == 1: # Gromov-Wasserstein problem
841 # default values for solver
842 if max_iter is None:
843 max_iter = 10000
844 if tol is None:
845 tol = 1e-9
846
847 value, log = gromov_wasserstein2(
848 Ca,
849 Cb,
850 a,
851 b,
852 loss_fun=loss_fun,
853 log=True,
854 symmetric=symmetric,
855 max_iter=max_iter,
856 G0=plan_init,
857 tol_rel=tol,
858 tol_abs=tol,
859 verbose=verbose,
860 )
861
862 value_quad = value
863 if alpha == 1: # set to 0 for FGW with alpha=1
864 value_linear = 0
865 plan = log["T"]
866 potentials = (log["u"], log["v"])
867
868 elif alpha == 0: # Wasserstein problem
869 # default values for EMD solver
870 if max_iter is None:
871 max_iter = 1000000
872
873 value_linear, log = emd2(
874 a,
875 b,
876 M,
877 numItermax=max_iter,
878 log=True,
879 return_matrix=True,
880 numThreads=n_threads,
881 )
882
883 value = value_linear
884 potentials = (log["u"], log["v"])
885 plan = log["G"]
886 status = log["warning"] if log["warning"] is not None else "Converged"
887 value_quad = 0
888
889 else: # Fused Gromov-Wasserstein problem
890 # default values for solver
891 if max_iter is None:
892 max_iter = 10000
893 if tol is None:
894 tol = 1e-9
895
896 value, log = fused_gromov_wasserstein2(
897 M,
898 Ca,
899 Cb,
900 a,
901 b,
902 loss_fun=loss_fun,
903 alpha=alpha,
904 log=True,
905 symmetric=symmetric,
906 max_iter=max_iter,
907 G0=plan_init,
908 tol_rel=tol,
909 tol_abs=tol,
910 verbose=verbose,
911 )
912
913 value_linear = log["lin_loss"]
914 value_quad = log["quad_loss"]
915 plan = log["T"]
916 potentials = (log["u"], log["v"])
917
918 elif unbalanced_type.lower() in ["semirelaxed"]: # Semi-relaxed OT
919 if M is None or alpha == 1: # Semi relaxed Gromov-Wasserstein problem
920 # default values for solver
921 if max_iter is None:
922 max_iter = 10000
923 if tol is None:
924 tol = 1e-9
925
926 value, log = semirelaxed_gromov_wasserstein2(
927 Ca,
928 Cb,
929 a,
930 loss_fun=loss_fun,
931 log=True,
932 symmetric=symmetric,
933 max_iter=max_iter,
934 G0=plan_init,
935 tol_rel=tol,
936 tol_abs=tol,
937 verbose=verbose,
938 )
939
940 value_quad = value
941 if alpha == 1: # set to 0 for FGW with alpha=1
942 value_linear = 0
943 plan = log["T"]
944 # potentials = (log['u'], log['v']) TODO
945
946 else: # Semi relaxed Fused Gromov-Wasserstein problem
947 # default values for solver
948 if max_iter is None:
949 max_iter = 10000
950 if tol is None:
951 tol = 1e-9
952
953 value, log = semirelaxed_fused_gromov_wasserstein2(
954 M,
955 Ca,
956 Cb,
957 a,
958 loss_fun=loss_fun,
959 alpha=alpha,
960 log=True,
961 symmetric=symmetric,
962 max_iter=max_iter,
963 G0=plan_init,
964 tol_rel=tol,
965 tol_abs=tol,
966 verbose=verbose,
967 )
968
969 value_linear = log["lin_loss"]
970 value_quad = log["quad_loss"]
971 plan = log["T"]
972 # potentials = (log['u'], log['v']) TODO
973
974 elif unbalanced_type.lower() in ["partial"]: # Partial OT
975 if M is None: # Partial Gromov-Wasserstein problem
976 if unbalanced > nx.sum(a) or unbalanced > nx.sum(b):
977 raise (ValueError("Partial GW mass given in reg is too large"))
978
979 # default values for solver
980 if max_iter is None:
981 max_iter = 1000
982 if tol is None:
983 tol = 1e-7
984
985 value, log = partial_gromov_wasserstein2(
986 Ca,
987 Cb,
988 a,
989 b,
990 m=unbalanced,
991 loss_fun=loss_fun,
992 log=True,
993 numItermax=max_iter,
994 G0=plan_init,
995 tol=tol,
996 symmetric=symmetric,
997 verbose=verbose,
998 )
999
1000 value_quad = value
1001 plan = log["T"]
1002 # potentials = (log['u'], log['v']) TODO
1003
1004 else: # partial FGW
1005 raise (NotImplementedError("Partial FGW not implemented yet"))
1006
1007 elif unbalanced_type.lower() in ["kl", "l2"]: # unbalanced exact OT
1008 raise (NotImplementedError('Unbalanced_type="{}"'.format(unbalanced_type)))
1009
1010 else:
1011 raise (
1012 NotImplementedError(
1013 'Unknown unbalanced_type="{}"'.format(unbalanced_type)
1014 )
1015 )
1016
1017 else: # regularized OT
1018 if unbalanced is None and unbalanced_type.lower() not in [
1019 "semirelaxed"
1020 ]: # Balanced regularized OT
1021 if reg_type.lower() in ["entropy"] and (
1022 M is None or alpha == 1
1023 ): # Entropic Gromov-Wasserstein problem
1024 # default values for solver
1025 if max_iter is None:
1026 max_iter = 1000
1027 if tol is None:
1028 tol = 1e-9
1029 if method is None:
1030 method = "PGD"
1031
1032 value_quad, log = entropic_gromov_wasserstein2(
1033 Ca,
1034 Cb,
1035 a,
1036 b,
1037 epsilon=reg,
1038 loss_fun=loss_fun,
1039 log=True,
1040 symmetric=symmetric,
1041 solver=method,
1042 max_iter=max_iter,
1043 G0=plan_init,
1044 tol_rel=tol,
1045 tol_abs=tol,
1046 verbose=verbose,
1047 )
1048
1049 plan = log["T"]
1050 value_linear = 0
1051 value = value_quad + reg * nx.sum(plan * nx.log(plan + 1e-16))
1052 # potentials = (log['log_u'], log['log_v']) #TODO
1053
1054 elif (
1055 reg_type.lower() in ["entropy"] and M is not None and alpha == 0
1056 ): # Entropic Wasserstein problem
1057 # default values for solver
1058 if max_iter is None:
1059 max_iter = 1000
1060 if tol is None:
1061 tol = 1e-9
1062
1063 plan, log = sinkhorn_log(
1064 a,
1065 b,
1066 M,
1067 reg=reg,
1068 numItermax=max_iter,
1069 stopThr=tol,
1070 log=True,
1071 verbose=verbose,
1072 )
1073
1074 value_linear = nx.sum(M * plan)
1075 value = value_linear + reg * nx.sum(plan * nx.log(plan + 1e-16))
1076 potentials = (log["log_u"], log["log_v"])
1077
1078 elif (
1079 reg_type.lower() in ["entropy"] and M is not None
1080 ): # Entropic Fused Gromov-Wasserstein problem
1081 # default values for solver
1082 if max_iter is None:
1083 max_iter = 1000
1084 if tol is None:
1085 tol = 1e-9
1086 if method is None:
1087 method = "PGD"
1088
1089 value_noreg, log = entropic_fused_gromov_wasserstein2(
1090 M,
1091 Ca,
1092 Cb,
1093 a,
1094 b,
1095 loss_fun=loss_fun,
1096 alpha=alpha,
1097 log=True,
1098 symmetric=symmetric,
1099 solver=method,
1100 max_iter=max_iter,
1101 G0=plan_init,
1102 tol_rel=tol,
1103 tol_abs=tol,
1104 verbose=verbose,
1105 )
1106
1107 value_linear = log["lin_loss"]
1108 value_quad = log["quad_loss"]
1109 plan = log["T"]
1110 # potentials = (log['u'], log['v'])
1111 value = value_noreg + reg * nx.sum(plan * nx.log(plan + 1e-16))
1112
1113 else:
1114 raise (
1115 NotImplementedError(
1116 'Not implemented reg_type="{}"'.format(reg_type)
1117 )
1118 )
1119
1120 elif unbalanced_type.lower() in ["semirelaxed"]: # Semi-relaxed OT
1121 if reg_type.lower() in ["entropy"] and (
1122 M is None or alpha == 1
1123 ): # Entropic Semi-relaxed Gromov-Wasserstein problem
1124 # default values for solver
1125 if max_iter is None:
1126 max_iter = 1000
1127 if tol is None:
1128 tol = 1e-9
1129
1130 value_quad, log = entropic_semirelaxed_gromov_wasserstein2(
1131 Ca,
1132 Cb,
1133 a,
1134 epsilon=reg,
1135 loss_fun=loss_fun,
1136 log=True,
1137 symmetric=symmetric,
1138 max_iter=max_iter,
1139 G0=plan_init,
1140 tol=tol,
1141 verbose=verbose,
1142 )
1143
1144 plan = log["T"]
1145 value_linear = 0
1146 value = value_quad + reg * nx.sum(plan * nx.log(plan + 1e-16))
1147
1148 else: # Entropic Semi-relaxed FGW problem
1149 # default values for solver
1150 if max_iter is None:
1151 max_iter = 1000
1152 if tol is None:
1153 tol = 1e-9
1154
1155 value_noreg, log = entropic_semirelaxed_fused_gromov_wasserstein2(
1156 M,
1157 Ca,
1158 Cb,
1159 a,
1160 loss_fun=loss_fun,
1161 alpha=alpha,
1162 log=True,
1163 symmetric=symmetric,
1164 max_iter=max_iter,
1165 G0=plan_init,
1166 tol=tol,
1167 verbose=verbose,
1168 )
1169
1170 value_linear = log["lin_loss"]
1171 value_quad = log["quad_loss"]
1172 plan = log["T"]
1173 value = value_noreg + reg * nx.sum(plan * nx.log(plan + 1e-16))
1174
1175 elif unbalanced_type.lower() in ["partial"]: # Partial OT
1176 if M is None: # Partial Gromov-Wasserstein problem
1177 if unbalanced > nx.sum(a) or unbalanced > nx.sum(b):
1178 raise (ValueError("Partial GW mass given in reg is too large"))
1179
1180 # default values for solver
1181 if max_iter is None:
1182 max_iter = 1000
1183 if tol is None:
1184 tol = 1e-7
1185
1186 value_quad, log = entropic_partial_gromov_wasserstein2(
1187 Ca,
1188 Cb,
1189 a,
1190 b,
1191 reg=reg,
1192 loss_fun=loss_fun,
1193 m=unbalanced,
1194 log=True,
1195 numItermax=max_iter,
1196 G0=plan_init,
1197 tol=tol,
1198 symmetric=symmetric,
1199 verbose=verbose,
1200 )
1201
1202 value_quad = value
1203 plan = log["T"]
1204 # potentials = (log['u'], log['v']) TODO
1205
1206 else: # partial FGW
1207 raise (NotImplementedError("Partial entropic FGW not implemented yet"))
1208
1209 else: # unbalanced AND regularized OT
1210 raise (
1211 NotImplementedError(
1212 'Not implemented reg_type="{}" and unbalanced_type="{}"'.format(
1213 reg_type, unbalanced_type
1214 )
1215 )
1216 )
1217
1218 res = OTResult(
1219 potentials=potentials,
1220 value=value,
1221 value_linear=value_linear,
1222 value_quad=value_quad,
1223 plan=plan,
1224 status=status,
1225 backend=nx,
1226 log=log,
1227 )
1228
1229 return res
1230
1231
1232 def solve_sample(
1233 X_a,
1234 X_b,
1235 a=None,
1236 b=None,
1237 metric="sqeuclidean",
1238 reg=None,
1239 c=None,
1240 reg_type="KL",
1241 unbalanced=None,
1242 unbalanced_type="KL",
1243 lazy=False,
1244 batch_size=None,
1245 method=None,
1246 n_threads=1,
1247 max_iter=None,
1248 plan_init=None,
1249 rank=100,
1250 scaling=0.95,
1251 potentials_init=None,
1252 X_init=None,
1253 tol=None,
1254 verbose=False,
1255 grad="autodiff",
1256 ):
1257 r"""Solve the discrete optimal transport problem using the samples in the source and target domains.
1258
1259 The function solves the following general optimal transport problem
1260
1261 .. math::
1262 \min_{\mathbf{T}\geq 0} \quad \sum_{i,j} T_{i,j}M_{i,j} + \lambda_r R(\mathbf{T}) +
1263 \lambda_u U(\mathbf{T}\mathbf{1},\mathbf{a}) +
1264 \lambda_u U(\mathbf{T}^T\mathbf{1},\mathbf{b})
1265
1266 where the cost matrix :math:`\mathbf{M}` is computed from the samples in the
1267 source and target domains such that :math:`M_{i,j} = d(x_i,y_j)` where
1268 :math:`d` is a metric (by default the squared Euclidean distance).
1269
1270 The regularization is selected with `reg` (:math:`\lambda_r`) and `reg_type`. By
1271 default ``reg=None`` and there is no regularization. The unbalanced marginal
1272 penalization can be selected with `unbalanced` (:math:`\lambda_u`) and
1273 `unbalanced_type`. By default ``unbalanced=None`` and the function
1274 solves the exact optimal transport problem (respecting the marginals).
1275
1276 Parameters
1277 ----------
1278 X_s : array-like, shape (n_samples_a, dim)
1279 samples in the source domain
1280 X_t : array-like, shape (n_samples_b, dim)
1281 samples in the target domain
1282 a : array-like, shape (dim_a,), optional
1283 Samples weights in the source domain (default is uniform)
1284 b : array-like, shape (dim_b,), optional
1285 Samples weights in the source domain (default is uniform)
1286 reg : float, optional
1287 Regularization weight :math:`\lambda_r`, by default None (no reg., exact
1288 OT)
1289 c : array-like (dim_a, dim_b), optional (default=None)
1290 Reference measure for the regularization.
1291 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
1292 If :math:`\texttt{reg_type}='entropy'`, then :math:`\mathbf{c} = 1_{dim_a} 1_{dim_b}^T`.
1293 reg_type : str, optional
1294 Type of regularization :math:`R` either "KL", "L2", "entropy", by default "KL"
1295 unbalanced : float or indexable object of length 1 or 2
1296 Marginal relaxation term.
1297 If it is a scalar or an indexable object of length 1,
1298 then the same relaxation is applied to both marginal relaxations.
1299 The balanced OT can be recovered using :math:`unbalanced=float("inf")`.
1300 For semi-relaxed case, use either
1301 :math:`unbalanced=(float("inf"), scalar)` or
1302 :math:`unbalanced=(scalar, float("inf"))`.
1303 If unbalanced is an array,
1304 it must have the same backend as input arrays `(a, b, M)`.
1305 unbalanced_type : str, optional
1306 Type of unbalanced penalization function :math:`U` either "KL", "L2", "TV", by default "KL"
1307 lazy : bool, optional
1308 Return :any:`OTResultlazy` object to reduce memory cost when True, by
1309 default False
1310 batch_size : int, optional
1311 Batch size for lazy solver, by default None (default values in each
1312 solvers)
1313 method : str, optional
1314 Method for solving the problem, this can be used to select the solver
1315 for unbalanced problems (see :any:`ot.solve`), or to select a specific
1316 large scale solver.
1317 n_threads : int, optional
1318 Number of OMP threads for exact OT solver, by default 1
1319 max_iter : int, optional
1320 Maximum number of iteration, by default None (default values in each solvers)
1321 plan_init : array_like, shape (dim_a, dim_b), optional
1322 Initialization of the OT plan for iterative methods, by default None
1323 rank : int, optional
1324 Rank of the OT matrix for lazy solers (method='factored'), by default 100
1325 scaling : float, optional
1326 Scaling factor for the epsilon scaling lazy solvers (method='geomloss'), by default 0.95
1327 potentials_init : (array_like(dim_a,),array_like(dim_b,)), optional
1328 Initialization of the OT dual potentials for iterative methods, by default None
1329 tol : _type_, optional
1330 Tolerance for solution precision, by default None (default values in each solvers)
1331 verbose : bool, optional
1332 Print information in the solver, by default False
1333 grad : str, optional
1334 Type of gradient computation, either or 'autodiff' or 'envelope' used only for
1335 Sinkhorn solver. By default 'autodiff' provides gradients wrt all
1336 outputs (`plan, value, value_linear`) but with important memory cost.
1337 'envelope' provides gradients only for `value` and and other outputs are
1338 detached. This is useful for memory saving when only the value is needed.
1339
1340 Returns
1341 -------
1342
1343 res : OTResult()
1344 Result of the optimization problem. The information can be obtained as follows:
1345
1346 - res.plan : OT plan :math:`\mathbf{T}`
1347 - res.potentials : OT dual potentials
1348 - res.value : Optimal value of the optimization problem
1349 - res.value_linear : Linear OT loss with the optimal OT plan
1350 - res.lazy_plan : Lazy OT plan (when ``lazy=True`` or lazy method)
1351
1352 See :any:`OTResult` for more information.
1353
1354 Notes
1355 -----
1356
1357 The following methods are available for solving the OT problems:
1358
1359 - **Classical exact OT problem [1]** (default parameters) :
1360
1361 .. math::
1362 \min_\mathbf{T} \quad \langle \mathbf{T}, \mathbf{M} \rangle_F
1363
1364 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
1365
1366 \mathbf{T}^T \mathbf{1} = \mathbf{b}
1367
1368 \mathbf{T} \geq 0, M_{i,j} = d(x_i,y_j)
1369
1370
1371
1372 can be solved with the following code:
1373
1374 .. code-block:: python
1375
1376 res = ot.solve_sample(xa, xb, a, b)
1377
1378 # for uniform weights
1379 res = ot.solve_sample(xa, xb)
1380
1381 - **Entropic regularized OT [2]** (when ``reg!=None``):
1382
1383 .. math::
1384 \min_\mathbf{T} \quad \langle \mathbf{T}, \mathbf{M} \rangle_F + \lambda R(\mathbf{T})
1385
1386 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
1387
1388 \mathbf{T}^T \mathbf{1} = \mathbf{b}
1389
1390 \mathbf{T} \geq 0, M_{i,j} = d(x_i,y_j)
1391
1392 can be solved with the following code:
1393
1394 .. code-block:: python
1395
1396 # default is ``"KL"`` regularization (``reg_type="KL"``)
1397 res = ot.solve_sample(xa, xb, a, b, reg=1.0)
1398 # or for original Sinkhorn paper formulation [2]
1399 res = ot.solve_sample(xa, xb, a, b, reg=1.0, reg_type='entropy')
1400
1401 # lazy solver of memory complexity O(n)
1402 res = ot.solve_sample(xa, xb, a, b, reg=1.0, lazy=True, batch_size=100)
1403 # lazy OT plan
1404 lazy_plan = res.lazy_plan
1405
1406 # Use envelope theorem differentiation for memory saving
1407 res = ot.solve_sample(xa, xb, a, b, reg=1.0, grad='envelope')
1408 res.value.backward() # only the value is differentiable
1409
1410 Note that by default the Sinkhorn solver uses automatic differentiation to
1411 compute the gradients of the values and plan. This can be changed with the
1412 `grad` parameter. The `envelope` mode computes the gradients only
1413 for the value and the other outputs are detached. This is useful for
1414 memory saving when only the gradient of value is needed.
1415
1416 We also have a very efficient solver with compiled CPU/CUDA code using
1417 geomloss/PyKeOps that can be used with the following code:
1418
1419 .. code-block:: python
1420
1421 # automatic solver
1422 res = ot.solve_sample(xa, xb, a, b, reg=1.0, method='geomloss')
1423
1424 # force O(n) memory efficient solver
1425 res = ot.solve_sample(xa, xb, a, b, reg=1.0, method='geomloss_online')
1426
1427 # force pre-computed cost matrix
1428 res = ot.solve_sample(xa, xb, a, b, reg=1.0, method='geomloss_tensorized')
1429
1430 # use multiscale solver
1431 res = ot.solve_sample(xa, xb, a, b, reg=1.0, method='geomloss_multiscale')
1432
1433 # One can play with speed (small scaling factor) and precision (scaling close to 1)
1434 res = ot.solve_sample(xa, xb, a, b, reg=1.0, method='geomloss', scaling=0.5)
1435
1436 - **Quadratic regularized OT [17]** (when ``reg!=None`` and ``reg_type="L2"``):
1437
1438 .. math::
1439 \min_\mathbf{T} \quad \langle \mathbf{T}, \mathbf{M} \rangle_F + \lambda R(\mathbf{T})
1440
1441 s.t. \ \mathbf{T} \mathbf{1} = \mathbf{a}
1442
1443 \mathbf{T}^T \mathbf{1} = \mathbf{b}
1444
1445 \mathbf{T} \geq 0, M_{i,j} = d(x_i,y_j)
1446
1447 can be solved with the following code:
1448
1449 .. code-block:: python
1450
1451 res = ot.solve_sample(xa, xb, a, b, reg=1.0, reg_type='L2')
1452
1453 - **Unbalanced OT [41]** (when ``unbalanced!=None``):
1454
1455 .. math::
1456 \min_{\mathbf{T}\geq 0} \quad \sum_{i,j} T_{i,j}M_{i,j} + \lambda_u U(\mathbf{T}\mathbf{1},\mathbf{a}) + \lambda_u U(\mathbf{T}^T\mathbf{1},\mathbf{b})
1457
1458 with M_{i,j} = d(x_i,y_j)
1459
1460 can be solved with the following code:
1461
1462 .. code-block:: python
1463
1464 # default is ``"KL"``
1465 res = ot.solve_sample(xa, xb, a, b, unbalanced=1.0)
1466 # quadratic unbalanced OT
1467 res = ot.solve_sample(xa, xb, a, b, unbalanced=1.0,unbalanced_type='L2')
1468 # TV = partial OT
1469 res = ot.solve_sample(xa, xb, a, b, unbalanced=1.0,unbalanced_type='TV')
1470
1471
1472 - **Regularized unbalanced regularized OT [34]** (when ``unbalanced!=None`` and ``reg!=None``):
1473
1474 .. math::
1475 \min_{\mathbf{T}\geq 0} \quad \sum_{i,j} T_{i,j}M_{i,j} + \lambda_r R(\mathbf{T}) + \lambda_u U(\mathbf{T}\mathbf{1},\mathbf{a}) + \lambda_u U(\mathbf{T}^T\mathbf{1},\mathbf{b})
1476
1477 with M_{i,j} = d(x_i,y_j)
1478
1479 can be solved with the following code:
1480
1481 .. code-block:: python
1482
1483 # default is ``"KL"`` for both
1484 res = ot.solve_sample(xa, xb, a, b, reg=1.0, unbalanced=1.0)
1485 # quadratic unbalanced OT with KL regularization
1486 res = ot.solve_sample(xa, xb, a, b, reg=1.0, unbalanced=1.0,unbalanced_type='L2')
1487 # both quadratic
1488 res = ot.solve_sample(xa, xb, a, b, reg=1.0, reg_type='L2',
1489 unbalanced=1.0, unbalanced_type='L2')
1490
1491
1492 - **Factored OT [2]** (when ``method='factored'``):
1493
1494 This method solve the following OT problem [40]_
1495
1496 .. math::
1497 \mathop{\arg \min}_\mu \quad W_2^2(\mu_a,\mu)+ W_2^2(\mu,\mu_b)
1498
1499 where $\mu$ is a uniform weighted empirical distribution of :math:`\mu_a` and :math:`\mu_b` are the empirical measures associated
1500 to the samples in the source and target domains, and :math:`W_2` is the
1501 Wasserstein distance. This problem is solved using exact OT solvers for
1502 `reg=None` and the Sinkhorn solver for `reg!=None`. The solution provides
1503 two transport plans that can be used to recover a low rank OT plan between
1504 the two distributions.
1505
1506 .. code-block:: python
1507
1508 res = ot.solve_sample(xa, xb, method='factored', rank=10)
1509
1510 # recover the lazy low rank plan
1511 factored_solution_lazy = res.lazy_plan
1512
1513 # recover the full low rank plan
1514 factored_solution = factored_solution_lazy[:]
1515
1516 - **Gaussian Bures-Wasserstein [2]** (when ``method='gaussian'``):
1517
1518 This method computes the Gaussian Bures-Wasserstein distance between two
1519 Gaussian distributions estimated from the empirical distributions
1520
1521 .. math::
1522 \mathcal{W}(\mu_s, \mu_t)_2^2= \left\lVert \mathbf{m}_s - \mathbf{m}_t \right\rVert^2 + \mathcal{B}(\Sigma_s, \Sigma_t)^{2}
1523
1524 where :
1525
1526 .. math::
1527 \mathbf{B}(\Sigma_s, \Sigma_t)^{2} = \text{Tr}\left(\Sigma_s + \Sigma_t - 2 \sqrt{\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2}} \right)
1528
1529 The covariances and means are estimated from the data.
1530
1531 .. code-block:: python
1532
1533 res = ot.solve_sample(xa, xb, method='gaussian')
1534
1535 # recover the squared Gaussian Bures-Wasserstein distance
1536 BW_dist = res.value
1537
1538 - **Wasserstein 1d [1]** (when ``method='1D'``):
1539
1540 This method computes the Wasserstein distance between two 1d distributions
1541 estimated from the empirical distributions. For multivariate data the
1542 distances are computed independently for each dimension.
1543
1544 .. code-block:: python
1545
1546 res = ot.solve_sample(xa, xb, method='1D')
1547
1548 # recover the squared Wasserstein distances
1549 W_dists = res.value
1550
1551
1552 .. _references-solve-sample:
1553 References
1554 ----------
1555
1556 .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W.
1557 (2011, December). Displacement interpolation using Lagrangian mass
1558 transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p.
1559 158). ACM.
1560
1561 .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation
1562 of Optimal Transport, Advances in Neural Information Processing
1563 Systems (NIPS) 26, 2013
1564
1565 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
1566 Scaling algorithms for unbalanced transport problems.
1567 arXiv preprint arXiv:1607.05816.
1568
1569 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse
1570 Optimal Transport. Proceedings of the Twenty-First International
1571 Conference on Artificial Intelligence and Statistics (AISTATS).
1572
1573 .. [34] Feydy, J., Séjourné, T., Vialard, F. X., Amari, S. I., Trouvé,
1574 A., & Peyré, G. (2019, April). Interpolating between optimal transport
1575 and MMD using Sinkhorn divergences. In The 22nd International Conference
1576 on Artificial Intelligence and Statistics (pp. 2681-2690). PMLR.
1577
1578 .. [40] Forrow, A., Hütter, J. C., Nitzan, M., Rigollet, P., Schiebinger,
1579 G., & Weed, J. (2019, April). Statistical optimal transport via factored
1580 couplings. In The 22nd International Conference on Artificial
1581 Intelligence and Statistics (pp. 2454-2465). PMLR.
1582
1583 .. [41] Chapel, L., Flamary, R., Wu, H., Févotte, C., and Gasso, G. (2021).
1584 Unbalanced optimal transport through non-negative penalized
1585 linear regression. NeurIPS.
1586
1587 .. [65] Scetbon, M., Cuturi, M., & Peyré, G. (2021).
1588 Low-rank Sinkhorn Factorization. In International Conference on
1589 Machine Learning.
1590
1591
1592 """
1593
1594 if method is not None and method.lower() in lst_method_lazy:
1595 lazy0 = lazy
1596 lazy = True
1597
1598 if not lazy: # default non lazy solver calls ot.solve
1599 # compute cost matrix M and use solve function
1600 M = dist(X_a, X_b, metric)
1601
1602 res = solve(
1603 M,
1604 a,
1605 b,
1606 reg,
1607 c,
1608 reg_type,
1609 unbalanced,
1610 unbalanced_type,
1611 method,
1612 n_threads,
1613 max_iter,
1614 plan_init,
1615 potentials_init,
1616 tol,
1617 verbose,
1618 grad,
1619 )
1620
1621 return res
1622
1623 else:
1624 # Detect backend
1625 nx = get_backend(X_a, X_b, a, b)
1626
1627 # default values for solutions
1628 potentials = None
1629 value = None
1630 value_linear = None
1631 plan = None
1632 lazy_plan = None
1633 status = None
1634 log = None
1635
1636 method = method.lower() if method is not None else ""
1637
1638 if method == "1d": # Wasserstein 1d (parallel on all dimensions)
1639 if metric == "sqeuclidean":
1640 p = 2
1641 elif metric in ["euclidean", "cityblock"]:
1642 p = 1
1643 else:
1644 raise (
1645 NotImplementedError('Not implemented metric="{}"'.format(metric))
1646 )
1647
1648 value = wasserstein_1d(X_a, X_b, a, b, p=p)
1649 value_linear = value
1650
1651 elif method == "gaussian": # Gaussian Bures-Wasserstein
1652 if metric.lower() not in ["sqeuclidean"]:
1653 raise (
1654 NotImplementedError('Not implemented metric="{}"'.format(metric))
1655 )
1656
1657 if reg is None:
1658 reg = 1e-6
1659
1660 value, log = empirical_bures_wasserstein_distance(
1661 X_a, X_b, reg=reg, log=True
1662 )
1663 value = value**2 # return the value (squared bures distance)
1664 value_linear = value # return the value
1665
1666 elif method == "factored": # Factored OT
1667 if metric.lower() not in ["sqeuclidean"]:
1668 raise (
1669 NotImplementedError('Not implemented metric="{}"'.format(metric))
1670 )
1671
1672 if max_iter is None:
1673 max_iter = 100
1674 if tol is None:
1675 tol = 1e-7
1676 if reg is None:
1677 reg = 0
1678
1679 Q, R, X, log = factored_optimal_transport(
1680 X_a,
1681 X_b,
1682 reg=reg,
1683 r=rank,
1684 log=True,
1685 stopThr=tol,
1686 numItermax=max_iter,
1687 verbose=verbose,
1688 )
1689 log["X"] = X
1690
1691 value_linear = log["costa"] + log["costb"]
1692 value = value_linear # TODO add reg term
1693 lazy_plan = log["lazy_plan"]
1694 if not lazy0: # store plan if not lazy
1695 plan = lazy_plan[:]
1696
1697 elif method == "lowrank":
1698 if metric.lower() not in ["sqeuclidean"]:
1699 raise (
1700 NotImplementedError('Not implemented metric="{}"'.format(metric))
1701 )
1702
1703 if max_iter is None:
1704 max_iter = 2000
1705 if tol is None:
1706 tol = 1e-7
1707 if reg is None:
1708 reg = 0
1709
1710 Q, R, g, log = lowrank_sinkhorn(
1711 X_a,
1712 X_b,
1713 rank=rank,
1714 reg=reg,
1715 a=a,
1716 b=b,
1717 numItermax=max_iter,
1718 stopThr=tol,
1719 log=True,
1720 )
1721 value = log["value"]
1722 value_linear = log["value_linear"]
1723 lazy_plan = log["lazy_plan"]
1724 if not lazy0: # store plan if not lazy
1725 plan = lazy_plan[:]
1726
1727 elif method.startswith("geomloss"): # Geomloss solver for entropic OT
1728 split_method = method.split("_")
1729 if len(split_method) == 2:
1730 backend = split_method[1]
1731 else:
1732 if lazy0 is None:
1733 backend = "auto"
1734 elif lazy0:
1735 backend = "online"
1736 else:
1737 backend = "tensorized"
1738
1739 value, log = empirical_sinkhorn2_geomloss(
1740 X_a,
1741 X_b,
1742 reg=reg,
1743 a=a,
1744 b=b,
1745 metric=metric,
1746 log=True,
1747 verbose=verbose,
1748 scaling=scaling,
1749 backend=backend,
1750 )
1751
1752 lazy_plan = log["lazy_plan"]
1753 if not lazy0: # store plan if not lazy
1754 plan = lazy_plan[:]
1755
1756 # return scaled potentials (to be consistent with other solvers)
1757 potentials = (
1758 log["f"] / (lazy_plan.blur**2),
1759 log["g"] / (lazy_plan.blur**2),
1760 )
1761
1762 elif reg is None or reg == 0: # exact OT
1763 if unbalanced is None: # balanced EMD solver not available for lazy
1764 raise (
1765 NotImplementedError(
1766 "Exact OT solver with lazy=True not implemented"
1767 )
1768 )
1769
1770 else:
1771 raise (
1772 NotImplementedError(
1773 'Non regularized solver with unbalanced_type="{}" not implemented'.format(
1774 unbalanced_type
1775 )
1776 )
1777 )
1778
1779 else:
1780 if unbalanced is None:
1781 if max_iter is None:
1782 max_iter = 1000
1783 if tol is None:
1784 tol = 1e-9
1785 if batch_size is None:
1786 batch_size = 100
1787
1788 value_linear, log = empirical_sinkhorn2(
1789 X_a,
1790 X_b,
1791 reg,
1792 a,
1793 b,
1794 metric=metric,
1795 numIterMax=max_iter,
1796 stopThr=tol,
1797 isLazy=True,
1798 batchSize=batch_size,
1799 verbose=verbose,
1800 log=True,
1801 )
1802 # compute potentials
1803 potentials = (log["u"], log["v"])
1804 lazy_plan = log["lazy_plan"]
1805
1806 else:
1807 raise (
1808 NotImplementedError(
1809 'Not implemented unbalanced_type="{}" with regularization'.format(
1810 unbalanced_type
1811 )
1812 )
1813 )
1814
1815 res = OTResult(
1816 potentials=potentials,
1817 value=value,
1818 lazy_plan=lazy_plan,
1819 value_linear=value_linear,
1820 plan=plan,
1821 status=status,
1822 backend=nx,
1823 log=log,
1824 )
1825 return res