Debian Codegraph @

ot/unbalanced/_sinkhorn.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Regularized Unbalanced OT solvers
4 """
5
6 # Author: Hicham Janati <[email protected]>
7 # Laetitia Chapel <[email protected]>
8 # Quang Huy Tran <[email protected]>
9 #
10 # License: MIT License
11
12 from __future__ import division
13 import warnings
14
15 from ..backend import get_backend
16 from ..utils import list_to_array, get_parameter_pair
17
18
19 def sinkhorn_unbalanced(
20 a,
21 b,
22 M,
23 reg,
24 reg_m,
25 method="sinkhorn",
26 reg_type="kl",
27 c=None,
28 warmstart=None,
29 numItermax=1000,
30 stopThr=1e-6,
31 verbose=False,
32 log=False,
33 **kwargs,
34 ):
35 r"""
36 Solve the unbalanced entropic regularization optimal transport problem
37 and return the OT plan
38
39 The function solves the following optimization problem:
40
41 .. math::
42 W = \arg \min_\gamma \ \langle \gamma, \mathbf{M} \rangle_F +
43 \mathrm{reg} \cdot \mathrm{KL}(\gamma, \mathbf{c}) +
44 \mathrm{reg_{m1}} \cdot \mathrm{KL}(\gamma \mathbf{1}, \mathbf{a}) +
45 \mathrm{reg_{m2}} \cdot \mathrm{KL}(\gamma^T \mathbf{1}, \mathbf{b})
46
47 s.t.
48 \gamma \geq 0
49
50 where :
51
52 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
53 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
54 - :math:`\mathbf{c}` is a reference distribution for the regularization
55 - KL is the Kullback-Leibler divergence
56
57 The algorithm used for solving the problem is the generalized
58 Sinkhorn-Knopp matrix scaling algorithm as proposed in :ref:`[10, 25] <references-sinkhorn-unbalanced>`
59
60
61 Parameters
62 ----------
63 a : array-like (dim_a,)
64 Unnormalized histogram of dimension `dim_a`
65 If `a` is an empty list or array ([]),
66 then `a` is set to uniform distribution.
67 b : array-like (dim_b,)
68 One or multiple unnormalized histograms of dimension `dim_b`.
69 If `b` is an empty list or array ([]),
70 then `b` is set to uniform distribution.
71 If many, compute all the OT costs :math:`(\mathbf{a}, \mathbf{b}_i)_i`
72 M : array-like (dim_a, dim_b)
73 loss matrix
74 reg : float
75 Entropy regularization term > 0
76 reg_m: float or indexable object of length 1 or 2
77 Marginal relaxation term.
78 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
79 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
80 The entropic balanced OT can be recovered using :math:`\mathrm{reg_{m}}=float("inf")`.
81 For semi-relaxed case, use either
82 :math:`\mathrm{reg_{m}}=(float("inf"), scalar)` or
83 :math:`\mathrm{reg_{m}}=(scalar, float("inf"))`.
84 If :math:`\mathrm{reg_{m}}` is an array,
85 it must have the same backend as input arrays `(a, b, M)`.
86 method : str
87 method used for the solver either 'sinkhorn', 'sinkhorn_stabilized', 'sinkhorn_translation_invariant' or
88 'sinkhorn_reg_scaling', see those function for specific parameters
89 reg_type : string, optional
90 Regularizer term. Can take two values:
91 + Negative entropy: 'entropy':
92 :math:`\Omega(\gamma) = \sum_{i,j} \gamma_{i,j} \log(\gamma_{i,j}) - \sum_{i,j} \gamma_{i,j}`.
93 This is equivalent (up to a constant) to :math:`\Omega(\gamma) = \text{KL}(\gamma, 1_{dim_a} 1_{dim_b}^T)`.
94 + Kullback-Leibler divergence: 'kl':
95 :math:`\Omega(\gamma) = \text{KL}(\gamma, \mathbf{a} \mathbf{b}^T)`.
96 c : array-like (dim_a, dim_b), optional (default=None)
97 Reference measure for the regularization.
98 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
99 If :math:`\texttt{reg_type}='entropy'`, then :math:`\mathbf{c} = 1_{dim_a} 1_{dim_b}^T`.
100 warmstart: tuple of arrays, shape (dim_a, dim_b), optional
101 Initialization of dual potentials. If provided, the dual potentials should be given
102 (that is the logarithm of the `u`, `v` sinkhorn scaling vectors).
103 numItermax : int, optional
104 Max number of iterations
105 stopThr : float, optional
106 Stop threshold on error (>0)
107 verbose : bool, optional
108 Print information along iterations
109 log : bool, optional
110 record `log` if `True`
111
112
113 Returns
114 -------
115 if n_hists == 1:
116 - gamma : (dim_a, dim_b) array-like
117 Optimal transportation matrix for the given parameters
118 - log : dict
119 log dictionary returned only if `log` is `True`
120 else:
121 - ot_distance : (n_hists,) array-like
122 the OT distance between :math:`\mathbf{a}` and each of the histograms :math:`\mathbf{b}_i`
123 - log : dict
124 log dictionary returned only if `log` is `True`
125
126 Examples
127 --------
128
129 >>> import ot
130 >>> import numpy as np
131 >>> a=[.5, .5]
132 >>> b=[.5, .5]
133 >>> M=[[0., 1.], [1., 0.]]
134 >>> np.round(ot.sinkhorn_unbalanced(a, b, M, 1, 1), 7)
135 array([[0.3220536, 0.1184769],
136 [0.1184769, 0.3220536]])
137
138 .. _references-sinkhorn-unbalanced:
139 References
140 ----------
141 .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal
142 Transport, Advances in Neural Information Processing Systems
143 (NIPS) 26, 2013
144
145 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for
146 Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
147
148 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
149 Scaling algorithms for unbalanced transport problems. arXiv preprint
150 arXiv:1607.05816.
151
152 .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
153 Learning with a Wasserstein Loss, Advances in Neural Information
154 Processing Systems (NIPS) 2015
155
156 .. [73] Séjourné, T., Vialard, F. X., & Peyré, G. (2022).
157 Faster unbalanced optimal transport: Translation invariant sinkhorn and 1-d frank-wolfe.
158 In International Conference on Artificial Intelligence and Statistics (pp. 4995-5021). PMLR.
159
160
161 See Also
162 --------
163 ot.unbalanced.sinkhorn_knopp_unbalanced: Unbalanced Classic Sinkhorn :ref:`[10] <references-sinkhorn-unbalanced>`
164 ot.unbalanced.sinkhorn_stabilized_unbalanced:
165 Unbalanced Stabilized sinkhorn :ref:`[9, 10] <references-sinkhorn-unbalanced>`
166 ot.unbalanced.sinkhorn_reg_scaling_unbalanced:
167 Unbalanced Sinkhorn with epsilon scaling :ref:`[9, 10] <references-sinkhorn-unbalanced>`
168 ot.unbalanced.sinkhorn_unbalanced_translation_invariant:
169 Translation Invariant Unbalanced Sinkhorn :ref:`[73] <references-sinkhorn-unbalanced-translation-invariant>`
170
171 """
172
173 if method.lower() == "sinkhorn":
174 return sinkhorn_knopp_unbalanced(
175 a,
176 b,
177 M,
178 reg,
179 reg_m,
180 reg_type,
181 c,
182 warmstart,
183 numItermax=numItermax,
184 stopThr=stopThr,
185 verbose=verbose,
186 log=log,
187 **kwargs,
188 )
189
190 elif method.lower() == "sinkhorn_stabilized":
191 return sinkhorn_stabilized_unbalanced(
192 a,
193 b,
194 M,
195 reg,
196 reg_m,
197 reg_type,
198 c,
199 warmstart,
200 numItermax=numItermax,
201 stopThr=stopThr,
202 verbose=verbose,
203 log=log,
204 **kwargs,
205 )
206
207 elif method.lower() == "sinkhorn_translation_invariant":
208 return sinkhorn_unbalanced_translation_invariant(
209 a,
210 b,
211 M,
212 reg,
213 reg_m,
214 reg_type,
215 c,
216 warmstart,
217 numItermax=numItermax,
218 stopThr=stopThr,
219 verbose=verbose,
220 log=log,
221 **kwargs,
222 )
223
224 elif method.lower() in ["sinkhorn_reg_scaling"]:
225 warnings.warn("Method not implemented yet. Using classic Sinkhorn-Knopp")
226 return sinkhorn_knopp_unbalanced(
227 a,
228 b,
229 M,
230 reg,
231 reg_m,
232 reg_type,
233 c,
234 warmstart,
235 numItermax=numItermax,
236 stopThr=stopThr,
237 verbose=verbose,
238 log=log,
239 **kwargs,
240 )
241 else:
242 raise ValueError("Unknown method '%s'." % method)
243
244
245 def sinkhorn_unbalanced2(
246 a,
247 b,
248 M,
249 reg,
250 reg_m,
251 method="sinkhorn",
252 reg_type="kl",
253 c=None,
254 warmstart=None,
255 returnCost="linear",
256 numItermax=1000,
257 stopThr=1e-6,
258 verbose=False,
259 log=False,
260 **kwargs,
261 ):
262 r"""
263 Solve the entropic regularization unbalanced optimal transport problem and
264 return the cost
265
266 The function solves the following optimization problem:
267
268 .. math::
269 \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
270 \mathrm{reg} \cdot \mathrm{KL}(\gamma, \mathbf{c}) +
271 \mathrm{reg_{m1}} \cdot \mathrm{KL}(\gamma \mathbf{1}, \mathbf{a}) +
272 \mathrm{reg_{m2}} \cdot \mathrm{KL}(\gamma^T \mathbf{1}, \mathbf{b})
273
274 s.t.
275 \gamma\geq 0
276 where :
277
278 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
279 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
280 - :math:`\mathbf{c}` is a reference distribution for the regularization
281 - KL is the Kullback-Leibler divergence
282
283 The algorithm used for solving the problem is the generalized
284 Sinkhorn-Knopp matrix scaling algorithm as proposed in :ref:`[10, 25] <references-sinkhorn-unbalanced2>`
285
286
287 Parameters
288 ----------
289 a : array-like (dim_a,)
290 Unnormalized histogram of dimension `dim_a`
291 If `a` is an empty list or array ([]),
292 then `a` is set to uniform distribution.
293 b : array-like (dim_b,)
294 One or multiple unnormalized histograms of dimension `dim_b`.
295 If `b` is an empty list or array ([]),
296 then `b` is set to uniform distribution.
297 If many, compute all the OT costs :math:`(\mathbf{a}, \mathbf{b}_i)_i`
298 M : array-like (dim_a, dim_b)
299 loss matrix
300 reg : float
301 Entropy regularization term > 0
302 reg_m: float or indexable object of length 1 or 2
303 Marginal relaxation term.
304 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
305 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
306 The entropic balanced OT can be recovered using :math:`\mathrm{reg_{m}}=float("inf")`.
307 For semi-relaxed case, use either
308 :math:`\mathrm{reg_{m}}=(float("inf"), scalar)` or
309 :math:`\mathrm{reg_{m}}=(scalar, float("inf"))`.
310 If :math:`\mathrm{reg_{m}}` is an array,
311 it must have the same backend as input arrays `(a, b, M)`.
312 method : str
313 method used for the solver either 'sinkhorn', 'sinkhorn_stabilized', 'sinkhorn_translation_invariant' or
314 'sinkhorn_reg_scaling', see those function for specific parameters
315 reg_type : string, optional
316 Regularizer term. Can take two values:
317 + Negative entropy: 'entropy':
318 :math:`\Omega(\gamma) = \sum_{i,j} \gamma_{i,j} \log(\gamma_{i,j}) - \sum_{i,j} \gamma_{i,j}`.
319 This is equivalent (up to a constant) to :math:`\Omega(\gamma) = \text{KL}(\gamma, 1_{dim_a} 1_{dim_b}^T)`.
320 + Kullback-Leibler divergence: 'kl':
321 :math:`\Omega(\gamma) = \text{KL}(\gamma, \mathbf{a} \mathbf{b}^T)`.
322 c : array-like (dim_a, dim_b), optional (default=None)
323 Reference measure for the regularization.
324 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
325 If :math:`\texttt{reg_type}='entropy'`, then :math:`\mathbf{c} = 1_{dim_a} 1_{dim_b}^T`.
326 warmstart: tuple of arrays, shape (dim_a, dim_b), optional
327 Initialization of dual potentials. If provided, the dual potentials should be given
328 (that is the logarithm of the u,v sinkhorn scaling vectors).
329 returnCost: string, optional (default = "linear")
330 If `returnCost` = "linear", then return the linear part of the unbalanced OT loss.
331 If `returnCost` = "total", then return the total unbalanced OT loss.
332 numItermax : int, optional
333 Max number of iterations
334 stopThr : float, optional
335 Stop threshold on error (>0)
336 verbose : bool, optional
337 Print information along iterations
338 log : bool, optional
339 record `log` if `True`
340
341
342 Returns
343 -------
344 ot_cost : (n_hists,) array-like
345 the OT cost between :math:`\mathbf{a}` and each of the histograms :math:`\mathbf{b}_i`
346 log : dict
347 log dictionary returned only if `log` is `True`
348
349 Examples
350 --------
351
352 >>> import ot
353 >>> import numpy as np
354 >>> a=[.5, .10]
355 >>> b=[.5, .5]
356 >>> M=[[0., 1.],[1., 0.]]
357 >>> np.round(ot.unbalanced.sinkhorn_unbalanced2(a, b, M, 1., 1.), 8)
358 0.19600125
359
360 .. _references-sinkhorn-unbalanced2:
361 References
362 ----------
363 .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal
364 Transport, Advances in Neural Information Processing Systems
365 (NIPS) 26, 2013
366
367 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for
368 Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
369
370 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
371 Scaling algorithms for unbalanced transport problems. arXiv preprint
372 arXiv:1607.05816.
373
374 .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
375 Learning with a Wasserstein Loss, Advances in Neural Information
376 Processing Systems (NIPS) 2015
377
378 .. [73] Séjourné, T., Vialard, F. X., & Peyré, G. (2022).
379 Faster unbalanced optimal transport: Translation invariant sinkhorn and 1-d frank-wolfe.
380 In International Conference on Artificial Intelligence and Statistics (pp. 4995-5021). PMLR.
381
382 See Also
383 --------
384 ot.unbalanced.sinkhorn_knopp: Unbalanced Classic Sinkhorn :ref:`[10] <references-sinkhorn-unbalanced2>`
385 ot.unbalanced.sinkhorn_stabilized: Unbalanced Stabilized sinkhorn :ref:`[9, 10] <references-sinkhorn-unbalanced2>`
386 ot.unbalanced.sinkhorn_reg_scaling: Unbalanced Sinkhorn with epsilon scaling :ref:`[9, 10] <references-sinkhorn-unbalanced2>`
387 ot.unbalanced.sinkhorn_unbalanced_translation_invariant: Translation Invariant Unbalanced Sinkhorn :ref:`[73] <references-sinkhorn-unbalanced2>`
388
389 """
390 M, a, b = list_to_array(M, a, b)
391
392 if len(b.shape) < 2:
393 if method.lower() == "sinkhorn":
394 res = sinkhorn_knopp_unbalanced(
395 a,
396 b,
397 M,
398 reg,
399 reg_m,
400 reg_type,
401 c,
402 warmstart,
403 numItermax=numItermax,
404 stopThr=stopThr,
405 verbose=verbose,
406 log=True,
407 **kwargs,
408 )
409
410 elif method.lower() == "sinkhorn_stabilized":
411 res = sinkhorn_stabilized_unbalanced(
412 a,
413 b,
414 M,
415 reg,
416 reg_m,
417 reg_type,
418 c,
419 warmstart,
420 numItermax=numItermax,
421 stopThr=stopThr,
422 verbose=verbose,
423 log=True,
424 **kwargs,
425 )
426
427 elif method.lower() == "sinkhorn_translation_invariant":
428 res = sinkhorn_unbalanced_translation_invariant(
429 a,
430 b,
431 M,
432 reg,
433 reg_m,
434 reg_type,
435 c,
436 warmstart,
437 numItermax=numItermax,
438 stopThr=stopThr,
439 verbose=verbose,
440 log=True,
441 **kwargs,
442 )
443
444 elif method.lower() in ["sinkhorn_reg_scaling"]:
445 warnings.warn("Method not implemented yet. Using classic Sinkhorn-Knopp")
446 res = sinkhorn_knopp_unbalanced(
447 a,
448 b,
449 M,
450 reg,
451 reg_m,
452 reg_type,
453 c,
454 warmstart,
455 numItermax=numItermax,
456 stopThr=stopThr,
457 verbose=verbose,
458 log=True,
459 **kwargs,
460 )
461 else:
462 raise ValueError("Unknown method %s." % method)
463
464 if returnCost == "linear":
465 cost = res[1]["cost"]
466 elif returnCost == "total":
467 cost = res[1]["total_cost"]
468 else:
469 raise ValueError("Unknown returnCost = {}".format(returnCost))
470
471 if log:
472 return cost, res[1]
473 else:
474 return cost
475
476 else:
477 if reg_type == "kl":
478 warnings.warn("Reg_type not implemented yet. Use entropy.")
479
480 if method.lower() == "sinkhorn":
481 return sinkhorn_knopp_unbalanced(
482 a,
483 b,
484 M,
485 reg,
486 reg_m,
487 reg_type,
488 c,
489 warmstart,
490 numItermax=numItermax,
491 stopThr=stopThr,
492 verbose=verbose,
493 log=log,
494 **kwargs,
495 )
496
497 elif method.lower() == "sinkhorn_stabilized":
498 return sinkhorn_stabilized_unbalanced(
499 a,
500 b,
501 M,
502 reg,
503 reg_m,
504 reg_type,
505 c,
506 warmstart,
507 numItermax=numItermax,
508 stopThr=stopThr,
509 verbose=verbose,
510 log=log,
511 **kwargs,
512 )
513
514 elif method.lower() == "sinkhorn_translation_invariant":
515 return sinkhorn_unbalanced_translation_invariant(
516 a,
517 b,
518 M,
519 reg,
520 reg_m,
521 reg_type,
522 c,
523 warmstart,
524 numItermax=numItermax,
525 stopThr=stopThr,
526 verbose=verbose,
527 log=log,
528 **kwargs,
529 )
530
531 elif method.lower() in ["sinkhorn_reg_scaling"]:
532 warnings.warn("Method not implemented yet. Using classic Sinkhorn-Knopp")
533 return sinkhorn_knopp_unbalanced(
534 a,
535 b,
536 M,
537 reg,
538 reg_m,
539 reg_type,
540 c,
541 warmstart,
542 numItermax=numItermax,
543 stopThr=stopThr,
544 verbose=verbose,
545 log=log,
546 **kwargs,
547 )
548 else:
549 raise ValueError("Unknown method %s." % method)
550
551
552 def sinkhorn_knopp_unbalanced(
553 a,
554 b,
555 M,
556 reg,
557 reg_m,
558 reg_type="kl",
559 c=None,
560 warmstart=None,
561 numItermax=1000,
562 stopThr=1e-6,
563 verbose=False,
564 log=False,
565 **kwargs,
566 ):
567 r"""
568 Solve the entropic regularization unbalanced optimal transport problem and
569 return the OT plan
570
571 The function solves the following optimization problem:
572
573 .. math::
574 W = \arg \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
575 \mathrm{reg} \cdot \mathrm{KL}(\gamma, \mathbf{c}) +
576 \mathrm{reg_{m1}} \cdot \mathrm{KL}(\gamma \mathbf{1}, \mathbf{a}) +
577 \mathrm{reg_{m2}} \cdot \mathrm{KL}(\gamma^T \mathbf{1}, \mathbf{b})
578
579 s.t.
580 \gamma \geq 0
581
582 where :
583
584 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
585 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
586 - :math:`\mathbf{c}` is a reference distribution for the regularization
587 - KL is the Kullback-Leibler divergence
588
589 The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in :ref:`[10, 25] <references-sinkhorn-knopp-unbalanced>`
590
591
592 Parameters
593 ----------
594 a : array-like (dim_a,)
595 Unnormalized histogram of dimension `dim_a`
596 If `a` is an empty list or array ([]),
597 then `a` is set to uniform distribution.
598 b : array-like (dim_b,)
599 One or multiple unnormalized histograms of dimension `dim_b`.
600 If `b` is an empty list or array ([]),
601 then `b` is set to uniform distribution.
602 If many, compute all the OT costs :math:`(\mathbf{a}, \mathbf{b}_i)_i`
603 M : array-like (dim_a, dim_b)
604 loss matrix
605 reg : float
606 Entropy regularization term > 0
607 reg_m: float or indexable object of length 1 or 2
608 Marginal relaxation term.
609 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
610 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
611 The entropic balanced OT can be recovered using :math:`\mathrm{reg_{m}}=float("inf")`.
612 For semi-relaxed case, use either
613 :math:`\mathrm{reg_{m}}=(float("inf"), scalar)` or
614 :math:`\mathrm{reg_{m}}=(scalar, float("inf"))`.
615 If :math:`\mathrm{reg_{m}}` is an array,
616 it must have the same backend as input arrays `(a, b, M)`.
617 reg_type : string, optional
618 Regularizer term. Can take two values:
619 + Negative entropy: 'entropy':
620 :math:`\Omega(\gamma) = \sum_{i,j} \gamma_{i,j} \log(\gamma_{i,j}) - \sum_{i,j} \gamma_{i,j}`.
621 This is equivalent (up to a constant) to :math:`\Omega(\gamma) = \text{KL}(\gamma, 1_{dim_a} 1_{dim_b}^T)`.
622 + Kullback-Leibler divergence: 'kl':
623 :math:`\Omega(\gamma) = \text{KL}(\gamma, \mathbf{a} \mathbf{b}^T)`.
624 c : array-like (dim_a, dim_b), optional (default=None)
625 Reference measure for the regularization.
626 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
627 If :math:`\texttt{reg_type}='entropy'`, then :math:`\mathbf{c} = 1_{dim_a} 1_{dim_b}^T`.
628 warmstart: tuple of arrays, shape (dim_a, dim_b), optional
629 Initialization of dual potentials. If provided, the dual potentials should be given
630 (that is the logarithm of the `u`, `v` sinkhorn scaling vectors).
631 numItermax : int, optional
632 Max number of iterations
633 stopThr : float, optional
634 Stop threshold on error (> 0)
635 verbose : bool, optional
636 Print information along iterations
637 log : bool, optional
638 record `log` if `True`
639
640
641 Returns
642 -------
643 if n_hists == 1:
644 - gamma : (dim_a, dim_b) array-like
645 Optimal transportation matrix for the given parameters
646 - log : dict
647 log dictionary returned only if `log` is `True`
648 else:
649 - ot_cost : (n_hists,) array-like
650 the OT cost between :math:`\mathbf{a}` and each of the histograms :math:`\mathbf{b}_i`
651 - log : dict
652 log dictionary returned only if `log` is `True`
653
654 Examples
655 --------
656
657 >>> import ot
658 >>> import numpy as np
659 >>> a=[.5, .5]
660 >>> b=[.5, .5]
661 >>> M=[[0., 1.],[1., 0.]]
662 >>> np.round(ot.unbalanced.sinkhorn_knopp_unbalanced(a, b, M, 1., 1.), 7)
663 array([[0.3220536, 0.1184769],
664 [0.1184769, 0.3220536]])
665
666 .. _references-sinkhorn-knopp-unbalanced:
667 References
668 ----------
669 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
670 Scaling algorithms for unbalanced transport problems. arXiv preprint
671 arXiv:1607.05816.
672
673 .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
674 Learning with a Wasserstein Loss, Advances in Neural Information
675 Processing Systems (NIPS) 2015
676
677 See Also
678 --------
679 ot.lp.emd : Unregularized OT
680 ot.optim.cg : General regularized OT
681
682 """
683 M, a, b = list_to_array(M, a, b)
684 nx = get_backend(M, a, b)
685
686 dim_a, dim_b = M.shape
687
688 if len(a) == 0:
689 a = nx.ones(dim_a, type_as=M) / dim_a
690 if len(b) == 0:
691 b = nx.ones(dim_b, type_as=M) / dim_b
692
693 if len(b.shape) > 1:
694 n_hists = b.shape[1]
695 else:
696 n_hists = 0
697
698 reg_m1, reg_m2 = get_parameter_pair(reg_m)
699
700 if log:
701 dict_log = {"err": []}
702
703 # we assume that no distances are null except those of the diagonal of
704 # distances
705 if warmstart is None:
706 if n_hists:
707 u = nx.ones((dim_a, 1), type_as=M)
708 v = nx.ones((dim_b, n_hists), type_as=M)
709 a = a.reshape(dim_a, 1)
710 else:
711 u = nx.ones(dim_a, type_as=M)
712 v = nx.ones(dim_b, type_as=M)
713 else:
714 u, v = nx.exp(warmstart[0]), nx.exp(warmstart[1])
715
716 if reg_type.lower() == "entropy":
717 warnings.warn(
718 "If reg_type = entropy, then the matrix c is overwritten by the one matrix."
719 )
720 c = nx.ones((dim_a, dim_b), type_as=M)
721
722 if n_hists:
723 K = nx.exp(-M / reg)
724 else:
725 c = a[:, None] * b[None, :] if c is None else c
726 K = nx.exp(-M / reg) * c
727
728 fi_1 = reg_m1 / (reg_m1 + reg) if reg_m1 != float("inf") else 1
729 fi_2 = reg_m2 / (reg_m2 + reg) if reg_m2 != float("inf") else 1
730
731 err = 1.0
732
733 for i in range(numItermax):
734 uprev = u
735 vprev = v
736
737 Kv = nx.dot(K, v)
738 u = (a / Kv) ** fi_1
739 Ktu = nx.dot(K.T, u)
740 v = (b / Ktu) ** fi_2
741
742 if (
743 nx.any(Ktu == 0.0)
744 or nx.any(nx.isnan(u))
745 or nx.any(nx.isnan(v))
746 or nx.any(nx.isinf(u))
747 or nx.any(nx.isinf(v))
748 ):
749 # we have reached the machine precision
750 # come back to previous solution and quit loop
751 warnings.warn("Numerical errors at iteration %s" % i)
752 u = uprev
753 v = vprev
754 break
755
756 err_u = nx.max(nx.abs(u - uprev)) / max(
757 nx.max(nx.abs(u)), nx.max(nx.abs(uprev)), 1.0
758 )
759 err_v = nx.max(nx.abs(v - vprev)) / max(
760 nx.max(nx.abs(v)), nx.max(nx.abs(vprev)), 1.0
761 )
762 err = 0.5 * (err_u + err_v)
763 if log:
764 dict_log["err"].append(err)
765 if verbose:
766 if i % 50 == 0:
767 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
768 print("{:5d}|{:8e}|".format(i, err))
769 if err < stopThr:
770 break
771
772 if log:
773 dict_log["logu"] = nx.log(u + 1e-300)
774 dict_log["logv"] = nx.log(v + 1e-300)
775
776 if n_hists: # return only loss
777 res = nx.einsum("ik,ij,jk,ij->k", u, K, v, M)
778 if log:
779 return res, dict_log
780 else:
781 return res
782
783 else: # return OT matrix
784 plan = u[:, None] * K * v[None, :]
785
786 if log:
787 linear_cost = nx.sum(plan * M)
788 dict_log["cost"] = linear_cost
789
790 total_cost = linear_cost + reg * nx.kl_div(plan, c)
791 if reg_m1 != float("inf"):
792 total_cost = total_cost + reg_m1 * nx.kl_div(nx.sum(plan, 1), a)
793 if reg_m2 != float("inf"):
794 total_cost = total_cost + reg_m2 * nx.kl_div(nx.sum(plan, 0), b)
795 dict_log["total_cost"] = total_cost
796
797 return plan, dict_log
798 else:
799 return plan
800
801
802 def sinkhorn_stabilized_unbalanced(
803 a,
804 b,
805 M,
806 reg,
807 reg_m,
808 reg_type="kl",
809 c=None,
810 warmstart=None,
811 tau=1e5,
812 numItermax=1000,
813 stopThr=1e-6,
814 verbose=False,
815 log=False,
816 **kwargs,
817 ):
818 r"""
819 Solve the entropic regularization unbalanced optimal transport
820 problem and return the loss
821
822 The function solves the following optimization problem using log-domain
823 stabilization as proposed in :ref:`[10] <references-sinkhorn-stabilized-unbalanced>`:
824
825 .. math::
826 W = \arg \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
827 \mathrm{reg} \cdot \mathrm{KL}(\gamma, \mathbf{c}) +
828 \mathrm{reg_{m1}} \cdot \mathrm{KL}(\gamma \mathbf{1}, \mathbf{a}) +
829 \mathrm{reg_{m2}} \cdot \mathrm{KL}(\gamma^T \mathbf{1}, \mathbf{b})
830
831 s.t.
832 \gamma \geq 0
833
834 where :
835
836 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
837 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
838 - :math:`\mathbf{c}` is a reference distribution for the regularization
839 - KL is the Kullback-Leibler divergence
840
841 The algorithm used for solving the problem is the generalized
842 Sinkhorn-Knopp matrix scaling algorithm as proposed in :ref:`[10, 25] <references-sinkhorn-stabilized-unbalanced>`
843
844
845 Parameters
846 ----------
847 a : array-like (dim_a,)
848 Unnormalized histogram of dimension `dim_a`
849 If `a` is an empty list or array ([]),
850 then `a` is set to uniform distribution.
851 b : array-like (dim_b,)
852 One or multiple unnormalized histograms of dimension `dim_b`.
853 If `b` is an empty list or array ([]),
854 then `b` is set to uniform distribution.
855 If many, compute all the OT costs :math:`(\mathbf{a}, \mathbf{b}_i)_i`
856 M : array-like (dim_a, dim_b)
857 loss matrix
858 reg : float
859 Entropy regularization term > 0
860 reg_m: float or indexable object of length 1 or 2
861 Marginal relaxation term.
862 If :math:`\mathrm{reg_{m}}` is a scalar or an indexable object of length 1,
863 then the same :math:`\mathrm{reg_{m}}` is applied to both marginal relaxations.
864 The entropic balanced OT can be recovered using :math:`\mathrm{reg_{m}}=float("inf")`.
865 For semi-relaxed case, use either
866 :math:`\mathrm{reg_{m}}=(float("inf"), scalar)` or
867 :math:`\mathrm{reg_{m}}=(scalar, float("inf"))`.
868 If :math:`\mathrm{reg_{m}}` is an array,
869 it must have the same backend as input arrays `(a, b, M)`.
870 method : str
871 method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
872 'sinkhorn_reg_scaling', see those function for specific parameters
873 reg_type : string, optional
874 Regularizer term. Can take two values:
875 + Negative entropy: 'entropy':
876 :math:`\Omega(\gamma) = \sum_{i,j} \gamma_{i,j} \log(\gamma_{i,j}) - \sum_{i,j} \gamma_{i,j}`.
877 This is equivalent (up to a constant) to :math:`\Omega(\gamma) = \text{KL}(\gamma, 1_{dim_a} 1_{dim_b}^T)`.
878 + Kullback-Leibler divergence: 'kl':
879 :math:`\Omega(\gamma) = \text{KL}(\gamma, \mathbf{a} \mathbf{b}^T)`.
880 c : array-like (dim_a, dim_b), optional (default=None)
881 Reference measure for the regularization.
882 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
883 If :math:`\texttt{reg_type}='entropy'`, then :math:`\mathbf{c} = 1_{dim_a} 1_{dim_b}^T`.
884 warmstart: tuple of arrays, shape (dim_a, dim_b), optional
885 Initialization of dual potentials. If provided, the dual potentials should be given
886 (that is the logarithm of the `u`, `v` sinkhorn scaling vectors).
887 tau : float
888 threshold for max value in `u` or `v` for log scaling
889 numItermax : int, optional
890 Max number of iterations
891 stopThr : float, optional
892 Stop threshold on error (>0)
893 verbose : bool, optional
894 Print information along iterations
895 log : bool, optional
896 record `log` if `True`
897
898
899 Returns
900 -------
901 if n_hists == 1:
902 - gamma : (dim_a, dim_b) array-like
903 Optimal transportation matrix for the given parameters
904 - log : dict
905 log dictionary returned only if `log` is `True`
906 else:
907 - ot_cost : (n_hists,) array-like
908 the OT cost between :math:`\mathbf{a}` and each of the histograms :math:`\mathbf{b}_i`
909 - log : dict
910 log dictionary returned only if `log` is `True`
911 Examples
912 --------
913
914 >>> import ot
915 >>> import numpy as np
916 >>> a=[.5, .5]
917 >>> b=[.5, .5]
918 >>> M=[[0., 1.],[1., 0.]]
919 >>> np.round(ot.unbalanced.sinkhorn_stabilized_unbalanced(a, b, M, 1., 1.), 7)
920 array([[0.3220536, 0.1184769],
921 [0.1184769, 0.3220536]])
922
923 .. _references-sinkhorn-stabilized-unbalanced:
924 References
925 ----------
926 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
927 Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
928
929 .. [25] Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. :
930 Learning with a Wasserstein Loss, Advances in Neural Information
931 Processing Systems (NIPS) 2015
932
933 See Also
934 --------
935 ot.lp.emd : Unregularized OT
936 ot.optim.cg : General regularized OT
937
938 """
939 a, b, M = list_to_array(a, b, M)
940 nx = get_backend(M, a, b)
941
942 dim_a, dim_b = M.shape
943
944 if len(a) == 0:
945 a = nx.ones(dim_a, type_as=M) / dim_a
946 if len(b) == 0:
947 b = nx.ones(dim_b, type_as=M) / dim_b
948
949 if len(b.shape) > 1:
950 n_hists = b.shape[1]
951 else:
952 n_hists = 0
953
954 reg_m1, reg_m2 = get_parameter_pair(reg_m)
955
956 if log:
957 dict_log = {"err": []}
958
959 # we assume that no distances are null except those of the diagonal of
960 # distances
961 if warmstart is None:
962 if n_hists:
963 u = nx.ones((dim_a, n_hists), type_as=M)
964 v = nx.ones((dim_b, n_hists), type_as=M)
965 a = a.reshape(dim_a, 1)
966 else:
967 u = nx.ones(dim_a, type_as=M)
968 v = nx.ones(dim_b, type_as=M)
969 else:
970 u, v = nx.exp(warmstart[0]), nx.exp(warmstart[1])
971
972 if reg_type == "entropy":
973 warnings.warn(
974 "If reg_type = entropy, then the matrix c is overwritten by the one matrix."
975 )
976 c = nx.ones((dim_a, dim_b), type_as=M)
977
978 if n_hists:
979 M0 = M
980 else:
981 c = a[:, None] * b[None, :] if c is None else c
982 M0 = M - reg * nx.log(c)
983 K = nx.exp(-M0 / reg)
984
985 fi_1 = reg_m1 / (reg_m1 + reg) if reg_m1 != float("inf") else 1
986 fi_2 = reg_m2 / (reg_m2 + reg) if reg_m2 != float("inf") else 1
987
988 cpt = 0
989 err = 1.0
990 alpha = nx.zeros(dim_a, type_as=M)
991 beta = nx.zeros(dim_b, type_as=M)
992 ones_a = nx.ones(dim_a, type_as=M)
993 ones_b = nx.ones(dim_b, type_as=M)
994
995 while err > stopThr and cpt < numItermax:
996 uprev = u
997 vprev = v
998
999 Kv = nx.dot(K, v)
1000 f_alpha = nx.exp(-alpha / (reg + reg_m1)) if reg_m1 != float("inf") else ones_a
1001 f_beta = nx.exp(-beta / (reg + reg_m2)) if reg_m2 != float("inf") else ones_b
1002
1003 if n_hists:
1004 f_alpha = f_alpha[:, None]
1005 f_beta = f_beta[:, None]
1006 u = ((a / (Kv + 1e-16)) ** fi_1) * f_alpha
1007 Ktu = nx.dot(K.T, u)
1008 v = ((b / (Ktu + 1e-16)) ** fi_2) * f_beta
1009 absorbing = False
1010 if nx.any(u > tau) or nx.any(v > tau):
1011 absorbing = True
1012 if n_hists:
1013 alpha = alpha + reg * nx.log(nx.max(u, 1))
1014 beta = beta + reg * nx.log(nx.max(v, 1))
1015 else:
1016 alpha = alpha + reg * nx.log(nx.max(u))
1017 beta = beta + reg * nx.log(nx.max(v))
1018 K = nx.exp((alpha[:, None] + beta[None, :] - M0) / reg)
1019 v = nx.ones(v.shape, type_as=v)
1020 Kv = nx.dot(K, v)
1021
1022 if (
1023 nx.any(Ktu == 0.0)
1024 or nx.any(nx.isnan(u))
1025 or nx.any(nx.isnan(v))
1026 or nx.any(nx.isinf(u))
1027 or nx.any(nx.isinf(v))
1028 ):
1029 # we have reached the machine precision
1030 # come back to previous solution and quit loop
1031 warnings.warn("Numerical errors at iteration %s" % cpt)
1032 u = uprev
1033 v = vprev
1034 break
1035 if (cpt % 10 == 0 and not absorbing) or cpt == 0:
1036 # we can speed up the process by checking for the error only all
1037 # the 10th iterations
1038 err = nx.max(nx.abs(u - uprev)) / max(
1039 nx.max(nx.abs(u)), nx.max(nx.abs(uprev)), 1.0
1040 )
1041 if log:
1042 dict_log["err"].append(err)
1043 if verbose:
1044 if cpt % 200 == 0:
1045 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
1046 print("{:5d}|{:8e}|".format(cpt, err))
1047 cpt = cpt + 1
1048
1049 if err > stopThr:
1050 warnings.warn(
1051 "Stabilized Unbalanced Sinkhorn did not converge."
1052 + "Try a larger entropy `reg` or a lower mass `reg_m`."
1053 + "Or a larger absorption threshold `tau`."
1054 )
1055 if n_hists:
1056 logu = alpha[:, None] / reg + nx.log(u)
1057 logv = beta[:, None] / reg + nx.log(v)
1058 else:
1059 logu = alpha / reg + nx.log(u)
1060 logv = beta / reg + nx.log(v)
1061 if log:
1062 dict_log["logu"] = logu
1063 dict_log["logv"] = logv
1064 if n_hists: # return only loss
1065 res = nx.logsumexp(
1066 nx.log(M + 1e-100)[:, :, None]
1067 + logu[:, None, :]
1068 + logv[None, :, :]
1069 - M0[:, :, None] / reg,
1070 axis=(0, 1),
1071 )
1072 res = nx.exp(res)
1073 if log:
1074 return res, dict_log
1075 else:
1076 return res
1077
1078 else: # return OT matrix
1079 plan = nx.exp(logu[:, None] + logv[None, :] - M0 / reg)
1080 if log:
1081 linear_cost = nx.sum(plan * M)
1082 dict_log["cost"] = linear_cost
1083
1084 total_cost = linear_cost + reg * nx.kl_div(plan, c)
1085 if reg_m1 != float("inf"):
1086 total_cost = total_cost + reg_m1 * nx.kl_div(nx.sum(plan, 1), a)
1087 if reg_m2 != float("inf"):
1088 total_cost = total_cost + reg_m2 * nx.kl_div(nx.sum(plan, 0), b)
1089 dict_log["total_cost"] = total_cost
1090
1091 return plan, dict_log
1092 else:
1093 return plan
1094
1095
1096 def sinkhorn_unbalanced_translation_invariant(
1097 a,
1098 b,
1099 M,
1100 reg,
1101 reg_m,
1102 reg_type="kl",
1103 c=None,
1104 warmstart=None,
1105 numItermax=1000,
1106 stopThr=1e-6,
1107 verbose=False,
1108 log=False,
1109 **kwargs,
1110 ):
1111 r"""
1112 Solve the entropic regularization unbalanced optimal transport problem and
1113 return the OT plan
1114
1115 The function solves the following optimization problem:
1116
1117 .. math::
1118 W = \arg \min_\gamma \ \langle \gamma, \mathbf{M} \rangle_F +
1119 \mathrm{reg} \cdot \mathrm{KL}(\gamma, \mathbf{c}) +
1120 \mathrm{reg_{m1}} \cdot \mathrm{KL}(\gamma \mathbf{1}, \mathbf{a}) +
1121 \mathrm{reg_{m2}} \cdot \mathrm{KL}(\gamma^T \mathbf{1}, \mathbf{b})
1122
1123 s.t.
1124 \gamma \geq 0
1125
1126 where :
1127
1128 - :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix
1129 - :math:`\Omega` is the entropic regularization term,KL divergence
1130 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
1131 - KL is the Kullback-Leibler divergence
1132
1133 The algorithm used for solving the problem is the translation invariant Sinkhorn algorithm as proposed in :ref:`[73] <references-sinkhorn-unbalanced-translation-invariant>`
1134
1135
1136 Parameters
1137 ----------
1138 a : array-like (dim_a,)
1139 Unnormalized histogram of dimension `dim_a`
1140 b : array-like (dim_b,) or array-like (dim_b, n_hists)
1141 One or multiple unnormalized histograms of dimension `dim_b`
1142 If many, compute all the OT distances (a, b_i)
1143 M : array-like (dim_a, dim_b)
1144 loss matrix
1145 reg : float
1146 Entropy regularization term > 0
1147 reg_m: float or indexable object of length 1 or 2
1148 Marginal relaxation term.
1149 If reg_m is a scalar or an indexable object of length 1,
1150 then the same reg_m is applied to both marginal relaxations.
1151 The entropic balanced OT can be recovered using `reg_m=float("inf")`.
1152 For semi-relaxed case, use either
1153 `reg_m=(float("inf"), scalar)` or `reg_m=(scalar, float("inf"))`.
1154 If reg_m is an array, it must have the same backend as input arrays (a, b, M).
1155 reg_type : string, optional
1156 Regularizer term. Can take two values:
1157 'entropy' (negative entropy)
1158 :math:`\Omega(\gamma) = \sum_{i,j} \gamma_{i,j} \log(\gamma_{i,j}) - \sum_{i,j} \gamma_{i,j}`, or
1159 'kl' (Kullback-Leibler)
1160 :math:`\Omega(\gamma) = \text{KL}(\gamma, \mathbf{a} \mathbf{b}^T)`.
1161 c : array-like (dim_a, dim_b), optional (default=None)
1162 Reference measure for the regularization.
1163 If None, then use :math:`\mathbf{c} = \mathbf{a} \mathbf{b}^T`.
1164 If :math:`\texttt{reg_type}='entropy'`, then :math:`\mathbf{c} = 1_{dim_a} 1_{dim_b}^T`.
1165 warmstart: tuple of arrays, shape (dim_a, dim_b), optional
1166 Initialization of dual potentials. If provided, the dual potentials should be given
1167 (that is the logarithm of the u,v sinkhorn scaling vectors).
1168 numItermax : int, optional
1169 Max number of iterations
1170 stopThr : float, optional
1171 Stop threshold on error (> 0)
1172 verbose : bool, optional
1173 Print information along iterations
1174 log : bool, optional
1175 record log if True
1176
1177
1178 Returns
1179 -------
1180 if n_hists == 1:
1181 - gamma : (dim_a, dim_b) array-like
1182 Optimal transportation matrix for the given parameters
1183 - log : dict
1184 log dictionary returned only if `log` is `True`
1185 else:
1186 - ot_distance : (n_hists,) array-like
1187 the OT distance between :math:`\mathbf{a}` and each of the histograms :math:`\mathbf{b}_i`
1188 - log : dict
1189 log dictionary returned only if `log` is `True`
1190
1191 Examples
1192 --------
1193
1194 >>> import ot
1195 >>> a=[.5, .5]
1196 >>> b=[.5, .5]
1197 >>> M=[[0., 1.],[1., 0.]]
1198 >>> ot.unbalanced.sinkhorn_unbalanced_translation_invariant(a, b, M, 1., 1.)
1199 array([[0.32205357, 0.11847689],
1200 [0.11847689, 0.32205357]])
1201
1202 .. _references-sinkhorn-unbalanced-translation-invariant:
1203 References
1204 ----------
1205 .. [73] Séjourné, T., Vialard, F. X., & Peyré, G. (2022).
1206 Faster unbalanced optimal transport: Translation invariant sinkhorn and 1-d frank-wolfe.
1207 In International Conference on Artificial Intelligence and Statistics (pp. 4995-5021). PMLR.
1208 """
1209
1210 M, a, b = list_to_array(M, a, b)
1211 nx = get_backend(M, a, b)
1212
1213 dim_a, dim_b = M.shape
1214
1215 if len(a) == 0:
1216 a = nx.ones(dim_a, type_as=M) / dim_a
1217 if len(b) == 0:
1218 b = nx.ones(dim_b, type_as=M) / dim_b
1219
1220 if len(b.shape) > 1:
1221 n_hists = b.shape[1]
1222 else:
1223 n_hists = 0
1224
1225 reg_m1, reg_m2 = get_parameter_pair(reg_m)
1226
1227 if log:
1228 dict_log = {"err": []}
1229
1230 # we assume that no distances are null except those of the diagonal of
1231 # distances
1232 if warmstart is None:
1233 if n_hists:
1234 u = nx.ones((dim_a, 1), type_as=M)
1235 v = nx.ones((dim_b, n_hists), type_as=M)
1236 a = a.reshape(dim_a, 1)
1237 else:
1238 u = nx.ones(dim_a, type_as=M)
1239 v = nx.ones(dim_b, type_as=M)
1240 else:
1241 u, v = nx.exp(warmstart[0]), nx.exp(warmstart[1])
1242
1243 u_, v_ = u, v
1244
1245 if reg_type == "entropy":
1246 warnings.warn(
1247 "If reg_type = entropy, then the matrix c is overwritten by the one matrix."
1248 )
1249 c = nx.ones((dim_a, dim_b), type_as=M)
1250
1251 if n_hists:
1252 M0 = M
1253 else:
1254 c = a[:, None] * b[None, :] if c is None else c
1255 M0 = M - reg * nx.log(c)
1256 K = nx.exp(-M0 / reg)
1257
1258 fi_1 = reg_m1 / (reg_m1 + reg) if reg_m1 != float("inf") else 1
1259 fi_2 = reg_m2 / (reg_m2 + reg) if reg_m2 != float("inf") else 1
1260
1261 k1 = (
1262 reg * reg_m1 / ((reg + reg_m1) * (reg_m1 + reg_m2))
1263 if reg_m1 != float("inf")
1264 else 0
1265 )
1266 k2 = (
1267 reg * reg_m2 / ((reg + reg_m2) * (reg_m1 + reg_m2))
1268 if reg_m2 != float("inf")
1269 else 0
1270 )
1271
1272 k_rho1 = k1 * reg_m1 / reg if reg_m1 != float("inf") else 0
1273 k_rho2 = k2 * reg_m2 / reg if reg_m2 != float("inf") else 0
1274
1275 if reg_m1 == float("inf") and reg_m2 == float("inf"):
1276 xi1, xi2 = 0, 0
1277 fi_12 = 1
1278 elif reg_m1 == float("inf"):
1279 xi1 = 0
1280 xi2 = reg / reg_m2
1281 fi_12 = reg_m2
1282 elif reg_m2 == float("inf"):
1283 xi1 = reg / reg_m1
1284 xi2 = 0
1285 fi_12 = reg_m1
1286 else:
1287 xi1 = (reg_m2 * reg) / (reg_m1 * (reg + reg_m1 + reg_m2))
1288 xi2 = (reg_m1 * reg) / (reg_m2 * (reg + reg_m1 + reg_m2))
1289 fi_12 = reg_m1 * reg_m2 / (reg_m1 + reg_m2)
1290
1291 xi_rho1 = xi1 * reg_m1 / reg if reg_m1 != float("inf") else 0
1292 xi_rho2 = xi2 * reg_m2 / reg if reg_m2 != float("inf") else 0
1293
1294 reg_ratio1 = reg / reg_m1 if reg_m1 != float("inf") else 0
1295 reg_ratio2 = reg / reg_m2 if reg_m2 != float("inf") else 0
1296
1297 err = 1.0
1298
1299 for i in range(numItermax):
1300 uprev = u
1301 vprev = v
1302
1303 Kv = nx.dot(K, v_)
1304 u_hat = (a / Kv) ** fi_1 * nx.sum(b * v_**reg_ratio2) ** k_rho2
1305 u_ = u_hat * nx.sum(a * u_hat ** (-reg_ratio1)) ** (-xi_rho1)
1306
1307 Ktu = nx.dot(K.T, u_)
1308 v_hat = (b / Ktu) ** fi_2 * nx.sum(a * u_ ** (-reg_ratio1)) ** k_rho1
1309 v_ = v_hat * nx.sum(b * v_hat ** (-reg_ratio2)) ** (-xi_rho2)
1310
1311 if (
1312 nx.any(Ktu == 0.0)
1313 or nx.any(nx.isnan(u_))
1314 or nx.any(nx.isnan(v_))
1315 or nx.any(nx.isinf(u_))
1316 or nx.any(nx.isinf(v_))
1317 ):
1318 # we have reached the machine precision
1319 # come back to previous solution and quit loop
1320 warnings.warn("Numerical errors at iteration %s" % i)
1321 u = uprev
1322 v = vprev
1323 break
1324
1325 t = (nx.sum(a * u_ ** (-reg_ratio1)) / nx.sum(b * v_ ** (-reg_ratio2))) ** (
1326 fi_12 / reg
1327 )
1328
1329 u = u_ * t
1330 v = v_ / t
1331
1332 err_u = nx.max(nx.abs(u - uprev)) / max(
1333 nx.max(nx.abs(u)), nx.max(nx.abs(uprev)), 1.0
1334 )
1335 err_v = nx.max(nx.abs(v - vprev)) / max(
1336 nx.max(nx.abs(v)), nx.max(nx.abs(vprev)), 1.0
1337 )
1338 err = 0.5 * (err_u + err_v)
1339 if log:
1340 dict_log["err"].append(err)
1341 if verbose:
1342 if i % 50 == 0:
1343 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
1344 print("{:5d}|{:8e}|".format(i, err))
1345
1346 if err < stopThr:
1347 break
1348
1349 if log:
1350 dict_log["logu"] = nx.log(u + 1e-300)
1351 dict_log["logv"] = nx.log(v + 1e-300)
1352
1353 if n_hists: # return only loss
1354 res = nx.einsum("ik,ij,jk,ij->k", u, K, v, M)
1355 if log:
1356 return res, dict_log
1357 else:
1358 return res
1359
1360 else: # return OT matrix
1361 plan = u[:, None] * K * v[None, :]
1362
1363 if log:
1364 linear_cost = nx.sum(plan * M)
1365 dict_log["cost"] = linear_cost
1366
1367 total_cost = linear_cost + reg * nx.kl_div(plan, c)
1368 if reg_m1 != float("inf"):
1369 total_cost = total_cost + reg_m1 * nx.kl_div(nx.sum(plan, 1), a)
1370 if reg_m2 != float("inf"):
1371 total_cost = total_cost + reg_m2 * nx.kl_div(nx.sum(plan, 0), b)
1372 dict_log["total_cost"] = total_cost
1373
1374 return plan, dict_log
1375 else:
1376 return plan
1377
1378
1379 def barycenter_unbalanced_stabilized(
1380 A,
1381 M,
1382 reg,
1383 reg_m,
1384 weights=None,
1385 tau=1e3,
1386 numItermax=1000,
1387 stopThr=1e-6,
1388 verbose=False,
1389 log=False,
1390 ):
1391 r"""Compute the entropic unbalanced wasserstein barycenter of :math:`\mathbf{A}` with stabilization.
1392
1393 The function solves the following optimization problem:
1394
1395 .. math::
1396 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i W_{u_{reg}}(\mathbf{a},\mathbf{a}_i)
1397
1398 where :
1399
1400 - :math:`W_{u_{reg}}(\cdot,\cdot)` is the unbalanced entropic regularized Wasserstein distance (see :py:func:`ot.unbalanced.sinkhorn_unbalanced`)
1401 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
1402 - reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
1403 - reg_mis the marginal relaxation hyperparameter
1404
1405 The algorithm used for solving the problem is the generalized
1406 Sinkhorn-Knopp matrix scaling algorithm as proposed in :ref:`[10] <references-barycenter-unbalanced-stabilized>`
1407
1408 Parameters
1409 ----------
1410 A : array-like (dim, n_hists)
1411 `n_hists` training distributions :math:`\mathbf{a}_i` of dimension `dim`
1412 M : array-like (dim, dim)
1413 ground metric matrix for OT.
1414 reg : float
1415 Entropy regularization term > 0
1416 reg_m : float
1417 Marginal relaxation term > 0
1418 tau : float
1419 Stabilization threshold for log domain absorption.
1420 weights : array-like (n_hists,) optional
1421 Weight of each distribution (barycentric coordinates)
1422 If None, uniform weights are used.
1423 numItermax : int, optional
1424 Max number of iterations
1425 stopThr : float, optional
1426 Stop threshold on error (> 0)
1427 verbose : bool, optional
1428 Print information along iterations
1429 log : bool, optional
1430 record `log` if `True`
1431
1432
1433 Returns
1434 -------
1435 a : (dim,) array-like
1436 Unbalanced Wasserstein barycenter
1437 log : dict
1438 log dictionary return only if :math:`log==True` in parameters
1439
1440
1441 .. _references-barycenter-unbalanced-stabilized:
1442 References
1443 ----------
1444 .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré,
1445 G. (2015). Iterative Bregman projections for regularized transportation
1446 problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
1447 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
1448 Scaling algorithms for unbalanced transport problems. arXiv preprint
1449 arXiv:1607.05816.
1450
1451
1452 """
1453 A, M = list_to_array(A, M)
1454 nx = get_backend(A, M)
1455
1456 dim, n_hists = A.shape
1457 if weights is None:
1458 weights = nx.ones(n_hists, type_as=A) / n_hists
1459 else:
1460 assert len(weights) == A.shape[1]
1461
1462 if log:
1463 log = {"err": []}
1464
1465 fi = reg_m / (reg_m + reg)
1466
1467 u = nx.ones((dim, n_hists), type_as=A) / dim
1468 v = nx.ones((dim, n_hists), type_as=A) / dim
1469
1470 # print(reg)
1471 K = nx.exp(-M / reg)
1472
1473 fi = reg_m / (reg_m + reg)
1474
1475 cpt = 0
1476 err = 1.0
1477 alpha = nx.zeros(dim, type_as=A)
1478 beta = nx.zeros(dim, type_as=A)
1479 q = nx.ones(dim, type_as=A) / dim
1480 for i in range(numItermax):
1481 qprev = nx.copy(q)
1482 Kv = nx.dot(K, v)
1483 f_alpha = nx.exp(-alpha / (reg + reg_m))
1484 f_beta = nx.exp(-beta / (reg + reg_m))
1485 f_alpha = f_alpha[:, None]
1486 f_beta = f_beta[:, None]
1487 u = ((A / (Kv + 1e-16)) ** fi) * f_alpha
1488 Ktu = nx.dot(K.T, u)
1489 q = (Ktu ** (1 - fi)) * f_beta
1490 q = nx.dot(q, weights) ** (1 / (1 - fi))
1491 Q = q[:, None]
1492 v = ((Q / (Ktu + 1e-16)) ** fi) * f_beta
1493 absorbing = False
1494 if nx.any(u > tau) or nx.any(v > tau):
1495 absorbing = True
1496 alpha = alpha + reg * nx.log(nx.max(u, 1))
1497 beta = beta + reg * nx.log(nx.max(v, 1))
1498 K = nx.exp((alpha[:, None] + beta[None, :] - M) / reg)
1499 v = nx.ones(v.shape, type_as=v)
1500 Kv = nx.dot(K, v)
1501 if (
1502 nx.any(Ktu == 0.0)
1503 or nx.any(nx.isnan(u))
1504 or nx.any(nx.isnan(v))
1505 or nx.any(nx.isinf(u))
1506 or nx.any(nx.isinf(v))
1507 ):
1508 # we have reached the machine precision
1509 # come back to previous solution and quit loop
1510 warnings.warn("Numerical errors at iteration %s" % cpt)
1511 q = qprev
1512 break
1513 if (i % 10 == 0 and not absorbing) or i == 0:
1514 # we can speed up the process by checking for the error only all
1515 # the 10th iterations
1516 err = nx.max(nx.abs(q - qprev)) / max(
1517 nx.max(nx.abs(q)), nx.max(nx.abs(qprev)), 1.0
1518 )
1519 if log:
1520 log["err"].append(err)
1521 if verbose:
1522 if i % 50 == 0:
1523 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
1524 print("{:5d}|{:8e}|".format(i, err))
1525 if err < stopThr:
1526 break
1527
1528 if err > stopThr:
1529 warnings.warn(
1530 "Stabilized Unbalanced Sinkhorn did not converge."
1531 + "Try a larger entropy `reg` or a lower mass `reg_m`."
1532 + "Or a larger absorption threshold `tau`."
1533 )
1534 if log:
1535 log["niter"] = i
1536 log["logu"] = nx.log(u + 1e-300)
1537 log["logv"] = nx.log(v + 1e-300)
1538 return q, log
1539 else:
1540 return q
1541
1542
1543 def barycenter_unbalanced_sinkhorn(
1544 A,
1545 M,
1546 reg,
1547 reg_m,
1548 weights=None,
1549 numItermax=1000,
1550 stopThr=1e-6,
1551 verbose=False,
1552 log=False,
1553 ):
1554 r"""Compute the entropic unbalanced wasserstein barycenter of :math:`\mathbf{A}`.
1555
1556 The function solves the following optimization problem with :math:`\mathbf{a}`
1557
1558 .. math::
1559 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i W_{u_{reg}}(\mathbf{a},\mathbf{a}_i)
1560
1561 where :
1562
1563 - :math:`W_{u_{reg}}(\cdot,\cdot)` is the unbalanced entropic regularized Wasserstein distance (see :py:func:`ot.unbalanced.sinkhorn_unbalanced`)
1564 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
1565 - reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
1566 - reg_mis the marginal relaxation hyperparameter
1567
1568 The algorithm used for solving the problem is the generalized
1569 Sinkhorn-Knopp matrix scaling algorithm as proposed in :ref:`[10] <references-barycenter-unbalanced-sinkhorn>`
1570
1571 Parameters
1572 ----------
1573 A : array-like (dim, n_hists)
1574 `n_hists` training distributions :math:`\mathbf{a}_i` of dimension `dim`
1575 M : array-like (dim, dim)
1576 ground metric matrix for OT.
1577 reg : float
1578 Entropy regularization term > 0
1579 reg_m: float
1580 Marginal relaxation term > 0
1581 weights : array-like (n_hists,) optional
1582 Weight of each distribution (barycentric coordinates)
1583 If None, uniform weights are used.
1584 numItermax : int, optional
1585 Max number of iterations
1586 stopThr : float, optional
1587 Stop threshold on error (> 0)
1588 verbose : bool, optional
1589 Print information along iterations
1590 log : bool, optional
1591 record `log` if `True`
1592
1593
1594 Returns
1595 -------
1596 a : (dim,) array-like
1597 Unbalanced Wasserstein barycenter
1598 log : dict
1599 log dictionary return only if :math:`log==True` in parameters
1600
1601
1602 .. _references-barycenter-unbalanced-sinkhorn:
1603 References
1604 ----------
1605 .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G.
1606 (2015). Iterative Bregman projections for regularized transportation
1607 problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
1608 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
1609 Scaling algorithms for unbalanced transport problems. arXiv preprin
1610 arXiv:1607.05816.
1611
1612
1613 """
1614 A, M = list_to_array(A, M)
1615 nx = get_backend(A, M)
1616
1617 dim, n_hists = A.shape
1618 if weights is None:
1619 weights = nx.ones(n_hists, type_as=A) / n_hists
1620 else:
1621 assert len(weights) == A.shape[1]
1622
1623 if log:
1624 log = {"err": []}
1625
1626 K = nx.exp(-M / reg)
1627
1628 fi = reg_m / (reg_m + reg)
1629
1630 v = nx.ones((dim, n_hists), type_as=A)
1631 u = nx.ones((dim, 1), type_as=A)
1632 q = nx.ones(dim, type_as=A)
1633 err = 1.0
1634
1635 for i in range(numItermax):
1636 uprev = nx.copy(u)
1637 vprev = nx.copy(v)
1638 qprev = nx.copy(q)
1639
1640 Kv = nx.dot(K, v)
1641 u = (A / Kv) ** fi
1642 Ktu = nx.dot(K.T, u)
1643 q = nx.dot(Ktu ** (1 - fi), weights)
1644 q = q ** (1 / (1 - fi))
1645 Q = q[:, None]
1646 v = (Q / Ktu) ** fi
1647
1648 if (
1649 nx.any(Ktu == 0.0)
1650 or nx.any(nx.isnan(u))
1651 or nx.any(nx.isnan(v))
1652 or nx.any(nx.isinf(u))
1653 or nx.any(nx.isinf(v))
1654 ):
1655 # we have reached the machine precision
1656 # come back to previous solution and quit loop
1657 warnings.warn("Numerical errors at iteration %s" % i)
1658 u = uprev
1659 v = vprev
1660 q = qprev
1661 break
1662 # compute change in barycenter
1663 err = nx.max(nx.abs(q - qprev)) / max(
1664 nx.max(nx.abs(q)), nx.max(nx.abs(qprev)), 1.0
1665 )
1666 if log:
1667 log["err"].append(err)
1668 # if barycenter did not change + at least 10 iterations - stop
1669 if err < stopThr and i > 10:
1670 break
1671
1672 if verbose:
1673 if i % 10 == 0:
1674 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
1675 print("{:5d}|{:8e}|".format(i, err))
1676
1677 if log:
1678 log["niter"] = i
1679 log["logu"] = nx.log(u + 1e-300)
1680 log["logv"] = nx.log(v + 1e-300)
1681 return q, log
1682 else:
1683 return q
1684
1685
1686 def barycenter_unbalanced(
1687 A,
1688 M,
1689 reg,
1690 reg_m,
1691 method="sinkhorn",
1692 weights=None,
1693 numItermax=1000,
1694 stopThr=1e-6,
1695 verbose=False,
1696 log=False,
1697 **kwargs,
1698 ):
1699 r"""Compute the entropic unbalanced wasserstein barycenter of :math:`\mathbf{A}`.
1700
1701 The function solves the following optimization problem with :math:`\mathbf{a}`
1702
1703 .. math::
1704 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i W_{u_{reg}}(\mathbf{a},\mathbf{a}_i)
1705
1706 where :
1707
1708 - :math:`W_{u_{reg}}(\cdot,\cdot)` is the unbalanced entropic regularized Wasserstein distance (see :py:func:`ot.unbalanced.sinkhorn_unbalanced`)
1709 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
1710 - reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
1711 - reg_mis the marginal relaxation hyperparameter
1712
1713 The algorithm used for solving the problem is the generalized
1714 Sinkhorn-Knopp matrix scaling algorithm as proposed in :ref:`[10] <references-barycenter-unbalanced>`
1715
1716 Parameters
1717 ----------
1718 A : array-like (dim, n_hists)
1719 `n_hists` training distributions :math:`\mathbf{a}_i` of dimension `dim`
1720 M : array-like (dim, dim)
1721 ground metric matrix for OT.
1722 reg : float
1723 Entropy regularization term > 0
1724 reg_m: float
1725 Marginal relaxation term > 0
1726 weights : array-like (n_hists,) optional
1727 Weight of each distribution (barycentric coordinates)
1728 If None, uniform weights are used.
1729 numItermax : int, optional
1730 Max number of iterations
1731 stopThr : float, optional
1732 Stop threshold on error (> 0)
1733 verbose : bool, optional
1734 Print information along iterations
1735 log : bool, optional
1736 record log if True
1737
1738
1739 Returns
1740 -------
1741 a : (dim,) array-like
1742 Unbalanced Wasserstein barycenter
1743 log : dict
1744 log dictionary return only if log==True in parameters
1745
1746
1747 .. _references-barycenter-unbalanced:
1748 References
1749 ----------
1750 .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G.
1751 (2015). Iterative Bregman projections for regularized transportation
1752 problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
1753 .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).
1754 Scaling algorithms for unbalanced transport problems. arXiv preprin
1755 arXiv:1607.05816.
1756
1757 """
1758
1759 if method.lower() == "sinkhorn":
1760 return barycenter_unbalanced_sinkhorn(
1761 A,
1762 M,
1763 reg,
1764 reg_m,
1765 weights=weights,
1766 numItermax=numItermax,
1767 stopThr=stopThr,
1768 verbose=verbose,
1769 log=log,
1770 **kwargs,
1771 )
1772
1773 elif method.lower() == "sinkhorn_stabilized":
1774 return barycenter_unbalanced_stabilized(
1775 A,
1776 M,
1777 reg,
1778 reg_m,
1779 weights=weights,
1780 numItermax=numItermax,
1781 stopThr=stopThr,
1782 verbose=verbose,
1783 log=log,
1784 **kwargs,
1785 )
1786 elif method.lower() in ["sinkhorn_reg_scaling", "sinkhorn_translation_invariant"]:
1787 warnings.warn("Method not implemented yet. Using classic Sinkhorn Knopp")
1788 return barycenter_unbalanced(
1789 A,
1790 M,
1791 reg,
1792 reg_m,
1793 weights=weights,
1794 numItermax=numItermax,
1795 stopThr=stopThr,
1796 verbose=verbose,
1797 log=log,
1798 **kwargs,
1799 )
1800 else:
1801 raise ValueError("Unknown method '%s'." % method)