Debian Codegraph @

ot/smooth.py

raw symbols SCIP
1 # Copyright (c) 2018, Mathieu Blondel
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6 #
7 # 1. Redistributions of source code must retain the above copyright notice, this
8 # list of conditions and the following disclaimer.
9 #
10 # 2. Redistributions in binary form must reproduce the above copyright notice,
11 # this list of conditions and the following disclaimer in the documentation and/or
12 # other materials provided with the distribution.
13 #
14 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
18 # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
20 # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
21 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
22 # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 # THE POSSIBILITY OF SUCH DAMAGE.
24
25 # Author: Mathieu Blondel
26 # Remi Flamary <[email protected]>
27 # Tianlin Liu <[email protected]>
28
29 """
30 Smooth and Sparse (KL an L2 reg.) and sparsity-constrained OT solvers.
31
32 Implementation of :
33 Smooth and Sparse Optimal Transport.
34 Mathieu Blondel, Vivien Seguy, Antoine Rolet.
35 In Proc. of AISTATS 2018.
36 https://arxiv.org/abs/1710.06276
37
38 (Original code from https://github.com/mblondel/smooth-ot/)
39
40 Sparsity-Constrained Optimal Transport.
41 Liu, T., Puigcerver, J., & Blondel, M. (2023).
42 Sparsity-constrained optimal transport.
43 Proceedings of the Eleventh International Conference on
44 Learning Representations (ICLR).
45 https://arxiv.org/abs/2209.15466
46
47
48 [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal
49 Transport. Proceedings of the Twenty-First International Conference on
50 Artificial Intelligence and Statistics (AISTATS).
51
52 [50] Liu, T., Puigcerver, J., & Blondel, M. (2023).
53 Sparsity-constrained optimal transport.
54 Proceedings of the Eleventh International Conference on
55 Learning Representations (ICLR).
56
57 """
58
59 import numpy as np
60 from scipy.optimize import minimize
61 from .backend import get_backend
62 import ot
63
64
65 def projection_simplex(V, z=1, axis=None):
66 r"""Projection of :math:`\mathbf{V}` onto the simplex, scaled by `z`
67
68 .. math::
69 P\left(\mathbf{V}, z\right) = \mathop{\arg \min}_{\substack{\mathbf{y} >= 0 \\ \sum_i \mathbf{y}_i = z}} \quad \|\mathbf{y} - \mathbf{V}\|^2
70
71 Parameters
72 ----------
73 V: ndarray, rank 2
74 z: float or array
75 If array, len(z) must be compatible with :math:`\mathbf{V}`
76 axis: None or int
77 - axis=None: project :math:`\mathbf{V}` by :math:`P(\mathbf{V}.\mathrm{ravel}(), z)`
78 - axis=1: project each :math:`\mathbf{V}_i` by :math:`P(\mathbf{V}_i, z_i)`
79 - axis=0: project each :math:`\mathbf{V}_{:, j}` by :math:`P(\mathbf{V}_{:, j}, z_j)`
80
81 Returns
82 -------
83 projection: ndarray, shape :math:`\mathbf{V}`.shape
84 """
85 if axis == 1:
86 n_features = V.shape[1]
87 U = np.sort(V, axis=1)[:, ::-1]
88 z = np.ones(len(V)) * z
89 cssv = np.cumsum(U, axis=1) - z[:, np.newaxis]
90 ind = np.arange(n_features) + 1
91 cond = U - cssv / ind > 0
92 rho = np.count_nonzero(cond, axis=1)
93 theta = cssv[np.arange(len(V)), rho - 1] / rho
94 return np.maximum(V - theta[:, np.newaxis], 0)
95
96 elif axis == 0:
97 return projection_simplex(V.T, z, axis=1).T
98
99 else:
100 V = V.ravel().reshape(1, -1)
101 return projection_simplex(V, z, axis=1).ravel()
102
103
104 class Regularization(object):
105 r"""Base class for Regularization objects
106
107 Notes
108 -----
109 This class is not intended for direct use but as apparent for true
110 regularization implementation.
111 """
112
113 def __init__(self, gamma=1.0):
114 """
115
116 Parameters
117 ----------
118 gamma: float
119 Regularization parameter.
120 We recover unregularized OT when gamma -> 0.
121
122 """
123 self.gamma = gamma
124
125 def delta_Omega(X):
126 r"""
127 Compute :math:`\delta_\Omega(\mathbf{X}_{:, j})` for each :math:`\mathbf{X}_{:, j}`.
128
129 .. math::
130 \delta_\Omega(\mathbf{x}) = \sup_{\mathbf{y} >= 0} \
131 \mathbf{y}^T \mathbf{x} - \Omega(\mathbf{y})
132
133 Parameters
134 ----------
135 X: array, shape = (len(a), len(b))
136 Input array.
137
138 Returns
139 -------
140 v: array, (len(b), )
141 Values: :math:`\mathbf{v}_j = \delta_\Omega(\mathbf{X}_{:, j})`
142 G: array, (len(a), len(b))
143 Gradients: :math:`\mathbf{G}_{:, j} = \nabla \delta_\Omega(\mathbf{X}_{:, j})`
144 """
145 raise NotImplementedError
146
147 def max_Omega(X, b):
148 r"""
149 Compute :math:`\mathrm{max}_{\Omega, j}(\mathbf{X}_{:, j})` for each :math:`\mathbf{X}_{:, j}`.
150
151 .. math::
152 \mathrm{max}_{\Omega, j}(\mathbf{x}) =
153 \sup_{\substack{\mathbf{y} >= 0 \ \sum_i \mathbf{y}_i = 1}}
154 \mathbf{y}^T \mathbf{x} - \frac{1}{\mathbf{b}_j} \Omega(\mathbf{b}_j \mathbf{y})
155
156 Parameters
157 ----------
158 X: array, shape = (len(a), len(b))
159 Input array.
160 b: array, shape = (len(b), )
161
162 Returns
163 -------
164 v: array, (len(b), )
165 Values: :math:`\mathbf{v}_j = \mathrm{max}_{\Omega, j}(\mathbf{X}_{:, j})`
166 G: array, (len(a), len(b))
167 Gradients: :math:`\mathbf{G}_{:, j} = \nabla \mathrm{max}_{\Omega, j}(\mathbf{X}_{:, j})`
168 """
169 raise NotImplementedError
170
171 def Omega(T):
172 """
173 Compute regularization term.
174
175 Parameters
176 ----------
177 T: array, shape = len(a) x len(b)
178 Input array.
179
180 Returns
181 -------
182 value: float
183 Regularization term.
184 """
185 raise NotImplementedError
186
187
188 class NegEntropy(Regularization):
189 """NegEntropy regularization"""
190
191 def delta_Omega(self, X):
192 G = np.exp(X / self.gamma - 1)
193 val = self.gamma * np.sum(G, axis=0)
194 return val, G
195
196 def max_Omega(self, X, b):
197 max_X = np.max(X, axis=0) / self.gamma
198 exp_X = np.exp(X / self.gamma - max_X)
199 val = self.gamma * (np.log(np.sum(exp_X, axis=0)) + max_X)
200 val -= self.gamma * np.log(b)
201 G = exp_X / np.sum(exp_X, axis=0)
202 return val, G
203
204 def Omega(self, T):
205 return self.gamma * np.sum(T * np.log(T))
206
207
208 class SquaredL2(Regularization):
209 """Squared L2 regularization"""
210
211 def delta_Omega(self, X):
212 max_X = np.maximum(X, 0)
213 val = np.sum(max_X**2, axis=0) / (2 * self.gamma)
214 G = max_X / self.gamma
215 return val, G
216
217 def max_Omega(self, X, b):
218 G = projection_simplex(X / (b * self.gamma), axis=0)
219 val = np.sum(X * G, axis=0)
220 val -= 0.5 * self.gamma * b * np.sum(G * G, axis=0)
221 return val, G
222
223 def Omega(self, T):
224 return 0.5 * self.gamma * np.sum(T**2)
225
226
227 class SparsityConstrained(Regularization):
228 """Squared L2 regularization with sparsity constraints"""
229
230 def __init__(self, max_nz, gamma=1.0):
231 self.max_nz = max_nz
232 self.gamma = gamma
233
234 def delta_Omega(self, X):
235 # For each column of X, find entries that are not among the top max_nz.
236 non_top_indices = np.argpartition(-X, self.max_nz, axis=0)[self.max_nz :]
237 # Set these entries to -inf.
238 if X.ndim == 1:
239 X[non_top_indices] = 0.0
240 else:
241 X[non_top_indices, np.arange(X.shape[1])] = 0.0
242 max_X = np.maximum(X, 0)
243 val = np.sum(max_X**2, axis=0) / (2 * self.gamma)
244 G = max_X / self.gamma
245 return val, G
246
247 def max_Omega(self, X, b):
248 # Project the scaled X onto the simplex with sparsity constraint.
249 G = ot.utils.projection_sparse_simplex(
250 X / (b * self.gamma), self.max_nz, axis=0
251 )
252 val = np.sum(X * G, axis=0)
253 val -= 0.5 * self.gamma * b * np.sum(G * G, axis=0)
254 return val, G
255
256 def Omega(self, T):
257 return 0.5 * self.gamma * np.sum(T**2)
258
259
260 def dual_obj_grad(alpha, beta, a, b, C, regul):
261 r"""
262 Compute objective value and gradients of dual objective.
263
264 Parameters
265 ----------
266 alpha: array, shape = len(a)
267 beta: array, shape = len(b)
268 Current iterate of dual potentials.
269 a: array, shape = len(a)
270 b: array, shape = len(b)
271 Input histograms (should be non-negative and sum to 1).
272 C: array, shape = (len(a), len(b))
273 Ground cost matrix.
274 regul: Regularization object
275 Should implement a `delta_Omega(X)` method.
276
277 Returns
278 -------
279 obj: float
280 Objective value (higher is better).
281 grad_alpha: array, shape = len(a)
282 Gradient w.r.t. `alpha`.
283 grad_beta: array, shape = len(b)
284 Gradient w.r.t. `beta`.
285 """
286 obj = np.dot(alpha, a) + np.dot(beta, b)
287 grad_alpha = a.copy()
288 grad_beta = b.copy()
289
290 # X[:, j] = alpha + beta[j] - C[:, j]
291 X = alpha[:, np.newaxis] + beta - C
292
293 # val.shape = len(b)
294 # G.shape = len(a) x len(b)
295 val, G = regul.delta_Omega(X)
296
297 obj -= np.sum(val)
298 grad_alpha -= G.sum(axis=1)
299 grad_beta -= G.sum(axis=0)
300
301 return obj, grad_alpha, grad_beta
302
303
304 def solve_dual(
305 a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False
306 ):
307 """
308 Solve the "smoothed" dual objective.
309
310 Parameters
311 ----------
312 a: array, shape = (len(a), )
313 b: array, shape = (len(b), )
314 Input histograms (should be non-negative and sum to 1).
315 C: array, shape = (len(a), len(b))
316 Ground cost matrix.
317 regul: Regularization object
318 Should implement a `delta_Omega(X)` method.
319 method: str
320 Solver to be used (passed to `scipy.optimize.minimize`).
321 tol: float
322 Tolerance parameter.
323 max_iter: int
324 Maximum number of iterations.
325
326 Returns
327 -------
328 alpha: array, shape = (len(a), )
329 beta: array, shape = (len(b), )
330 Dual potentials.
331 """
332
333 def _func(params):
334 # Unpack alpha and beta.
335 alpha = params[: len(a)]
336 beta = params[len(a) :]
337
338 obj, grad_alpha, grad_beta = dual_obj_grad(alpha, beta, a, b, C, regul)
339
340 # Pack grad_alpha and grad_beta.
341 grad = np.concatenate((grad_alpha, grad_beta))
342
343 # We need to maximize the dual.
344 return -obj, -grad
345
346 # Unfortunately, `minimize` only supports functions whose argument is a
347 # vector. So, we need to concatenate alpha and beta.
348 alpha_init = np.zeros(len(a))
349 beta_init = np.zeros(len(b))
350 params_init = np.concatenate((alpha_init, beta_init))
351
352 res = minimize(
353 _func,
354 params_init,
355 method=method,
356 jac=True,
357 tol=tol,
358 options=dict(maxiter=max_iter, disp=verbose),
359 )
360
361 alpha = res.x[: len(a)]
362 beta = res.x[len(a) :]
363
364 return alpha, beta, res
365
366
367 def semi_dual_obj_grad(alpha, a, b, C, regul):
368 """
369 Compute objective value and gradient of semi-dual objective.
370
371 Parameters
372 ----------
373 alpha: array, shape = len(a)
374 Current iterate of semi-dual potentials.
375 a: array, shape = len(a)
376 b: array, shape = len(b)
377 Input histograms (should be non-negative and sum to 1).
378 C: array, shape = (len(a), len(b))
379 Ground cost matrix.
380 regul: Regularization object
381 Should implement a `max_Omega(X)` method.
382
383 Returns
384 -------
385 obj: float
386 Objective value (higher is better).
387 grad: array, shape = len(a)
388 Gradient w.r.t. alpha.
389 """
390 obj = np.dot(alpha, a)
391 grad = a.copy()
392
393 # X[:, j] = alpha - C[:, j]
394 X = alpha[:, np.newaxis] - C
395
396 # val.shape = len(b)
397 # G.shape = len(a) x len(b)
398 val, G = regul.max_Omega(X, b)
399
400 obj -= np.dot(b, val)
401 grad -= np.dot(G, b)
402
403 return obj, grad
404
405
406 def solve_semi_dual(
407 a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False
408 ):
409 """
410 Solve the "smoothed" semi-dual objective.
411
412 Parameters
413 ----------
414 a: array, shape = (len(a), )
415 b: array, shape = (len(b), )
416 Input histograms (should be non-negative and sum to 1).
417 C: array, shape = (len(a), len(b))
418 Ground cost matrix.
419 regul: Regularization object
420 Should implement a `max_Omega(X)` method.
421 method: str
422 Solver to be used (passed to `scipy.optimize.minimize`).
423 tol: float
424 Tolerance parameter.
425 max_iter: int
426 Maximum number of iterations.
427
428 Returns
429 -------
430 alpha: array, shape = (len(a), )
431 Semi-dual potentials.
432 """
433
434 def _func(alpha):
435 obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul)
436 # We need to maximize the semi-dual.
437 return -obj, -grad
438
439 alpha_init = np.zeros(len(a))
440
441 res = minimize(
442 _func,
443 alpha_init,
444 method=method,
445 jac=True,
446 tol=tol,
447 options=dict(maxiter=max_iter, disp=verbose),
448 )
449
450 return res.x, res
451
452
453 def get_plan_from_dual(alpha, beta, C, regul):
454 r"""
455 Retrieve optimal transportation plan from optimal dual potentials.
456
457 Parameters
458 ----------
459 alpha: array, shape = len(a)
460 beta: array, shape = len(b)
461 Optimal dual potentials.
462 C: array, shape = (len(a), len(b))
463 Ground cost matrix.
464 regul: Regularization object
465 Should implement a `delta_Omega(X)` method.
466
467 Returns
468 -------
469 T: array, shape = (len(a), len(b))
470 Optimal transportation plan.
471 """
472 X = alpha[:, np.newaxis] + beta - C
473 return regul.delta_Omega(X)[1]
474
475
476 def get_plan_from_semi_dual(alpha, b, C, regul):
477 r"""
478 Retrieve optimal transportation plan from optimal semi-dual potentials.
479
480 Parameters
481 ----------
482 alpha: array, shape = len(a)
483 Optimal semi-dual potentials.
484 b: array, shape = len(b)
485 Second input histogram (should be non-negative and sum to 1).
486 C: array, shape = (len(a), len(b))
487 Ground cost matrix.
488 regul: Regularization object
489 Should implement a `delta_Omega(X)` method.
490
491 Returns
492 -------
493 T: array, shape = (len(a), len(b))
494 Optimal transportation plan.
495 """
496 X = alpha[:, np.newaxis] - C
497 return regul.max_Omega(X, b)[1] * b
498
499
500 def smooth_ot_dual(
501 a,
502 b,
503 M,
504 reg,
505 reg_type="l2",
506 method="L-BFGS-B",
507 stopThr=1e-9,
508 numItermax=500,
509 verbose=False,
510 log=False,
511 max_nz=None,
512 ):
513 r"""
514 Solve the regularized OT problem in the dual and return the OT matrix
515
516 The function solves the smooth relaxed dual formulation (7) in
517 :ref:`[17] <references-smooth-ot-dual>`:
518
519 .. math::
520 \max_{\alpha,\beta}\quad \mathbf{a}^T\alpha + \mathbf{b}^T\beta -
521 \sum_j \delta_\Omega \left(\alpha+\beta_j-\mathbf{m}_j \right)
522
523 where :
524
525 - :math:`\mathbf{m}_j` is the j-th column of the cost matrix
526 - :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega`
527 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
528
529 The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega`
530 (See :ref:`[17] <references-smooth-ot-dual>` Proposition 1).
531 The optimization algorithm is using gradient decent (L-BFGS by default).
532
533
534 Parameters
535 ----------
536 a : np.ndarray (ns,)
537 samples weights in the source domain
538 b : np.ndarray (nt,) or np.ndarray (nt,nbb)
539 samples in the target domain, compute sinkhorn with multiple targets
540 and fixed :math:`\mathbf{M}` if :math:`\mathbf{b}` is a matrix
541 (return OT loss + dual variables in log)
542 M : np.ndarray (ns,nt)
543 loss matrix
544 reg : float
545 Regularization term >0
546 reg_type : str
547 Regularization type, can be the following (default ='l2'):
548
549 - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn
550 :ref:`[2] <references-smooth-ot-dual>`)
551
552 - 'l2' : Squared Euclidean regularization
553 - 'sparsity_constrained' : Sparsity-constrained regularization [50]
554 max_nz : int or None, optional. Used only in the case of reg_type = 'sparsity_constrained' to specify the maximum number of nonzeros per column of the optimal plan;
555 not used for other regularization types.
556 method : str
557 Solver to use for scipy.optimize.minimize
558 numItermax : int, optional
559 Max number of iterations
560 stopThr : float, optional
561 Stop threshold on error (>0)
562 verbose : bool, optional
563 Print information along iterations
564 log : bool, optional
565 record log if True
566
567
568 Returns
569 -------
570 gamma : (ns, nt) ndarray
571 Optimal transportation matrix for the given parameters
572 log : dict
573 log dictionary return only if log==True in parameters
574
575
576 .. _references-smooth-ot-dual:
577 References
578 ----------
579 .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
580
581 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
582
583 .. [50] Liu, T., Puigcerver, J., & Blondel, M. (2023). Sparsity-constrained optimal transport. Proceedings of the Eleventh International Conference on Learning Representations (ICLR).
584
585 See Also
586 --------
587 ot.lp.emd : Unregularized OT
588 ot.sinhorn : Entropic regularized OT
589 ot.optim.cg : General regularized OT
590
591 """
592
593 nx = get_backend(a, b, M)
594
595 if reg_type.lower() in ["l2", "squaredl2"]:
596 regul = SquaredL2(gamma=reg)
597 elif reg_type.lower() in ["entropic", "negentropy", "kl"]:
598 regul = NegEntropy(gamma=reg)
599 elif reg_type.lower() in ["sparsity_constrained", "sparsity-constrained"]:
600 if not isinstance(max_nz, int):
601 raise ValueError(f"max_nz {max_nz} must be an integer")
602 regul = SparsityConstrained(gamma=reg, max_nz=max_nz)
603 else:
604 raise NotImplementedError("Unknown regularization")
605
606 a0, b0, M0 = a, b, M
607 # convert to humpy
608 a, b, M = nx.to_numpy(a, b, M)
609
610 # solve dual
611 alpha, beta, res = solve_dual(
612 a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose
613 )
614
615 # reconstruct transport matrix
616 G = nx.from_numpy(get_plan_from_dual(alpha, beta, M, regul), type_as=M0)
617
618 if log:
619 log = {
620 "alpha": nx.from_numpy(alpha, type_as=a0),
621 "beta": nx.from_numpy(beta, type_as=b0),
622 "res": res,
623 }
624 return G, log
625 else:
626 return G
627
628
629 def smooth_ot_semi_dual(
630 a,
631 b,
632 M,
633 reg,
634 reg_type="l2",
635 max_nz=None,
636 method="L-BFGS-B",
637 stopThr=1e-9,
638 numItermax=500,
639 verbose=False,
640 log=False,
641 ):
642 r"""
643 Solve the regularized OT problem in the semi-dual and return the OT matrix
644
645 The function solves the smooth relaxed dual formulation (10) in
646 :ref:`[17] <references-smooth-ot-semi-dual>`:
647
648 .. math::
649 \max_{\alpha}\quad \mathbf{a}^T\alpha- \mathrm{OT}_\Omega^*(\alpha, \mathbf{b})
650
651 where :
652
653 .. math::
654 \mathrm{OT}_\Omega^*(\alpha,b)=\sum_j \mathbf{b}_j
655
656 - :math:`\mathbf{m}_j` is the j-th column of the cost matrix
657 - :math:`\mathrm{OT}_\Omega^*(\alpha,b)` is defined in Eq. (9) in
658 :ref:`[17] <references-smooth-ot-semi-dual>`
659 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1)
660
661 The OT matrix can is reconstructed using :ref:`[17] <references-smooth-ot-semi-dual>` Proposition 2.
662 The optimization algorithm is using gradient decent (L-BFGS by default).
663
664
665 Parameters
666 ----------
667 a : np.ndarray (ns,)
668 samples weights in the source domain
669 b : np.ndarray (nt,) or np.ndarray (nt,nbb)
670 samples in the target domain, compute sinkhorn with multiple targets
671 and fixed:math:`\mathbf{M}` if :math:`\mathbf{b}` is a matrix
672 (return OT loss + dual variables in log)
673 M : np.ndarray (ns,nt)
674 loss matrix
675 reg : float
676 Regularization term >0
677 reg_type : str
678 Regularization type, can be the following (default ='l2'):
679
680 - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn
681 :ref:`[2] <references-smooth-ot-semi-dual>`)
682
683 - 'l2' : Squared Euclidean regularization
684 - 'sparsity_constrained' : Sparsity-constrained regularization [50]
685 max_nz : int or None, optional. Used only in the case of reg_type = 'sparsity_constrained' to specify the maximum number of nonzeros per column of the optimal plan;
686 not used for other regularization types.
687 method : str
688 Solver to use for scipy.optimize.minimize
689 numItermax : int, optional
690 Max number of iterations
691 stopThr : float, optional
692 Stop threshold on error (>0)
693 verbose : bool, optional
694 Print information along iterations
695 log : bool, optional
696 record log if True
697
698
699 Returns
700 -------
701 gamma : (ns, nt) ndarray
702 Optimal transportation matrix for the given parameters
703 log : dict
704 log dictionary return only if log==True in parameters
705
706
707 .. _references-smooth-ot-semi-dual:
708 References
709 ----------
710 .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
711
712 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS).
713
714 .. [50] Liu, T., Puigcerver, J., & Blondel, M. (2023). Sparsity-constrained optimal transport. Proceedings of the Eleventh International Conference on Learning Representations (ICLR).
715
716 See Also
717 --------
718 ot.lp.emd : Unregularized OT
719 ot.sinhorn : Entropic regularized OT
720 ot.optim.cg : General regularized OT
721
722 """
723 if reg_type.lower() in ["l2", "squaredl2"]:
724 regul = SquaredL2(gamma=reg)
725 elif reg_type.lower() in ["entropic", "negentropy", "kl"]:
726 regul = NegEntropy(gamma=reg)
727 elif reg_type.lower() in ["sparsity_constrained", "sparsity-constrained"]:
728 if not isinstance(max_nz, int):
729 raise ValueError(f"max_nz {max_nz} must be an integer")
730 regul = SparsityConstrained(gamma=reg, max_nz=max_nz)
731 else:
732 raise NotImplementedError("Unknown regularization")
733
734 # solve dual
735 alpha, res = solve_semi_dual(
736 a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose
737 )
738
739 # reconstruct transport matrix
740 G = get_plan_from_semi_dual(alpha, b, M, regul)
741
742 if log:
743 log = {"alpha": alpha, "res": res}
744 return G, log
745 else:
746 return G