Debian Codegraph @

ot/bregman/_barycenter.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Bregman projections solvers for entropic regularized wasserstein barycenters
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 # Nicolas Courty <[email protected]>
8 # Hicham Janati <[email protected]>
9 # Ievgen Redko <[email protected]>
10 #
11 # License: MIT License
12
13 import warnings
14 import numpy as np
15
16 from ..utils import dist, list_to_array, unif
17 from ..backend import get_backend
18
19 from ._utils import geometricBar, geometricMean, projR, projC
20 from ._sinkhorn import sinkhorn
21
22
23 def barycenter(
24 A,
25 M,
26 reg,
27 weights=None,
28 method="sinkhorn",
29 numItermax=10000,
30 stopThr=1e-4,
31 verbose=False,
32 log=False,
33 warn=True,
34 **kwargs,
35 ):
36 r"""Compute the entropic regularized wasserstein barycenter of distributions :math:`\mathbf{A}`
37
38 The function solves the following optimization problem:
39
40 .. math::
41 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
42
43 where :
44
45 - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein
46 distance (see :py:func:`ot.bregman.sinkhorn`)
47 if `method` is `sinkhorn` or `sinkhorn_stabilized` or `sinkhorn_log`.
48 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix
49 :math:`\mathbf{A}`
50 - `reg` and :math:`\mathbf{M}` are respectively the regularization term and
51 the cost matrix for OT
52
53 The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling
54 algorithm as proposed in :ref:`[3] <references-barycenter>`
55
56 Parameters
57 ----------
58 A : array-like, shape (dim, n_hists)
59 `n_hists` training distributions :math:`\mathbf{a}_i` of size `dim`
60 M : array-like, shape (dim, dim)
61 loss matrix for OT
62 reg : float
63 Regularization term > 0
64 method : str (optional)
65 method used for the solver either 'sinkhorn' or 'sinkhorn_stabilized' or 'sinkhorn_log'
66 weights : array-like, shape (n_hists,)
67 Weights of each histogram :math:`\mathbf{a}_i` on the simplex (barycentric coordinates)
68 numItermax : int, optional
69 Max number of iterations
70 stopThr : float, optional
71 Stop threshold on error (>0)
72 verbose : bool, optional
73 Print information along iterations
74 log : bool, optional
75 record log if True
76 warn : bool, optional
77 if True, raises a warning if the algorithm doesn't convergence.
78
79
80 Returns
81 -------
82 a : (dim,) array-like
83 Wasserstein barycenter
84 log : dict
85 log dictionary return only if log==True in parameters
86
87
88 .. _references-barycenter:
89 References
90 ----------
91
92 .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015).
93 Iterative Bregman projections for regularized transportation problems.
94 SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
95
96 """
97
98 if method.lower() == "sinkhorn":
99 return barycenter_sinkhorn(
100 A,
101 M,
102 reg,
103 weights=weights,
104 numItermax=numItermax,
105 stopThr=stopThr,
106 verbose=verbose,
107 log=log,
108 warn=warn,
109 **kwargs,
110 )
111 elif method.lower() == "sinkhorn_stabilized":
112 return barycenter_stabilized(
113 A,
114 M,
115 reg,
116 weights=weights,
117 numItermax=numItermax,
118 stopThr=stopThr,
119 verbose=verbose,
120 log=log,
121 warn=warn,
122 **kwargs,
123 )
124 elif method.lower() == "sinkhorn_log":
125 return _barycenter_sinkhorn_log(
126 A,
127 M,
128 reg,
129 weights=weights,
130 numItermax=numItermax,
131 stopThr=stopThr,
132 verbose=verbose,
133 log=log,
134 warn=warn,
135 **kwargs,
136 )
137 else:
138 raise ValueError("Unknown method '%s'." % method)
139
140
141 def barycenter_sinkhorn(
142 A,
143 M,
144 reg,
145 weights=None,
146 numItermax=1000,
147 stopThr=1e-4,
148 verbose=False,
149 log=False,
150 warn=True,
151 ):
152 r"""Compute the entropic regularized wasserstein barycenter of distributions :math:`\mathbf{A}`
153
154 The function solves the following optimization problem:
155
156 .. math::
157 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
158
159 where :
160
161 - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance
162 (see :py:func:`ot.bregman.sinkhorn`)
163 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix
164 :math:`\mathbf{A}`
165 - `reg` and :math:`\mathbf{M}` are respectively the regularization term and
166 the cost matrix for OT
167
168 The algorithm used for solving the problem is the Sinkhorn-Knopp matrix
169 scaling algorithm as proposed in :ref:`[3]<references-barycenter-sinkhorn>`.
170
171 Parameters
172 ----------
173 A : array-like, shape (dim, n_hists)
174 `n_hists` training distributions :math:`\mathbf{a}_i` of size `dim`
175 M : array-like, shape (dim, dim)
176 loss matrix for OT
177 reg : float
178 Regularization term > 0
179 weights : array-like, shape (n_hists,)
180 Weights of each histogram :math:`\mathbf{a}_i` on the simplex (barycentric coordinates)
181 numItermax : int, optional
182 Max number of iterations
183 stopThr : float, optional
184 Stop threshold on error (>0)
185 verbose : bool, optional
186 Print information along iterations
187 log : bool, optional
188 record log if True
189 warn : bool, optional
190 if True, raises a warning if the algorithm doesn't convergence.
191
192
193 Returns
194 -------
195 a : (dim,) array-like
196 Wasserstein barycenter
197 log : dict
198 log dictionary return only if log==True in parameters
199
200
201 .. _references-barycenter-sinkhorn:
202 References
203 ----------
204
205 .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015).
206 Iterative Bregman projections for regularized transportation problems.
207 SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
208
209 """
210
211 A, M = list_to_array(A, M)
212
213 nx = get_backend(A, M)
214
215 if weights is None:
216 weights = nx.ones((A.shape[1],), type_as=A) / A.shape[1]
217 else:
218 assert len(weights) == A.shape[1]
219
220 if log:
221 log = {"err": []}
222
223 K = nx.exp(-M / reg)
224
225 err = 1
226
227 UKv = nx.dot(K, (A.T / nx.sum(K, axis=0)).T)
228
229 u = (geometricMean(UKv) / UKv.T).T
230
231 for ii in range(numItermax):
232 UKv = u * nx.dot(K.T, A / nx.dot(K, u))
233 u = (u.T * geometricBar(weights, UKv)).T / UKv
234
235 if ii % 10 == 1:
236 err = nx.sum(nx.std(UKv, axis=1))
237
238 # log and verbose print
239 if log:
240 log["err"].append(err)
241
242 if err < stopThr:
243 break
244 if verbose:
245 if ii % 200 == 0:
246 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
247 print("{:5d}|{:8e}|".format(ii, err))
248 else:
249 if warn:
250 warnings.warn(
251 "Sinkhorn did not converge. You might want to "
252 "increase the number of iterations `numItermax` "
253 "or the regularization parameter `reg`."
254 )
255 if log:
256 log["niter"] = ii
257 return geometricBar(weights, UKv), log
258 else:
259 return geometricBar(weights, UKv)
260
261
262 def free_support_sinkhorn_barycenter(
263 measures_locations,
264 measures_weights,
265 X_init,
266 reg,
267 b=None,
268 weights=None,
269 numItermax=100,
270 numInnerItermax=1000,
271 stopThr=1e-7,
272 verbose=False,
273 log=None,
274 **kwargs,
275 ):
276 r"""
277 Solves the free support (locations of the barycenters are optimized, not the weights) regularized Wasserstein barycenter problem (i.e. the weighted Frechet mean for the 2-Sinkhorn divergence), formally:
278
279 .. math::
280 \min_\mathbf{X} \quad \sum_{i=1}^N w_i W_{reg}^2(\mathbf{b}, \mathbf{X}, \mathbf{a}_i, \mathbf{X}_i)
281
282 where :
283
284 - :math:`w \in \mathbb{(0, 1)}^{N}`'s are the barycenter weights and sum to one
285 - `measure_weights` denotes the :math:`\mathbf{a}_i \in \mathbb{R}^{k_i}`: empirical measures weights (on simplex)
286 - `measures_locations` denotes the :math:`\mathbf{X}_i \in \mathbb{R}^{k_i, d}`: empirical measures atoms locations
287 - :math:`\mathbf{b} \in \mathbb{R}^{k}` is the desired weights vector of the barycenter
288
289 This problem is considered in :ref:`[20] <references-free-support-barycenter>` (Algorithm 2).
290 There are two differences with the following codes:
291
292 - we do not optimize over the weights
293 - we do not do line search for the locations updates, we use i.e. :math:`\theta = 1` in
294 :ref:`[20] <references-free-support-barycenter>` (Algorithm 2). This can be seen as a discrete
295 implementation of the fixed-point algorithm of
296 :ref:`[43] <references-free-support-barycenter>` proposed in the continuous setting.
297 - at each iteration, instead of solving an exact OT problem, we use the Sinkhorn algorithm for calculating the
298 transport plan in :ref:`[20] <references-free-support-barycenter>` (Algorithm 2).
299
300 Parameters
301 ----------
302 measures_locations : list of N (k_i,d) array-like
303 The discrete support of a measure supported on :math:`k_i` locations of a `d`-dimensional space
304 (:math:`k_i` can be different for each element of the list)
305 measures_weights : list of N (k_i,) array-like
306 Numpy arrays where each numpy array has :math:`k_i` non-negatives values summing to one
307 representing the weights of each discrete input measure
308
309 X_init : (k,d) array-like
310 Initialization of the support locations (on `k` atoms) of the barycenter
311 reg : float
312 Regularization term >0
313 b : (k,) array-like
314 Initialization of the weights of the barycenter (non-negatives, sum to 1)
315 weights : (N,) array-like
316 Initialization of the coefficients of the barycenter (non-negatives, sum to 1)
317
318 numItermax : int, optional
319 Max number of iterations
320 numInnerItermax : int, optional
321 Max number of iterations when calculating the transport plans with Sinkhorn
322 stopThr : float, optional
323 Stop threshold on error (>0)
324 verbose : bool, optional
325 Print information along iterations
326 log : bool, optional
327 record log if True
328
329 Returns
330 -------
331 X : (k,d) array-like
332 Support locations (on k atoms) of the barycenter
333
334 See Also
335 --------
336 ot.bregman.sinkhorn : Entropic regularized OT solver
337 ot.lp.free_support_barycenter : Barycenter solver based on Linear Programming
338
339 .. _references-free-support-barycenter:
340 References
341 ----------
342 .. [20] Cuturi, Marco, and Arnaud Doucet. "Fast computation of Wasserstein barycenters." International Conference on Machine Learning. 2014.
343
344 .. [43] Álvarez-Esteban, Pedro C., et al. "A fixed-point approach to barycenters in Wasserstein space." Journal of Mathematical Analysis and Applications 441.2 (2016): 744-762.
345
346 """
347 nx = get_backend(*measures_locations, *measures_weights, X_init)
348
349 iter_count = 0
350
351 N = len(measures_locations)
352 k = X_init.shape[0]
353 d = X_init.shape[1]
354 if b is None:
355 b = nx.ones((k,), type_as=X_init) / k
356 if weights is None:
357 weights = nx.ones((N,), type_as=X_init) / N
358
359 X = X_init
360
361 log_dict = {}
362 displacement_square_norms = []
363
364 displacement_square_norm = stopThr + 1.0
365
366 while displacement_square_norm > stopThr and iter_count < numItermax:
367 T_sum = nx.zeros((k, d), type_as=X_init)
368
369 for measure_locations_i, measure_weights_i, weight_i in zip(
370 measures_locations, measures_weights, weights
371 ):
372 M_i = dist(X, measure_locations_i)
373 T_i = sinkhorn(
374 b, measure_weights_i, M_i, reg=reg, numItermax=numInnerItermax, **kwargs
375 )
376 T_sum = T_sum + weight_i * 1.0 / b[:, None] * nx.dot(
377 T_i, measure_locations_i
378 )
379
380 displacement_square_norm = nx.sum((T_sum - X) ** 2)
381 if log:
382 displacement_square_norms.append(displacement_square_norm)
383
384 X = T_sum
385
386 if verbose:
387 print(
388 "iteration %d, displacement_square_norm=%f\n",
389 iter_count,
390 displacement_square_norm,
391 )
392
393 iter_count += 1
394
395 if log:
396 log_dict["displacement_square_norms"] = displacement_square_norms
397 return X, log_dict
398 else:
399 return X
400
401
402 def _barycenter_sinkhorn_log(
403 A,
404 M,
405 reg,
406 weights=None,
407 numItermax=1000,
408 stopThr=1e-4,
409 verbose=False,
410 log=False,
411 warn=True,
412 ):
413 r"""Compute the entropic wasserstein barycenter in log-domain"""
414
415 A, M = list_to_array(A, M)
416 dim, n_hists = A.shape
417
418 nx = get_backend(A, M)
419
420 if nx.__name__ in ("jax", "tf"):
421 raise NotImplementedError(
422 "Log-domain functions are not yet implemented"
423 " for Jax and tf. Use numpy or torch arrays instead."
424 )
425
426 if weights is None:
427 weights = nx.ones(n_hists, type_as=A) / n_hists
428 else:
429 assert len(weights) == A.shape[1]
430
431 if log:
432 log = {"err": []}
433
434 M = -M / reg
435 logA = nx.log(A + 1e-16)
436 log_KU, G = nx.zeros((2, *logA.shape), type_as=A)
437 err = 1
438 for ii in range(numItermax):
439 log_bar = nx.zeros(dim, type_as=A)
440 for k in range(n_hists):
441 f = logA[:, k] - nx.logsumexp(M + G[None, :, k], axis=1)
442 log_KU[:, k] = nx.logsumexp(M + f[:, None], axis=0)
443 log_bar = log_bar + weights[k] * log_KU[:, k]
444
445 if ii % 10 == 1:
446 err = nx.exp(G + log_KU).std(axis=1).sum()
447
448 # log and verbose print
449 if log:
450 log["err"].append(err)
451
452 if err < stopThr:
453 break
454 if verbose:
455 if ii % 200 == 0:
456 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
457 print("{:5d}|{:8e}|".format(ii, err))
458
459 G = log_bar[:, None] - log_KU
460
461 else:
462 if warn:
463 warnings.warn(
464 "Sinkhorn did not converge. You might want to "
465 "increase the number of iterations `numItermax` "
466 "or the regularization parameter `reg`."
467 )
468 if log:
469 log["niter"] = ii
470 return nx.exp(log_bar), log
471 else:
472 return nx.exp(log_bar)
473
474
475 def barycenter_stabilized(
476 A,
477 M,
478 reg,
479 tau=1e10,
480 weights=None,
481 numItermax=1000,
482 stopThr=1e-4,
483 verbose=False,
484 log=False,
485 warn=True,
486 ):
487 r"""Compute the entropic regularized wasserstein barycenter of distributions :math:`\mathbf{A}` with stabilization.
488
489 The function solves the following optimization problem:
490
491 .. math::
492 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
493
494 where :
495
496 - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein
497 distance (see :py:func:`ot.bregman.sinkhorn`)
498 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix
499 :math:`\mathbf{A}`
500 - `reg` and :math:`\mathbf{M}` are respectively the regularization term and
501 the cost matrix for OT
502
503 The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling
504 algorithm as proposed in :ref:`[3] <references-barycenter-stabilized>`
505
506 Parameters
507 ----------
508 A : array-like, shape (dim, n_hists)
509 `n_hists` training distributions :math:`\mathbf{a}_i` of size `dim`
510 M : array-like, shape (dim, dim)
511 loss matrix for OT
512 reg : float
513 Regularization term > 0
514 tau : float
515 threshold for max value in :math:`\mathbf{u}` or :math:`\mathbf{v}`
516 for log scaling
517 weights : array-like, shape (n_hists,)
518 Weights of each histogram :math:`\mathbf{a}_i` on the simplex (barycentric coordinates)
519 numItermax : int, optional
520 Max number of iterations
521 stopThr : float, optional
522 Stop threshold on error (>0)
523 verbose : bool, optional
524 Print information along iterations
525 log : bool, optional
526 record log if True
527 warn : bool, optional
528 if True, raises a warning if the algorithm doesn't convergence.
529
530
531 Returns
532 -------
533 a : (dim,) array-like
534 Wasserstein barycenter
535 log : dict
536 log dictionary return only if log==True in parameters
537
538
539 .. _references-barycenter-stabilized:
540 References
541 ----------
542
543 .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015).
544 Iterative Bregman projections for regularized transportation problems.
545 SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
546
547 """
548
549 A, M = list_to_array(A, M)
550
551 nx = get_backend(A, M)
552
553 dim, n_hists = A.shape
554 if weights is None:
555 weights = nx.ones((n_hists,), type_as=M) / n_hists
556 else:
557 assert len(weights) == A.shape[1]
558
559 if log:
560 log = {"err": []}
561
562 u = nx.ones((dim, n_hists), type_as=M) / dim
563 v = nx.ones((dim, n_hists), type_as=M) / dim
564
565 K = nx.exp(-M / reg)
566
567 err = 1.0
568 alpha = nx.zeros((dim,), type_as=M)
569 beta = nx.zeros((dim,), type_as=M)
570 q = nx.ones((dim,), type_as=M) / dim
571 for ii in range(numItermax):
572 qprev = q
573 Kv = nx.dot(K, v)
574 u = A / Kv
575 Ktu = nx.dot(K.T, u)
576 q = geometricBar(weights, Ktu)
577 Q = q[:, None]
578 v = Q / Ktu
579 absorbing = False
580 if nx.any(u > tau) or nx.any(v > tau):
581 absorbing = True
582 alpha += reg * nx.log(nx.max(u, 1))
583 beta += reg * nx.log(nx.max(v, 1))
584 K = nx.exp((alpha[:, None] + beta[None, :] - M) / reg)
585 v = nx.ones(tuple(v.shape), type_as=v)
586 Kv = nx.dot(K, v)
587 if (
588 nx.any(Ktu == 0.0)
589 or nx.any(nx.isnan(u))
590 or nx.any(nx.isnan(v))
591 or nx.any(nx.isinf(u))
592 or nx.any(nx.isinf(v))
593 ):
594 # we have reached the machine precision
595 # come back to previous solution and quit loop
596 warnings.warn("Numerical errors at iteration %s" % ii)
597 q = qprev
598 break
599 if (ii % 10 == 0 and not absorbing) or ii == 0:
600 # we can speed up the process by checking for the error only all
601 # the 10th iterations
602 err = nx.max(nx.abs(u * Kv - A))
603 if log:
604 log["err"].append(err)
605 if err < stopThr:
606 break
607 if verbose:
608 if ii % 50 == 0:
609 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
610 print("{:5d}|{:8e}|".format(ii, err))
611
612 else:
613 if warn:
614 warnings.warn(
615 "Stabilized Sinkhorn did not converge."
616 + "Try a larger entropy `reg`"
617 + "Or a larger absorption threshold `tau`."
618 )
619 if log:
620 log["niter"] = ii
621 log["logu"] = nx.log(u + 1e-16)
622 log["logv"] = nx.log(v + 1e-16)
623 return q, log
624 else:
625 return q
626
627
628 def barycenter_debiased(
629 A,
630 M,
631 reg,
632 weights=None,
633 method="sinkhorn",
634 numItermax=10000,
635 stopThr=1e-4,
636 verbose=False,
637 log=False,
638 warn=True,
639 **kwargs,
640 ):
641 r"""Compute the debiased Sinkhorn barycenter of distributions A
642
643 The function solves the following optimization problem:
644
645 .. math::
646 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i S_{reg}(\mathbf{a},\mathbf{a}_i)
647
648 where :
649
650 - :math:`S_{reg}(\cdot,\cdot)` is the debiased Sinkhorn divergence
651 (see :py:func:`ot.bregman.empirical_sinkhorn_divergence`)
652 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix
653 :math:`\mathbf{A}`
654 - `reg` and :math:`\mathbf{M}` are respectively the regularization term and
655 the cost matrix for OT
656
657 The algorithm used for solving the problem is the debiased Sinkhorn
658 algorithm as proposed in :ref:`[37] <references-barycenter-debiased>`
659
660 Parameters
661 ----------
662 A : array-like, shape (dim, n_hists)
663 `n_hists` training distributions :math:`\mathbf{a}_i` of size `dim`
664 M : array-like, shape (dim, dim)
665 loss matrix for OT
666 reg : float
667 Regularization term > 0
668 method : str (optional)
669 method used for the solver either 'sinkhorn' or 'sinkhorn_log'
670 weights : array-like, shape (n_hists,)
671 Weights of each histogram :math:`\mathbf{a}_i` on the simplex (barycentric coordinates)
672 numItermax : int, optional
673 Max number of iterations
674 stopThr : float, optional
675 Stop threshold on error (>0)
676 verbose : bool, optional
677 Print information along iterations
678 log : bool, optional
679 record log if True
680 warn : bool, optional
681 if True, raises a warning if the algorithm doesn't convergence.
682
683
684 Returns
685 -------
686 a : (dim,) array-like
687 Wasserstein barycenter
688 log : dict
689 log dictionary return only if log==True in parameters
690
691
692 .. _references-barycenter-debiased:
693 References
694 ----------
695 .. [37] Janati, H., Cuturi, M., Gramfort, A. Proceedings of the 37th International
696 Conference on Machine Learning, PMLR 119:4692-4701, 2020
697 """
698
699 if method.lower() == "sinkhorn":
700 return _barycenter_debiased(
701 A,
702 M,
703 reg,
704 weights=weights,
705 numItermax=numItermax,
706 stopThr=stopThr,
707 verbose=verbose,
708 log=log,
709 warn=warn,
710 **kwargs,
711 )
712 elif method.lower() == "sinkhorn_log":
713 return _barycenter_debiased_log(
714 A,
715 M,
716 reg,
717 weights=weights,
718 numItermax=numItermax,
719 stopThr=stopThr,
720 verbose=verbose,
721 log=log,
722 warn=warn,
723 **kwargs,
724 )
725 else:
726 raise ValueError("Unknown method '%s'." % method)
727
728
729 def _barycenter_debiased(
730 A,
731 M,
732 reg,
733 weights=None,
734 numItermax=1000,
735 stopThr=1e-4,
736 verbose=False,
737 log=False,
738 warn=True,
739 ):
740 r"""Compute the debiased sinkhorn barycenter of distributions A."""
741
742 A, M = list_to_array(A, M)
743
744 nx = get_backend(A, M)
745
746 if weights is None:
747 weights = nx.ones((A.shape[1],), type_as=A) / A.shape[1]
748 else:
749 assert len(weights) == A.shape[1]
750
751 if log:
752 log = {"err": []}
753
754 K = nx.exp(-M / reg)
755
756 err = 1
757
758 UKv = nx.dot(K, (A.T / nx.sum(K, axis=0)).T)
759
760 u = (geometricMean(UKv) / UKv.T).T
761 c = nx.ones(A.shape[0], type_as=A)
762 bar = nx.ones(A.shape[0], type_as=A)
763
764 for ii in range(numItermax):
765 bold = bar
766 UKv = nx.dot(K, A / nx.dot(K, u))
767 bar = c * geometricBar(weights, UKv)
768 u = bar[:, None] / UKv
769 c = (c * bar / nx.dot(K, c)) ** 0.5
770
771 if ii % 10 == 9:
772 err = abs(bar - bold).max() / max(bar.max(), 1.0)
773
774 # log and verbose print
775 if log:
776 log["err"].append(err)
777
778 # debiased Sinkhorn does not converge monotonically
779 # guarantee a few iterations are done before stopping
780 if err < stopThr and ii > 20:
781 break
782 if verbose:
783 if ii % 200 == 0:
784 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
785 print("{:5d}|{:8e}|".format(ii, err))
786 else:
787 if warn:
788 warnings.warn(
789 "Sinkhorn did not converge. You might want to "
790 "increase the number of iterations `numItermax` "
791 "or the regularization parameter `reg`."
792 )
793 if log:
794 log["niter"] = ii
795 return bar, log
796 else:
797 return bar
798
799
800 def _barycenter_debiased_log(
801 A,
802 M,
803 reg,
804 weights=None,
805 numItermax=1000,
806 stopThr=1e-4,
807 verbose=False,
808 log=False,
809 warn=True,
810 ):
811 r"""Compute the debiased sinkhorn barycenter in log domain."""
812
813 A, M = list_to_array(A, M)
814 dim, n_hists = A.shape
815
816 nx = get_backend(A, M)
817 if nx.__name__ in ("jax", "tf"):
818 raise NotImplementedError(
819 "Log-domain functions are not yet implemented"
820 " for Jax and TF. Use numpy or torch arrays instead."
821 )
822
823 if weights is None:
824 weights = nx.ones(n_hists, type_as=A) / n_hists
825 else:
826 assert len(weights) == A.shape[1]
827
828 if log:
829 log = {"err": []}
830
831 M = -M / reg
832 logA = nx.log(A + 1e-16)
833 log_KU, G = nx.zeros((2, *logA.shape), type_as=A)
834 c = nx.zeros(dim, type_as=A)
835 err = 1
836 for ii in range(numItermax):
837 log_bar = nx.zeros(dim, type_as=A)
838 for k in range(n_hists):
839 f = logA[:, k] - nx.logsumexp(M + G[None, :, k], axis=1)
840 log_KU[:, k] = nx.logsumexp(M + f[:, None], axis=0)
841 log_bar += weights[k] * log_KU[:, k]
842 log_bar += c
843 if ii % 10 == 1:
844 err = nx.exp(G + log_KU).std(axis=1).sum()
845
846 # log and verbose print
847 if log:
848 log["err"].append(err)
849
850 if err < stopThr and ii > 20:
851 break
852 if verbose:
853 if ii % 200 == 0:
854 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
855 print("{:5d}|{:8e}|".format(ii, err))
856
857 G = log_bar[:, None] - log_KU
858 for _ in range(10):
859 c = 0.5 * (c + log_bar - nx.logsumexp(M + c[:, None], axis=0))
860
861 else:
862 if warn:
863 warnings.warn(
864 "Sinkhorn did not converge. You might want to "
865 "increase the number of iterations `numItermax` "
866 "or the regularization parameter `reg`."
867 )
868 if log:
869 log["niter"] = ii
870 return nx.exp(log_bar), log
871 else:
872 return nx.exp(log_bar)
873
874
875 def jcpot_barycenter(
876 Xs,
877 Ys,
878 Xt,
879 reg,
880 metric="sqeuclidean",
881 numItermax=100,
882 stopThr=1e-6,
883 verbose=False,
884 log=False,
885 warn=True,
886 **kwargs,
887 ):
888 r"""Joint OT and proportion estimation for multi-source target shift as
889 proposed in :ref:`[27] <references-jcpot-barycenter>`
890
891 The function solves the following optimization problem:
892
893 .. math::
894
895 \mathbf{h} = \mathop{\arg \min}_{\mathbf{h}} \quad \sum_{k=1}^{K} \lambda_k
896 W_{reg}((\mathbf{D}_2^{(k)} \mathbf{h})^T, \mathbf{a})
897
898 s.t. \ \forall k, \mathbf{D}_1^{(k)} \gamma_k \mathbf{1}_n= \mathbf{h}
899
900 where :
901
902 - :math:`\lambda_k` is the weight of `k`-th source domain
903 - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance
904 (see :py:func:`ot.bregman.sinkhorn`)
905 - :math:`\mathbf{D}_2^{(k)}` is a matrix of weights related to `k`-th source domain
906 defined as in [p. 5, :ref:`27 <references-jcpot-barycenter>`], its expected shape
907 is :math:`(n_k, C)` where :math:`n_k` is the number of elements in the `k`-th source
908 domain and `C` is the number of classes
909 - :math:`\mathbf{h}` is a vector of estimated proportions in the target domain of size `C`
910 - :math:`\mathbf{a}` is a uniform vector of weights in the target domain of size `n`
911 - :math:`\mathbf{D}_1^{(k)}` is a matrix of class assignments defined as in
912 [p. 5, :ref:`27 <references-jcpot-barycenter>`], its expected shape is :math:`(n_k, C)`
913
914 The problem consist in solving a Wasserstein barycenter problem to estimate
915 the proportions :math:`\mathbf{h}` in the target domain.
916
917 The algorithm used for solving the problem is the Iterative Bregman projections algorithm
918 with two sets of marginal constraints related to the unknown vector
919 :math:`\mathbf{h}` and uniform target distribution.
920
921 Parameters
922 ----------
923 Xs : list of K array-like(nsk,d)
924 features of all source domains' samples
925 Ys : list of K array-like(nsk,)
926 labels of all source domains' samples
927 Xt : array-like (nt,d)
928 samples in the target domain
929 reg : float
930 Regularization term > 0
931 metric : string, optional (default="sqeuclidean")
932 The ground metric for the Wasserstein problem
933 numItermax : int, optional
934 Max number of iterations
935 stopThr : float, optional
936 Stop threshold on relative change in the barycenter (>0)
937 verbose : bool, optional (default=False)
938 Controls the verbosity of the optimization algorithm
939 log : bool, optional
940 record log if True
941 warn : bool, optional
942 if True, raises a warning if the algorithm doesn't convergence.
943
944 Returns
945 -------
946 h : (C,) array-like
947 proportion estimation in the target domain
948 log : dict
949 log dictionary return only if log==True in parameters
950
951
952 .. _references-jcpot-barycenter:
953 References
954 ----------
955
956 .. [27] Ievgen Redko, Nicolas Courty, Rémi Flamary, Devis Tuia
957 "Optimal transport for multi-source domain adaptation under target shift",
958 International Conference on Artificial Intelligence and Statistics (AISTATS), 2019.
959 """
960
961 Xs = list_to_array(*Xs)
962 Ys = list_to_array(*Ys)
963 Xt = list_to_array(Xt)
964
965 nx = get_backend(*Xs, *Ys, Xt)
966
967 nbclasses = len(nx.unique(Ys[0]))
968 nbdomains = len(Xs)
969
970 # log dictionary
971 if log:
972 log = {"niter": 0, "err": [], "M": [], "D1": [], "D2": [], "gamma": []}
973
974 K = []
975 M = []
976 D1 = []
977 D2 = []
978
979 # For each source domain, build cost matrices M, Gibbs kernels K and corresponding matrices D_1 and D_2
980 for d in range(nbdomains):
981 dom = {}
982 nsk = Xs[d].shape[0] # get number of elements for this domain
983 dom["nbelem"] = nsk
984 classes = nx.unique(Ys[d]) # get number of classes for this domain
985
986 # format classes to start from 0 for convenience
987 if nx.min(classes) != 0:
988 Ys[d] -= nx.min(classes)
989 classes = nx.unique(Ys[d])
990
991 # build the corresponding D_1 and D_2 matrices
992 Dtmp1 = np.zeros((nbclasses, nsk))
993 Dtmp2 = np.zeros((nbclasses, nsk))
994
995 for c in classes:
996 nbelemperclass = float(nx.sum(Ys[d] == c))
997 if nbelemperclass != 0:
998 Dtmp1[int(c), nx.to_numpy(Ys[d] == c)] = 1.0
999 Dtmp2[int(c), nx.to_numpy(Ys[d] == c)] = 1.0 / (nbelemperclass)
1000 D1.append(nx.from_numpy(Dtmp1, type_as=Xs[0]))
1001 D2.append(nx.from_numpy(Dtmp2, type_as=Xs[0]))
1002
1003 # build the cost matrix and the Gibbs kernel
1004 Mtmp = dist(Xs[d], Xt, metric=metric)
1005 M.append(Mtmp)
1006
1007 Ktmp = nx.exp(-Mtmp / reg)
1008 K.append(Ktmp)
1009
1010 # uniform target distribution
1011 a = nx.from_numpy(unif(Xt.shape[0]), type_as=Xs[0])
1012
1013 err = 1
1014 old_bary = nx.ones((nbclasses,), type_as=Xs[0])
1015
1016 for ii in range(numItermax):
1017 bary = nx.zeros((nbclasses,), type_as=Xs[0])
1018
1019 # update coupling matrices for marginal constraints w.r.t. uniform target distribution
1020 for d in range(nbdomains):
1021 K[d] = projC(K[d], a)
1022 other = nx.sum(K[d], axis=1)
1023 bary += nx.log(nx.dot(D1[d], other)) / nbdomains
1024
1025 bary = nx.exp(bary)
1026
1027 # update coupling matrices for marginal constraints w.r.t. unknown proportions based on [Prop 4., 27]
1028 for d in range(nbdomains):
1029 new = nx.dot(D2[d].T, bary)
1030 K[d] = projR(K[d], new)
1031
1032 err = nx.norm(bary - old_bary)
1033
1034 old_bary = bary
1035
1036 if log:
1037 log["err"].append(err)
1038
1039 if err < stopThr:
1040 break
1041 if verbose:
1042 if ii % 200 == 0:
1043 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
1044 print("{:5d}|{:8e}|".format(ii, err))
1045 else:
1046 if warn:
1047 warnings.warn(
1048 "Algorithm did not converge. You might want to "
1049 "increase the number of iterations `numItermax` "
1050 "or the regularization parameter `reg`."
1051 )
1052 bary = bary / nx.sum(bary)
1053
1054 if log:
1055 log["niter"] = ii
1056 log["M"] = M
1057 log["D1"] = D1
1058 log["D2"] = D2
1059 log["gamma"] = K
1060 return bary, log
1061 else:
1062 return bary