Debian Codegraph @

ot/stochastic.py

raw symbols SCIP
1 """
2 Stochastic solvers for regularized OT.
3
4
5 """
6
7 # Authors: Kilian Fatras <[email protected]>
8 # Rémi Flamary <[email protected]>
9 #
10 # License: MIT License
11
12 import numpy as np
13 from .utils import dist, check_random_state
14 from .backend import get_backend
15
16 ##############################################################################
17 # Optimization toolbox for SEMI - DUAL problems
18 ##############################################################################
19
20
21 def coordinate_grad_semi_dual(b, M, reg, beta, i):
22 r"""
23 Compute the coordinate gradient update for regularized discrete distributions for :math:`(i, :)`
24
25 The function computes the gradient of the semi dual problem:
26
27 .. math::
28 \max_\mathbf{v} \ \sum_i \mathbf{a}_i \left[ \sum_j \mathbf{v}_j \mathbf{b}_j - \mathrm{reg}
29 \cdot \log \left( \sum_j \mathbf{b}_j
30 \exp \left( \frac{\mathbf{v}_j - \mathbf{M}_{i,j}}{\mathrm{reg}}
31 \right) \right) \right]
32
33 Where :
34
35 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
36 - :math:`\mathbf{v}` is a dual variable in :math:`\mathbb{R}^{nt}`
37 - reg is the regularization term
38 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
39
40 The algorithm used for solving the problem is the ASGD & SAG algorithms
41 as proposed in :ref:`[18] <references-coordinate-grad-semi-dual>` [alg.1 & alg.2]
42
43
44 Parameters
45 ----------
46 b : ndarray, shape (nt,)
47 Target measure.
48 M : ndarray, shape (ns, nt)
49 Cost matrix.
50 reg : float
51 Regularization term > 0.
52 v : ndarray, shape (nt,)
53 Dual variable.
54 i : int
55 Picked number `i`.
56
57 Returns
58 -------
59 coordinate gradient : ndarray, shape (nt,)
60
61 .. _references-coordinate-grad-semi-dual:
62 References
63 ----------
64 .. [18] Genevay, A., Cuturi, M., Peyré, G. & Bach, F. (2016) Stochastic Optimization for Large-scale Optimal Transport. Advances in Neural Information Processing Systems (2016).
65 """
66 r = M[i, :] - beta
67 exp_beta = np.exp(-r / reg) * b
68 khi = exp_beta / (np.sum(exp_beta))
69 return b - khi
70
71
72 def sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None, random_state=None):
73 r"""
74 Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem
75
76 The function solves the following optimization problem:
77
78 .. math::
79 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
80 \mathrm{reg} \cdot\Omega(\gamma)
81
82 s.t. \ \gamma \mathbf{1} = \mathbf{a}
83
84 \gamma^T \mathbf{1} = \mathbf{b}
85
86 \gamma \geq 0
87
88 Where :
89
90 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
91 - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
92 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
93
94 The algorithm used for solving the problem is the SAG algorithm
95 as proposed in :ref:`[18] <references-sag-entropic-transport>` [alg.1]
96
97
98 Parameters
99 ----------
100
101 a : ndarray, shape (ns,),
102 Source measure.
103 b : ndarray, shape (nt,),
104 Target measure.
105 M : ndarray, shape (ns, nt),
106 Cost matrix.
107 reg : float
108 Regularization term > 0
109 numItermax : int
110 Number of iteration.
111 lr : float
112 Learning rate.
113 random_state : int, RandomState instance or None, default=None
114 Determines random number generation. Pass an int for reproducible
115 output across multiple function calls.
116
117 Returns
118 -------
119 v : ndarray, shape (`nt`,)
120 Dual variable.
121
122 .. _references-sag-entropic-transport:
123 References
124 ----------
125 .. [18] Genevay, A., Cuturi, M., Peyré, G. & Bach, F. (2016) Stochastic Optimization for Large-scale Optimal Transport. Advances in Neural Information Processing Systems (2016).
126 """
127
128 if lr is None:
129 lr = 1.0 / max(a / reg)
130 n_source = np.shape(M)[0]
131 n_target = np.shape(M)[1]
132 cur_beta = np.zeros(n_target)
133 stored_gradient = np.zeros((n_source, n_target))
134 sum_stored_gradient = np.zeros(n_target)
135 rng = check_random_state(random_state)
136 for _ in range(numItermax):
137 i = rng.randint(n_source)
138 cur_coord_grad = a[i] * coordinate_grad_semi_dual(b, M, reg, cur_beta, i)
139 sum_stored_gradient += cur_coord_grad - stored_gradient[i]
140 stored_gradient[i] = cur_coord_grad
141 cur_beta += lr * (1.0 / n_source) * sum_stored_gradient
142 return cur_beta
143
144
145 def averaged_sgd_entropic_transport(
146 a, b, M, reg, numItermax=300000, lr=None, random_state=None
147 ):
148 r"""
149 Compute the ASGD algorithm to solve the regularized semi continuous measures optimal transport max problem
150
151 The function solves the following optimization problem:
152
153 .. math::
154 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
155 \mathrm{reg}\cdot\Omega(\gamma)
156
157 s.t. \gamma \mathbf{1} = \mathbf{a}
158
159 \gamma^T \mathbf{1} = \mathbf{b}
160
161 \gamma \geq 0
162
163 Where :
164
165 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
166 - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
167 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
168
169 The algorithm used for solving the problem is the ASGD algorithm
170 as proposed in :ref:`[18] <references-averaged-sgd-entropic-transport>` [alg.2]
171
172
173 Parameters
174 ----------
175 b : ndarray, shape (nt,)
176 target measure
177 M : ndarray, shape (ns, nt)
178 cost matrix
179 reg : float
180 Regularization term > 0
181 numItermax : int
182 Number of iteration.
183 lr : float
184 Learning rate.
185 random_state : int, RandomState instance or None, default=None
186 Determines random number generation. Pass an int for reproducible
187 output across multiple function calls.
188
189 Returns
190 -------
191 ave_v : ndarray, shape (`nt`,)
192 dual variable
193
194 .. _references-averaged-sgd-entropic-transport:
195 References
196 ----------
197 .. [18] Genevay, A., Cuturi, M., Peyré, G. & Bach, F. (2016) Stochastic Optimization for Large-scale Optimal Transport. Advances in Neural Information Processing Systems (2016).
198 """
199
200 if lr is None:
201 lr = 1.0 / max(a / reg)
202 n_source = np.shape(M)[0]
203 n_target = np.shape(M)[1]
204 cur_beta = np.zeros(n_target)
205 ave_beta = np.zeros(n_target)
206 rng = check_random_state(random_state)
207 for cur_iter in range(numItermax):
208 k = cur_iter + 1
209 i = rng.randint(n_source)
210 cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i)
211 cur_beta += (lr / np.sqrt(k)) * cur_coord_grad
212 ave_beta = (1.0 / k) * cur_beta + (1 - 1.0 / k) * ave_beta
213 return ave_beta
214
215
216 def c_transform_entropic(b, M, reg, beta):
217 r"""
218 The goal is to recover u from the c-transform.
219
220 The function computes the c-transform of a dual variable from the other
221 dual variable:
222
223 .. math::
224 \mathbf{u} = \mathbf{v}^{c,reg} = - \mathrm{reg} \sum_j \mathbf{b}_j
225 \exp\left( \frac{\mathbf{v} - \mathbf{M}}{\mathrm{reg}} \right)
226
227 Where :
228
229 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
230 - :math:`\mathbf{u}`, :math:`\mathbf{v}` are dual variables in :math:`\mathbb{R}^{ns} \times \mathbb{R}^{nt}`
231 - reg is the regularization term
232
233 It is used to recover an optimal u from optimal v solving the semi dual
234 problem, see Proposition 2.1 of :ref:`[18] <references-c-transform-entropic>`
235
236
237 Parameters
238 ----------
239 b : ndarray, shape (nt,)
240 Target measure
241 M : ndarray, shape (ns, nt)
242 Cost matrix
243 reg : float
244 Regularization term > 0
245 v : ndarray, shape (nt,)
246 Dual variable.
247
248 Returns
249 -------
250 u : ndarray, shape (`ns`,)
251 Dual variable.
252
253 .. _references-c-transform-entropic:
254 References
255 ----------
256 .. [18] Genevay, A., Cuturi, M., Peyré, G. & Bach, F. (2016) Stochastic Optimization for Large-scale Optimal Transport. Advances in Neural Information Processing Systems (2016).
257 """
258
259 n_source = np.shape(M)[0]
260 alpha = np.zeros(n_source)
261 for i in range(n_source):
262 r = M[i, :] - beta
263 min_r = np.min(r)
264 exp_beta = np.exp(-(r - min_r) / reg) * b
265 alpha[i] = min_r - reg * np.log(np.sum(exp_beta))
266 return alpha
267
268
269 def solve_semi_dual_entropic(
270 a, b, M, reg, method, numItermax=10000, lr=None, log=False
271 ):
272 r"""
273 Compute the transportation matrix to solve the regularized discrete measures optimal transport max problem
274
275 The function solves the following optimization problem:
276
277 .. math::
278 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
279 \mathrm{reg} \cdot\Omega(\gamma)
280
281 s.t. \ \gamma \mathbf{1} = \mathbf{a}
282
283 \gamma^T \mathbf{1} = \mathbf{b}
284
285 \gamma \geq 0
286
287 Where :
288
289 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
290 - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
291 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
292
293 The algorithm used for solving the problem is the SAG or ASGD algorithms
294 as proposed in :ref:`[18] <references-solve-semi-dual-entropic>`
295
296
297 Parameters
298 ----------
299
300 a : ndarray, shape (ns,)
301 source measure
302 b : ndarray, shape (nt,)
303 target measure
304 M : ndarray, shape (ns, nt)
305 cost matrix
306 reg : float
307 Regularization term > 0
308 method : str
309 used method (SAG or ASGD)
310 numItermax : int
311 number of iteration
312 lr : float
313 learning rate
314 n_source : int
315 size of the source measure
316 n_target : int
317 size of the target measure
318 log : bool, optional
319 record log if True
320
321 Returns
322 -------
323 pi : ndarray, shape (ns, nt)
324 transportation matrix
325 log : dict
326 log dictionary return only if log==True in parameters
327
328 .. _references-solve-semi-dual-entropic:
329 References
330 ----------
331 .. [18] Genevay, A., Cuturi, M., Peyré, G. & Bach, F. (2016) Stochastic Optimization for Large-scale Optimal Transport. Advances in Neural Information Processing Systems (2016).
332 """
333
334 if method.lower() == "sag":
335 opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr)
336 elif method.lower() == "asgd":
337 opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr)
338 else:
339 print("Please, select your method between SAG and ASGD")
340 return None
341
342 opt_alpha = c_transform_entropic(b, M, reg, opt_beta)
343 pi = (
344 np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg)
345 * a[:, None]
346 * b[None, :]
347 )
348
349 if log:
350 log = {}
351 log["alpha"] = opt_alpha
352 log["beta"] = opt_beta
353 return pi, log
354 else:
355 return pi
356
357
358 ##############################################################################
359 # Optimization toolbox for DUAL problems
360 ##############################################################################
361
362
363 def batch_grad_dual(a, b, M, reg, alpha, beta, batch_size, batch_alpha, batch_beta):
364 r"""
365 Computes the partial gradient of the dual optimal transport problem.
366
367 For each :math:`(i,j)` in a batch of coordinates, the partial gradients are :
368
369 .. math::
370 \partial_{\mathbf{u}_i} F = \frac{b_s}{l_v} \mathbf{u}_i -
371 \sum_{j \in B_v} \mathbf{a}_i \mathbf{b}_j
372 \exp\left( \frac{\mathbf{u}_i + \mathbf{v}_j - \mathbf{M}_{i,j}}{\mathrm{reg}} \right)
373
374 \partial_{\mathbf{v}_j} F = \frac{b_s}{l_u} \mathbf{v}_j -
375 \sum_{i \in B_u} \mathbf{a}_i \mathbf{b}_j
376 \exp\left( \frac{\mathbf{u}_i + \mathbf{v}_j - \mathbf{M}_{i,j}}{\mathrm{reg}} \right)
377
378 Where :
379
380 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
381 - :math:`\mathbf{u}`, :math:`\mathbf{v}` are dual variables in :math:`\mathbb{R}^{ns} \times \mathbb{R}^{nt}`
382 - reg is the regularization term
383 - :math:`B_u` and :math:`B_v` are lists of index
384 - :math:`b_s` is the size of the batches :math:`B_u` and :math:`B_v`
385 - :math:`l_u` and :math:`l_v` are the lengths of :math:`B_u` and :math:`B_v`
386 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
387
388
389 The algorithm used for solving the dual problem is the SGD algorithm
390 as proposed in :ref:`[19] <references-batch-grad-dual>` [alg.1]
391
392
393 Parameters
394 ----------
395 a : ndarray, shape (ns,)
396 source measure
397 b : ndarray, shape (nt,)
398 target measure
399 M : ndarray, shape (ns, nt)
400 cost matrix
401 reg : float
402 Regularization term > 0
403 alpha : ndarray, shape (ns,)
404 dual variable
405 beta : ndarray, shape (nt,)
406 dual variable
407 batch_size : int
408 size of the batch
409 batch_alpha : ndarray, shape (bs,)
410 batch of index of alpha
411 batch_beta : ndarray, shape (bs,)
412 batch of index of beta
413
414 Returns
415 -------
416 grad : ndarray, shape (`ns`,)
417 partial grad F
418
419 .. _references-batch-grad-dual:
420 References
421 ----------
422 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. Large-scale Optimal Transport and Mapping Estimation. International Conference on Learning Representation (2018)
423 """
424 G = -(
425 np.exp(
426 (
427 alpha[batch_alpha, None]
428 + beta[None, batch_beta]
429 - M[batch_alpha, :][:, batch_beta]
430 )
431 / reg
432 )
433 * a[batch_alpha, None]
434 * b[None, batch_beta]
435 )
436 grad_beta = np.zeros(np.shape(M)[1])
437 grad_alpha = np.zeros(np.shape(M)[0])
438 grad_beta[batch_beta] = b[batch_beta] * len(batch_alpha) / np.shape(M)[0] + G.sum(0)
439 grad_alpha[batch_alpha] = a[batch_alpha] * len(batch_beta) / np.shape(M)[1] + G.sum(
440 1
441 )
442
443 return grad_alpha, grad_beta
444
445
446 def sgd_entropic_regularization(
447 a, b, M, reg, batch_size, numItermax, lr, random_state=None
448 ):
449 r"""
450 Compute the sgd algorithm to solve the regularized discrete measures optimal transport dual problem
451
452 The function solves the following optimization problem:
453
454 .. math::
455 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
456 \mathrm{reg} \cdot\Omega(\gamma)
457
458 s.t. \ \gamma \mathbf{1} = \mathbf{a}
459
460 \gamma^T \mathbf{1} = \mathbf{b}
461
462 \gamma \geq 0
463
464 Where :
465
466 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
467 - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
468 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
469
470 Parameters
471 ----------
472 a : ndarray, shape (ns,)
473 source measure
474 b : ndarray, shape (nt,)
475 target measure
476 M : ndarray, shape (ns, nt)
477 cost matrix
478 reg : float
479 Regularization term > 0
480 batch_size : int
481 size of the batch
482 numItermax : int
483 number of iteration
484 lr : float
485 learning rate
486 random_state : int, RandomState instance or None, default=None
487 Determines random number generation. Pass an int for reproducible
488 output across multiple function calls.
489
490 Returns
491 -------
492 alpha : ndarray, shape (ns,)
493 dual variable
494 beta : ndarray, shape (nt,)
495 dual variable
496
497 References
498 ----------
499 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. Large-scale Optimal Transport and Mapping Estimation. International Conference on Learning Representation (2018)
500 """
501
502 n_source = np.shape(M)[0]
503 n_target = np.shape(M)[1]
504 cur_alpha = np.zeros(n_source)
505 cur_beta = np.zeros(n_target)
506 rng = check_random_state(random_state)
507 for cur_iter in range(numItermax):
508 k = np.sqrt(cur_iter + 1)
509 batch_alpha = rng.choice(n_source, batch_size, replace=False)
510 batch_beta = rng.choice(n_target, batch_size, replace=False)
511 update_alpha, update_beta = batch_grad_dual(
512 a, b, M, reg, cur_alpha, cur_beta, batch_size, batch_alpha, batch_beta
513 )
514 cur_alpha[batch_alpha] += (lr / k) * update_alpha[batch_alpha]
515 cur_beta[batch_beta] += (lr / k) * update_beta[batch_beta]
516
517 return cur_alpha, cur_beta
518
519
520 def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1, log=False):
521 r"""
522 Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem
523
524 The function solves the following optimization problem:
525
526 .. math::
527 \gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F +
528 \mathrm{reg} \cdot\Omega(\gamma)
529
530 s.t. \ \gamma \mathbf{1} = \mathbf{a}
531
532 \gamma^T \mathbf{1} = \mathbf{b}
533
534 \gamma \geq 0
535
536 Where :
537
538 - :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix
539 - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
540 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
541
542 Parameters
543 ----------
544 a : ndarray, shape (ns,)
545 source measure
546 b : ndarray, shape (nt,)
547 target measure
548 M : ndarray, shape (ns, nt)
549 cost matrix
550 reg : float
551 Regularization term > 0
552 batch_size : int
553 size of the batch
554 numItermax : int
555 number of iteration
556 lr : float
557 learning rate
558 log : bool, optional
559 record log if True
560
561 Returns
562 -------
563 pi : ndarray, shape (ns, nt)
564 transportation matrix
565 log : dict
566 log dictionary return only if log==True in parameters
567
568 References
569 ----------
570 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. Large-scale Optimal Transport and Mapping Estimation. International Conference on Learning Representation (2018)
571 """
572
573 opt_alpha, opt_beta = sgd_entropic_regularization(
574 a, b, M, reg, batch_size, numItermax, lr
575 )
576 pi = (
577 np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg)
578 * a[:, None]
579 * b[None, :]
580 )
581 if log:
582 log = {}
583 log["alpha"] = opt_alpha
584 log["beta"] = opt_beta
585 return pi, log
586 else:
587 return pi
588
589
590 ################################################################################
591 # Losses for stochastic optimization
592 ################################################################################
593
594
595 def loss_dual_entropic(u, v, xs, xt, reg=1, ws=None, wt=None, metric="sqeuclidean"):
596 r"""
597 Compute the dual loss of the entropic OT as in equation (6)-(7) of [19]
598
599 This loss is backend compatible and can be used for stochastic optimization
600 of the dual potentials. It can be used on the full dataset (beware of
601 memory) or on minibatches.
602
603
604 Parameters
605 ----------
606 u : array-like, shape (ns,)
607 Source dual potential
608 v : array-like, shape (nt,)
609 Target dual potential
610 xs : array-like, shape (ns,d)
611 Source samples
612 xt : array-like, shape (ns,d)
613 Target samples
614 reg : float
615 Regularization term > 0 (default=1)
616 ws : array-like, shape (ns,), optional
617 Source sample weights (default unif)
618 wt : array-like, shape (ns,), optional
619 Target sample weights (default unif)
620 metric : string, callable
621 Ground metric for OT (default quadratic). Can be given as a callable
622 function taking (xs,xt) as parameters.
623
624 Returns
625 -------
626 dual_loss : array-like
627 Dual loss (to maximize)
628
629
630 References
631 ----------
632 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. Large-scale Optimal Transport and Mapping Estimation. International Conference on Learning Representation (2018)
633 """
634
635 nx = get_backend(u, v, xs, xt)
636
637 if ws is None:
638 ws = nx.ones(xs.shape[0], type_as=xs) / xs.shape[0]
639
640 if wt is None:
641 wt = nx.ones(xt.shape[0], type_as=xt) / xt.shape[0]
642
643 if callable(metric):
644 M = metric(xs, xt)
645 else:
646 M = dist(xs, xt, metric=metric)
647
648 F = -reg * nx.exp((u[:, None] + v[None, :] - M) / reg)
649
650 return nx.sum(u * ws) + nx.sum(v * wt) + nx.sum(ws[:, None] * F * wt[None, :])
651
652
653 def plan_dual_entropic(u, v, xs, xt, reg=1, ws=None, wt=None, metric="sqeuclidean"):
654 r"""
655 Compute the primal OT plan the entropic OT as in equation (8) of [19]
656
657 This loss is backend compatible and can be used for stochastic optimization
658 of the dual potentials. It can be used on the full dataset (beware of
659 memory) or on minibatches.
660
661
662 Parameters
663 ----------
664 u : array-like, shape (ns,)
665 Source dual potential
666 v : array-like, shape (nt,)
667 Target dual potential
668 xs : array-like, shape (ns,d)
669 Source samples
670 xt : array-like, shape (ns,d)
671 Target samples
672 reg : float
673 Regularization term > 0 (default=1)
674 ws : array-like, shape (ns,), optional
675 Source sample weights (default unif)
676 wt : array-like, shape (ns,), optional
677 Target sample weights (default unif)
678 metric : string, callable
679 Ground metric for OT (default quadratic). Can be given as a callable
680 function taking (xs,xt) as parameters.
681
682 Returns
683 -------
684 G : array-like
685 Primal OT plan
686
687
688 References
689 ----------
690 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. Large-scale Optimal Transport and Mapping Estimation. International Conference on Learning Representation (2018)
691 """
692
693 nx = get_backend(u, v, xs, xt)
694
695 if ws is None:
696 ws = nx.ones(xs.shape[0], type_as=xs) / xs.shape[0]
697
698 if wt is None:
699 wt = nx.ones(xt.shape[0], type_as=xt) / xt.shape[0]
700
701 if callable(metric):
702 M = metric(xs, xt)
703 else:
704 M = dist(xs, xt, metric=metric)
705
706 H = nx.exp((u[:, None] + v[None, :] - M) / reg)
707
708 return ws[:, None] * H * wt[None, :]
709
710
711 def loss_dual_quadratic(u, v, xs, xt, reg=1, ws=None, wt=None, metric="sqeuclidean"):
712 r"""
713 Compute the dual loss of the quadratic regularized OT as in equation (6)-(7) of [19]
714
715 This loss is backend compatible and can be used for stochastic optimization
716 of the dual potentials. It can be used on the full dataset (beware of
717 memory) or on minibatches.
718
719
720 Parameters
721 ----------
722 u : array-like, shape (ns,)
723 Source dual potential
724 v : array-like, shape (nt,)
725 Target dual potential
726 xs : array-like, shape (ns,d)
727 Source samples
728 xt : array-like, shape (ns,d)
729 Target samples
730 reg : float
731 Regularization term > 0 (default=1)
732 ws : array-like, shape (ns,), optional
733 Source sample weights (default unif)
734 wt : array-like, shape (ns,), optional
735 Target sample weights (default unif)
736 metric : string, callable
737 Ground metric for OT (default quadratic). Can be given as a callable
738 function taking (xs,xt) as parameters.
739
740 Returns
741 -------
742 dual_loss : array-like
743 Dual loss (to maximize)
744
745
746 References
747 ----------
748 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. Large-scale Optimal Transport and Mapping Estimation. International Conference on Learning Representation (2018)
749 """
750
751 nx = get_backend(u, v, xs, xt)
752
753 if ws is None:
754 ws = nx.ones(xs.shape[0], type_as=xs) / xs.shape[0]
755
756 if wt is None:
757 wt = nx.ones(xt.shape[0], type_as=xt) / xt.shape[0]
758
759 if callable(metric):
760 M = metric(xs, xt)
761 else:
762 M = dist(xs, xt, metric=metric)
763
764 F = -1.0 / (4 * reg) * nx.maximum(u[:, None] + v[None, :] - M, 0.0) ** 2
765
766 return nx.sum(u * ws) + nx.sum(v * wt) + nx.sum(ws[:, None] * F * wt[None, :])
767
768
769 def plan_dual_quadratic(u, v, xs, xt, reg=1, ws=None, wt=None, metric="sqeuclidean"):
770 r"""
771 Compute the primal OT plan the quadratic regularized OT as in equation (8) of [19]
772
773 This loss is backend compatible and can be used for stochastic optimization
774 of the dual potentials. It can be used on the full dataset (beware of
775 memory) or on minibatches.
776
777
778 Parameters
779 ----------
780 u : array-like, shape (ns,)
781 Source dual potential
782 v : array-like, shape (nt,)
783 Target dual potential
784 xs : array-like, shape (ns,d)
785 Source samples
786 xt : array-like, shape (ns,d)
787 Target samples
788 reg : float
789 Regularization term > 0 (default=1)
790 ws : array-like, shape (ns,), optional
791 Source sample weights (default unif)
792 wt : array-like, shape (ns,), optional
793 Target sample weights (default unif)
794 metric : string, callable
795 Ground metric for OT (default quadratic). Can be given as a callable
796 function taking (xs,xt) as parameters.
797
798 Returns
799 -------
800 G : array-like
801 Primal OT plan
802
803
804 References
805 ----------
806 .. [19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. Large-scale Optimal Transport and Mapping Estimation. International Conference on Learning Representation (2018)
807 """
808
809 nx = get_backend(u, v, xs, xt)
810
811 if ws is None:
812 ws = nx.ones(xs.shape[0], type_as=xs) / xs.shape[0]
813
814 if wt is None:
815 wt = nx.ones(xt.shape[0], type_as=xt) / xt.shape[0]
816
817 if callable(metric):
818 M = metric(xs, xt)
819 else:
820 M = dist(xs, xt, metric=metric)
821
822 H = 1.0 / (2 * reg) * nx.maximum(u[:, None] + v[None, :] - M, 0.0)
823
824 return ws[:, None] * H * wt[None, :]