Python modules

ot

This is the main module of the POT toolbox. It provides easy access to a number of sub-modules and functions described below.

Note

Here is a list of the submodules and short description of what they contain.

  • ot.lp contains OT solvers for the exact (Linear Program) OT problems.
  • ot.bregman contains OT solvers for the entropic OT problems using Bregman projections.
  • ot.lp contains OT solvers for the exact (Linear Program) OT problems.
  • ot.smooth contains OT solvers for the regularized (l2 and kl) smooth OT problems.
  • ot.gromov contains solvers for Gromov-Wasserstein and Fused Gromov Wasserstein problems.
  • ot.optim contains generic solvers OT based optimization problems
  • ot.da contains classes and function related to Monge mapping estimation and Domain Adaptation (DA).
  • ot.gpu contains GPU (cupy) implementation of some OT solvers
  • ot.dr contains Dimension Reduction (DR) methods such as Wasserstein Discriminant Analysis.
  • ot.utils contains utility functions such as distance computation and timing.
  • ot.datasets contains toy dataset generation functions.
  • ot.plot contains visualization functions
  • ot.stochastic contains stochastic solvers for regularized OT.
  • ot.unbalanced contains solvers for regularized unbalanced OT.

Warning

The list of automatically imported sub-modules is as follows: ot.lp, ot.bregman, ot.optim ot.utils, ot.datasets, ot.gromov, ot.smooth ot.stochastic

The following sub-modules are not imported due to additional dependencies:

  • ot.dr : depends on pymanopt and autograd.
  • ot.gpu : depends on cupy and a CUDA GPU.
  • ot.plot : depends on matplotlib
ot.emd(a, b, M, numItermax=100000, log=False)[source]

Solves the Earth Movers distance problem and returns the OT matrix

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F\\s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the metric cost matrix
  • a and b are the sample weights

Warning

Note that the M matrix needs to be a C-order numpy.array in float64 format.

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) numpy.ndarray, float64) – Source histogram (uniform weight if empty list)
  • b ((nt,) numpy.ndarray, float64) – Target histogram (uniform weight if empty list)
  • M ((ns,nt) numpy.ndarray, float64) – Loss matrix (c-order array with type float64)
  • numItermax (int, optional (default=100000)) – The maximum number of iterations before stopping the optimization algorithm if it has not converged.
  • log (bool, optional (default=False)) – If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation matrix.
Returns:

  • gamma ((ns x nt) numpy.ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – If input log is true, a dictionary containing the cost and dual variables and exit status

Examples

Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays

>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd(a,b,M)
array([[0.5, 0. ],
       [0. , 0.5]])

References

[1]Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM.

See also

ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.emd2(a, b, M, processes=4, numItermax=100000, log=False, return_matrix=False)[source]

Solves the Earth Movers distance problem and returns the loss

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F\\s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the metric cost matrix
  • a and b are the sample weights

Warning

Note that the M matrix needs to be a C-order numpy.array in float64 format.

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) numpy.ndarray, float64) – Source histogram (uniform weight if empty list)
  • b ((nt,) numpy.ndarray, float64) – Target histogram (uniform weight if empty list)
  • M ((ns,nt) numpy.ndarray, float64) – Loss matrix (c-order array with type float64)
  • processes (int, optional (default=nb cpu)) – Nb of processes used for multiple emd computation (not used on windows)
  • numItermax (int, optional (default=100000)) – The maximum number of iterations before stopping the optimization algorithm if it has not converged.
  • log (boolean, optional (default=False)) – If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation cost.
  • return_matrix (boolean, optional (default=False)) – If True, returns the optimal transportation matrix in the log.
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dictnp) – If input log is true, a dictionary containing the cost and dual variables and exit status

Examples

Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays

>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd2(a,b,M)
0.0

References

[1]Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM.

See also

ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.emd_1d(x_a, x_b, a=None, b=None, metric='sqeuclidean', p=1.0, dense=True, log=False)[source]

Solves the Earth Movers distance problem between 1d measures and returns the OT matrix

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma \sum_i \sum_j \gamma_{ij} d(x_a[i], x_b[j])\\s.t. \gamma 1 = a, \gamma^T 1= b, \gamma\geq 0\end{aligned}\end{align} \]

where :

  • d is the metric
  • x_a and x_b are the samples
  • a and b are the sample weights

When ‘minkowski’ is used as a metric, \(d(x, y) = |x - y|^p\).

Uses the algorithm detailed in [1]_

Parameters:
  • x_a ((ns,) or (ns, 1) ndarray, float64) – Source dirac locations (on the real line)
  • x_b ((nt,) or (ns, 1) ndarray, float64) – Target dirac locations (on the real line)
  • a ((ns,) ndarray, float64, optional) – Source histogram (default is uniform weight)
  • b ((nt,) ndarray, float64, optional) – Target histogram (default is uniform weight)
  • metric (str, optional (default='sqeuclidean')) – Metric to be used. Only strings listed in ot.dist() are accepted. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • p (float, optional (default=1.0)) – The p-norm to apply for if metric=’minkowski’
  • dense (boolean, optional (default=True)) – If True, returns math:gamma as a dense ndarray of shape (ns, nt). Otherwise returns a sparse representation using scipy’s coo_matrix format. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘minkowski’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • log (boolean, optional (default=False)) – If True, returns a dictionary containing the cost. Otherwise returns only the optimal transportation matrix.
Returns:

  • gamma ((ns, nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – If input log is True, a dictionary containing the cost

Examples

Simple example with obvious solution. The function emd_1d accepts lists and performs automatic conversion to numpy arrays

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> x_a = [2., 0.]
>>> x_b = [0., 3.]
>>> ot.emd_1d(x_a, x_b, a, b)
array([[0. , 0.5],
       [0.5, 0. ]])
>>> ot.emd_1d(x_a, x_b)
array([[0. , 0.5],
       [0.5, 0. ]])

References

[1]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.

See also

ot.lp.emd()
EMD for multidimensional distributions
ot.lp.emd2_1d()
EMD for 1d distributions (returns cost instead of the transportation matrix)
ot.sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem and return the OT matrix

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_

Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,) or ndarray, shape (dim_b, n_hists)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘greenkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_epsilon_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (dim_a, dim_b)) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn(a, b, M, 1)
array([[0.36552929, 0.13447071],
       [0.13447071, 0.36552929]])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.sinkhorn_knopp()
Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized()
Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling()
Sinkhorn with epslilon scaling [9][10]
ot.sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem and return the loss

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_

Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,) or ndarray, shape (dim_b, n_hists)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_epsilon_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • W ((n_hists) ndarray or float) – Optimal transportation loss for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn2(a, b, M, 1)
array([0.26894142])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]

Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.

[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.sinkhorn_knopp()
Classic Sinkhorn [2]
ot.bregman.greenkhorn()
Greenkhorn [21]
ot.bregman.sinkhorn_stabilized()
Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling()
Sinkhorn with epslilon scaling [9][10]
ot.tic()[source]

Python implementation of Matlab tic() function

ot.toc(message='Elapsed time : {} s')[source]

Python implementation of Matlab toc() function

ot.toq()[source]

Python implementation of Julia toc() function

ot.emd_1d(x_a, x_b, a=None, b=None, metric='sqeuclidean', p=1.0, dense=True, log=False)[source]

Solves the Earth Movers distance problem between 1d measures and returns the OT matrix

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma \sum_i \sum_j \gamma_{ij} d(x_a[i], x_b[j])\\s.t. \gamma 1 = a, \gamma^T 1= b, \gamma\geq 0\end{aligned}\end{align} \]

where :

  • d is the metric
  • x_a and x_b are the samples
  • a and b are the sample weights

When ‘minkowski’ is used as a metric, \(d(x, y) = |x - y|^p\).

Uses the algorithm detailed in [1]_

Parameters:
  • x_a ((ns,) or (ns, 1) ndarray, float64) – Source dirac locations (on the real line)
  • x_b ((nt,) or (ns, 1) ndarray, float64) – Target dirac locations (on the real line)
  • a ((ns,) ndarray, float64, optional) – Source histogram (default is uniform weight)
  • b ((nt,) ndarray, float64, optional) – Target histogram (default is uniform weight)
  • metric (str, optional (default='sqeuclidean')) – Metric to be used. Only strings listed in ot.dist() are accepted. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • p (float, optional (default=1.0)) – The p-norm to apply for if metric=’minkowski’
  • dense (boolean, optional (default=True)) – If True, returns math:gamma as a dense ndarray of shape (ns, nt). Otherwise returns a sparse representation using scipy’s coo_matrix format. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘minkowski’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • log (boolean, optional (default=False)) – If True, returns a dictionary containing the cost. Otherwise returns only the optimal transportation matrix.
Returns:

  • gamma ((ns, nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – If input log is True, a dictionary containing the cost

Examples

Simple example with obvious solution. The function emd_1d accepts lists and performs automatic conversion to numpy arrays

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> x_a = [2., 0.]
>>> x_b = [0., 3.]
>>> ot.emd_1d(x_a, x_b, a, b)
array([[0. , 0.5],
       [0.5, 0. ]])
>>> ot.emd_1d(x_a, x_b)
array([[0. , 0.5],
       [0.5, 0. ]])

References

[1]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.

See also

ot.lp.emd()
EMD for multidimensional distributions
ot.lp.emd2_1d()
EMD for 1d distributions (returns cost instead of the transportation matrix)
ot.emd2_1d(x_a, x_b, a=None, b=None, metric='sqeuclidean', p=1.0, dense=True, log=False)[source]

Solves the Earth Movers distance problem between 1d measures and returns the loss

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma \sum_i \sum_j \gamma_{ij} d(x_a[i], x_b[j])\\s.t. \gamma 1 = a, \gamma^T 1= b, \gamma\geq 0\end{aligned}\end{align} \]

where :

  • d is the metric
  • x_a and x_b are the samples
  • a and b are the sample weights

When ‘minkowski’ is used as a metric, \(d(x, y) = |x - y|^p\).

Uses the algorithm detailed in [1]_

Parameters:
  • x_a ((ns,) or (ns, 1) ndarray, float64) – Source dirac locations (on the real line)
  • x_b ((nt,) or (ns, 1) ndarray, float64) – Target dirac locations (on the real line)
  • a ((ns,) ndarray, float64, optional) – Source histogram (default is uniform weight)
  • b ((nt,) ndarray, float64, optional) – Target histogram (default is uniform weight)
  • metric (str, optional (default='sqeuclidean')) – Metric to be used. Only strings listed in ot.dist() are accepted. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘minkowski’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • p (float, optional (default=1.0)) – The p-norm to apply for if metric=’minkowski’
  • dense (boolean, optional (default=True)) – If True, returns math:gamma as a dense ndarray of shape (ns, nt). Otherwise returns a sparse representation using scipy’s coo_matrix format. Only used if log is set to True. Due to implementation details, this function runs faster when dense is set to False.
  • log (boolean, optional (default=False)) – If True, returns a dictionary containing the transportation matrix. Otherwise returns only the loss.
Returns:

  • loss (float) – Cost associated to the optimal transportation
  • log (dict) – If input log is True, a dictionary containing the Optimal transportation matrix for the given parameters

Examples

Simple example with obvious solution. The function emd2_1d accepts lists and performs automatic conversion to numpy arrays

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> x_a = [2., 0.]
>>> x_b = [0., 3.]
>>> ot.emd2_1d(x_a, x_b, a, b)
0.5
>>> ot.emd2_1d(x_a, x_b)
0.5

References

[1]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.

See also

ot.lp.emd2()
EMD for multidimensional distributions
ot.lp.emd_1d()
EMD for 1d distributions (returns the transportation matrix instead of the cost)
ot.wasserstein_1d(x_a, x_b, a=None, b=None, p=1.0)[source]

Solves the p-Wasserstein distance problem between 1d measures and returns the distance

\[ \begin{align}\begin{aligned}\min_\gamma \left( \sum_i \sum_j \gamma_{ij} \|x_a[i] - x_b[j]\|^p \right)^{1/p}\\s.t. \gamma 1 = a, \gamma^T 1= b, \gamma\geq 0\end{aligned}\end{align} \]

where :

  • x_a and x_b are the samples
  • a and b are the sample weights

Uses the algorithm detailed in [1]_

Parameters:
  • x_a ((ns,) or (ns, 1) ndarray, float64) – Source dirac locations (on the real line)
  • x_b ((nt,) or (ns, 1) ndarray, float64) – Target dirac locations (on the real line)
  • a ((ns,) ndarray, float64, optional) – Source histogram (default is uniform weight)
  • b ((nt,) ndarray, float64, optional) – Target histogram (default is uniform weight)
  • p (float, optional (default=1.0)) – The order of the p-Wasserstein distance to be computed
Returns:

dist – p-Wasserstein distance

Return type:

float

Examples

Simple example with obvious solution. The function wasserstein_1d accepts lists and performs automatic conversion to numpy arrays

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> x_a = [2., 0.]
>>> x_b = [0., 3.]
>>> ot.wasserstein_1d(x_a, x_b, a, b)
0.5
>>> ot.wasserstein_1d(x_a, x_b)
0.5

References

[1]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.

See also

ot.lp.emd_1d()
EMD for 1d distributions
ot.dist(x1, x2=None, metric='sqeuclidean')[source]

Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist

Parameters:
  • x1 (ndarray, shape (n1,d)) – matrix with n1 samples of size d
  • x2 (array, shape (n2,d), optional) – matrix with n2 samples of size d (if None then x2=x1)
  • metric (str | callable, optional) – Name of the metric to be computed (full list in the doc of scipy), If a string, the distance function can be ‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘cityblock’, ‘correlation’, ‘cosine’, ‘dice’, ‘euclidean’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘matching’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘wminkowski’, ‘yule’.
Returns:

M – distance matrix computed with given metric

Return type:

np.array (n1,n2)

ot.unif(n)[source]

return a uniform histogram of length n (simplex)

Parameters:n (int) – number of bins in the histogram
Returns:h – histogram of length n such that h_i=1/n for all i
Return type:np.array (n,)
ot.barycenter(A, M, reg, weights=None, method='sinkhorn', numItermax=10000, stopThr=0.0001, verbose=False, log=False, **kwargs)[source]

Compute the entropic regularized wasserstein barycenter of distributions A

The function solves the following optimization problem:
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(W_{reg}(\cdot,\cdot)\) is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
  • \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\)
  • reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_

Parameters:
  • A (ndarray, shape (dim, n_hists)) – n_hists training distributions a_i of size dim
  • M (ndarray, shape (dim, dim)) – loss matrix for OT
  • reg (float) – Regularization term > 0
  • method (str (optional)) – method used for the solver either ‘sinkhorn’ or ‘sinkhorn_stabilized’
  • weights (ndarray, shape (n_hists,)) – Weights of each histogram a_i on the simplex (barycentric coodinates)
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
ot.sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-09, verbose=False, log=False)[source]

Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma) + \eta \Omega_g(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega_e\) is the entropic regularization term \(\Omega_e (\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(\Omega_g\) is the group lasso regularization term \(\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1\) where \(\mathcal{I}_c\) are the index of samples from class c in the source domain.
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the generalized conditional gradient as proposed in [5]_ [7]_

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • labels_a (np.ndarray (ns,)) – labels of samples in the source domain
  • b (np.ndarray (nt,)) – samples weights in the target domain
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term for entropic regularization >0
  • eta (float, optional) – Regularization term for group lasso regularization >0
  • numItermax (int, optional) – Max number of iterations
  • numInnerItermax (int, optional) – Max number of iterations (inner sinkhorn solver)
  • stopInnerThr (float, optional) – Stop threshold on error (inner sinkhorn solver) (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[5]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[7]Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.

See also

ot.lp.emd()
Unregularized OT
ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.sinkhorn_unbalanced(a, b, M, reg, reg_m, method='sinkhorn', numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Solve the unbalanced entropic regularization optimal transport problem and return the OT plan

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)\\s.t. \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization
    term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target unbalanced distributions
  • KL is the Kullback-Leibler divergence
The algorithm used for solving the problem is the generalized
Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_
Parameters:
  • a (np.ndarray (dim_a,)) – Unnormalized histogram of dimension dim_a
  • b (np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)) – One or multiple unnormalized histograms of dimension dim_b If many, compute all the OT distances (a, b_i)
  • M (np.ndarray (dim_a, dim_b)) – loss matrix
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_reg_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • if n_hists == 1

    gamma : (dim_a x dim_b) ndarray

    Optimal transportation matrix for the given parameters

    log : dict

    log dictionary returned only if log is True

  • else

    ot_distance : (n_hists,) ndarray

    the OT distance between a and each of the histograms b_i

    log : dict

    log dictionary returned only if log is True

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn_unbalanced(a, b, M, 1, 1)
array([[0.51122823, 0.18807035],
       [0.18807035, 0.51122823]])

References

[2]M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[25]Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. : Learning with a Wasserstein Loss, Advances in Neural Information Processing Systems (NIPS) 2015

See also

ot.unbalanced.sinkhorn_knopp_unbalanced()
Unbalanced Classic Sinkhorn [10]
ot.unbalanced.sinkhorn_stabilized_unbalanced()
Unbalanced Stabilized sinkhorn [9][10]
ot.unbalanced.sinkhorn_reg_scaling_unbalanced()
Unbalanced Sinkhorn with epslilon scaling [9][10]
ot.barycenter_unbalanced(A, M, reg, reg_m, method='sinkhorn', weights=None, numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Compute the entropic unbalanced wasserstein barycenter of A.

The function solves the following optimization problem with a
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i Wu_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(Wu_{reg}(\cdot,\cdot)\) is the unbalanced entropic regularized

Wasserstein distance (see ot.unbalanced.sinkhorn_unbalanced) - \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\) - reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT - reg_mis the marginal relaxation hyperparameter The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10]_

Parameters:
  • A (np.ndarray (dim, n_hists)) – n_hists training distributions a_i of dimension dim
  • M (np.ndarray (dim, dim)) – ground metric matrix for OT.
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • weights (np.ndarray (n_hists,) optional) – Weight of each distribution (barycentric coodinates) If None, uniform weights are used.
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (> 0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Unbalanced Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprin arXiv:1607.05816.
ot.sinkhorn_unbalanced2(a, b, M, reg, reg_m, method='sinkhorn', numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization unbalanced optimal transport problem and return the loss

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)\\s.t. \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term
    \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target unbalanced distributions
  • KL is the Kullback-Leibler divergence

The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

Parameters:
  • a (np.ndarray (dim_a,)) – Unnormalized histogram of dimension dim_a
  • b (np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)) – One or multiple unnormalized histograms of dimension dim_b If many, compute all the OT distances (a, b_i)
  • M (np.ndarray (dim_a, dim_b)) – loss matrix
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_reg_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • ot_distance ((n_hists,) ndarray) – the OT distance between a and each of the histograms b_i
  • log (dict) – log dictionary returned only if log is True

Examples

>>> import ot
>>> a=[.5, .10]
>>> b=[.5, .5]
>>> M=[[0., 1.],[1., 0.]]
>>> ot.unbalanced.sinkhorn_unbalanced2(a, b, M, 1., 1.)
array([0.31912866])

References

[2]M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[25]Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. : Learning with a Wasserstein Loss, Advances in Neural Information Processing Systems (NIPS) 2015

See also

ot.unbalanced.sinkhorn_knopp()
Unbalanced Classic Sinkhorn [10]
ot.unbalanced.sinkhorn_stabilized()
Unbalanced Stabilized sinkhorn [9][10]
ot.unbalanced.sinkhorn_reg_scaling()
Unbalanced Sinkhorn with epslilon scaling [9][10]

ot.lp

Solvers for the original linear program OT problem

ot.lp.emd(a, b, M, numItermax=100000, log=False)[source]

Solves the Earth Movers distance problem and returns the OT matrix

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F\\s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the metric cost matrix
  • a and b are the sample weights

Warning

Note that the M matrix needs to be a C-order numpy.array in float64 format.

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) numpy.ndarray, float64) – Source histogram (uniform weight if empty list)
  • b ((nt,) numpy.ndarray, float64) – Target histogram (uniform weight if empty list)
  • M ((ns,nt) numpy.ndarray, float64) – Loss matrix (c-order array with type float64)
  • numItermax (int, optional (default=100000)) – The maximum number of iterations before stopping the optimization algorithm if it has not converged.
  • log (bool, optional (default=False)) – If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation matrix.
Returns:

  • gamma ((ns x nt) numpy.ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – If input log is true, a dictionary containing the cost and dual variables and exit status

Examples

Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays

>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd(a,b,M)
array([[0.5, 0. ],
       [0. , 0.5]])

References

[1]Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM.

See also

ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.lp.emd2(a, b, M, processes=4, numItermax=100000, log=False, return_matrix=False)[source]

Solves the Earth Movers distance problem and returns the loss

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F\\s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the metric cost matrix
  • a and b are the sample weights

Warning

Note that the M matrix needs to be a C-order numpy.array in float64 format.

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) numpy.ndarray, float64) – Source histogram (uniform weight if empty list)
  • b ((nt,) numpy.ndarray, float64) – Target histogram (uniform weight if empty list)
  • M ((ns,nt) numpy.ndarray, float64) – Loss matrix (c-order array with type float64)
  • processes (int, optional (default=nb cpu)) – Nb of processes used for multiple emd computation (not used on windows)
  • numItermax (int, optional (default=100000)) – The maximum number of iterations before stopping the optimization algorithm if it has not converged.
  • log (boolean, optional (default=False)) – If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation cost.
  • return_matrix (boolean, optional (default=False)) – If True, returns the optimal transportation matrix in the log.
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dictnp) – If input log is true, a dictionary containing the cost and dual variables and exit status

Examples

Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays

>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.emd2(a,b,M)
0.0

References

[1]Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM.

See also

ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.lp.barycenter(A, M, weights=None, verbose=False, log=False, solver='interior-point')[source]

Compute the Wasserstein barycenter of distributions A

The function solves the following optimization problem [16]:
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{1}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(W_1(\cdot,\cdot)\) is the Wasserstein distance (see ot.emd.sinkhorn)
  • \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\)

The linear program is solved using the interior point solver from scipy.optimize. If cvxopt solver if installed it can use cvxopt

Note that this problem do not scale well (both in memory and computational time).

Parameters:
  • A (np.ndarray (d,n)) – n training distributions a_i of size d
  • M (np.ndarray (d,d)) – loss matrix for OT
  • reg (float) – Regularization term >0
  • weights (np.ndarray (n,)) – Weights of each histogram a_i on the simplex (barycentric coodinates)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
  • solver (string, optional) – the solver used, default ‘interior-point’ use the lp solver from scipy.optimize. None, or ‘glpk’ or ‘mosek’ use the solver from cvxopt.
Returns:

  • a ((d,) ndarray) – Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[16]Agueh, M., & Carlier, G. (2011). Barycenters in the Wasserstein space. SIAM Journal on Mathematical Analysis, 43(2), 904-924.
ot.lp.free_support_barycenter(measures_locations, measures_weights, X_init, b=None, weights=None, numItermax=100, stopThr=1e-07, verbose=False, log=None)[source]

Solves the free support (locations of the barycenters are optimized, not the weights) Wasserstein barycenter problem (i.e. the weighted Frechet mean for the 2-Wasserstein distance)

The function solves the Wasserstein barycenter problem when the barycenter measure is constrained to be supported on k atoms. This problem is considered in [1] (Algorithm 2). There are two differences with the following codes: - we do not optimize over the weights - we do not do line search for the locations updates, we use i.e. theta = 1 in [1] (Algorithm 2). This can be seen as a discrete implementation of the fixed-point algorithm of [2] proposed in the continuous setting.

Parameters:
  • measures_locations (list of (k_i,d) numpy.ndarray) – The discrete support of a measure supported on k_i locations of a d-dimensional space (k_i can be different for each element of the list)
  • measures_weights (list of (k_i,) numpy.ndarray) – Numpy arrays where each numpy array has k_i non-negatives values summing to one representing the weights of each discrete input measure
  • X_init ((k,d) np.ndarray) – Initialization of the support locations (on k atoms) of the barycenter
  • b ((k,) np.ndarray) – Initialization of the weights of the barycenter (non-negatives, sum to 1)
  • weights ((k,) np.ndarray) – Initialization of the coefficients of the barycenter (non-negatives, sum to 1)
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshold on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

X – Support locations (on k atoms) of the barycenter

Return type:

(k,d) np.ndarray

References

[1]Cuturi, Marco, and Arnaud Doucet. “Fast computation of Wasserstein barycenters.” International Conference on Machine Learning. 2014.
[2]Á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.
ot.lp.emd_1d(x_a, x_b, a=None, b=None, metric='sqeuclidean', p=1.0, dense=True, log=False)[source]

Solves the Earth Movers distance problem between 1d measures and returns the OT matrix

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma \sum_i \sum_j \gamma_{ij} d(x_a[i], x_b[j])\\s.t. \gamma 1 = a, \gamma^T 1= b, \gamma\geq 0\end{aligned}\end{align} \]

where :

  • d is the metric
  • x_a and x_b are the samples
  • a and b are the sample weights

When ‘minkowski’ is used as a metric, \(d(x, y) = |x - y|^p\).

Uses the algorithm detailed in [1]_

Parameters:
  • x_a ((ns,) or (ns, 1) ndarray, float64) – Source dirac locations (on the real line)
  • x_b ((nt,) or (ns, 1) ndarray, float64) – Target dirac locations (on the real line)
  • a ((ns,) ndarray, float64, optional) – Source histogram (default is uniform weight)
  • b ((nt,) ndarray, float64, optional) – Target histogram (default is uniform weight)
  • metric (str, optional (default='sqeuclidean')) – Metric to be used. Only strings listed in ot.dist() are accepted. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • p (float, optional (default=1.0)) – The p-norm to apply for if metric=’minkowski’
  • dense (boolean, optional (default=True)) – If True, returns math:gamma as a dense ndarray of shape (ns, nt). Otherwise returns a sparse representation using scipy’s coo_matrix format. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘minkowski’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • log (boolean, optional (default=False)) – If True, returns a dictionary containing the cost. Otherwise returns only the optimal transportation matrix.
Returns:

  • gamma ((ns, nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – If input log is True, a dictionary containing the cost

Examples

Simple example with obvious solution. The function emd_1d accepts lists and performs automatic conversion to numpy arrays

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> x_a = [2., 0.]
>>> x_b = [0., 3.]
>>> ot.emd_1d(x_a, x_b, a, b)
array([[0. , 0.5],
       [0.5, 0. ]])
>>> ot.emd_1d(x_a, x_b)
array([[0. , 0.5],
       [0.5, 0. ]])

References

[1]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.

See also

ot.lp.emd()
EMD for multidimensional distributions
ot.lp.emd2_1d()
EMD for 1d distributions (returns cost instead of the transportation matrix)
ot.lp.emd2_1d(x_a, x_b, a=None, b=None, metric='sqeuclidean', p=1.0, dense=True, log=False)[source]

Solves the Earth Movers distance problem between 1d measures and returns the loss

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma \sum_i \sum_j \gamma_{ij} d(x_a[i], x_b[j])\\s.t. \gamma 1 = a, \gamma^T 1= b, \gamma\geq 0\end{aligned}\end{align} \]

where :

  • d is the metric
  • x_a and x_b are the samples
  • a and b are the sample weights

When ‘minkowski’ is used as a metric, \(d(x, y) = |x - y|^p\).

Uses the algorithm detailed in [1]_

Parameters:
  • x_a ((ns,) or (ns, 1) ndarray, float64) – Source dirac locations (on the real line)
  • x_b ((nt,) or (ns, 1) ndarray, float64) – Target dirac locations (on the real line)
  • a ((ns,) ndarray, float64, optional) – Source histogram (default is uniform weight)
  • b ((nt,) ndarray, float64, optional) – Target histogram (default is uniform weight)
  • metric (str, optional (default='sqeuclidean')) – Metric to be used. Only strings listed in ot.dist() are accepted. Due to implementation details, this function runs faster when ‘sqeuclidean’, ‘minkowski’, ‘cityblock’, or ‘euclidean’ metrics are used.
  • p (float, optional (default=1.0)) – The p-norm to apply for if metric=’minkowski’
  • dense (boolean, optional (default=True)) – If True, returns math:gamma as a dense ndarray of shape (ns, nt). Otherwise returns a sparse representation using scipy’s coo_matrix format. Only used if log is set to True. Due to implementation details, this function runs faster when dense is set to False.
  • log (boolean, optional (default=False)) – If True, returns a dictionary containing the transportation matrix. Otherwise returns only the loss.
Returns:

  • loss (float) – Cost associated to the optimal transportation
  • log (dict) – If input log is True, a dictionary containing the Optimal transportation matrix for the given parameters

Examples

Simple example with obvious solution. The function emd2_1d accepts lists and performs automatic conversion to numpy arrays

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> x_a = [2., 0.]
>>> x_b = [0., 3.]
>>> ot.emd2_1d(x_a, x_b, a, b)
0.5
>>> ot.emd2_1d(x_a, x_b)
0.5

References

[1]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.

See also

ot.lp.emd2()
EMD for multidimensional distributions
ot.lp.emd_1d()
EMD for 1d distributions (returns the transportation matrix instead of the cost)
ot.lp.wasserstein_1d(x_a, x_b, a=None, b=None, p=1.0)[source]

Solves the p-Wasserstein distance problem between 1d measures and returns the distance

\[ \begin{align}\begin{aligned}\min_\gamma \left( \sum_i \sum_j \gamma_{ij} \|x_a[i] - x_b[j]\|^p \right)^{1/p}\\s.t. \gamma 1 = a, \gamma^T 1= b, \gamma\geq 0\end{aligned}\end{align} \]

where :

  • x_a and x_b are the samples
  • a and b are the sample weights

Uses the algorithm detailed in [1]_

Parameters:
  • x_a ((ns,) or (ns, 1) ndarray, float64) – Source dirac locations (on the real line)
  • x_b ((nt,) or (ns, 1) ndarray, float64) – Target dirac locations (on the real line)
  • a ((ns,) ndarray, float64, optional) – Source histogram (default is uniform weight)
  • b ((nt,) ndarray, float64, optional) – Target histogram (default is uniform weight)
  • p (float, optional (default=1.0)) – The order of the p-Wasserstein distance to be computed
Returns:

dist – p-Wasserstein distance

Return type:

float

Examples

Simple example with obvious solution. The function wasserstein_1d accepts lists and performs automatic conversion to numpy arrays

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> x_a = [2., 0.]
>>> x_b = [0., 3.]
>>> ot.wasserstein_1d(x_a, x_b, a, b)
0.5
>>> ot.wasserstein_1d(x_a, x_b)
0.5

References

[1]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.

See also

ot.lp.emd_1d()
EMD for 1d distributions

ot.bregman

Bregman projections for regularized OT

ot.bregman.barycenter(A, M, reg, weights=None, method='sinkhorn', numItermax=10000, stopThr=0.0001, verbose=False, log=False, **kwargs)[source]

Compute the entropic regularized wasserstein barycenter of distributions A

The function solves the following optimization problem:
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(W_{reg}(\cdot,\cdot)\) is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
  • \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\)
  • reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_

Parameters:
  • A (ndarray, shape (dim, n_hists)) – n_hists training distributions a_i of size dim
  • M (ndarray, shape (dim, dim)) – loss matrix for OT
  • reg (float) – Regularization term > 0
  • method (str (optional)) – method used for the solver either ‘sinkhorn’ or ‘sinkhorn_stabilized’
  • weights (ndarray, shape (n_hists,)) – Weights of each histogram a_i on the simplex (barycentric coodinates)
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
ot.bregman.barycenter_sinkhorn(A, M, reg, weights=None, numItermax=1000, stopThr=0.0001, verbose=False, log=False)[source]

Compute the entropic regularized wasserstein barycenter of distributions A

The function solves the following optimization problem:
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(W_{reg}(\cdot,\cdot)\) is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
  • \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\)
  • reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_

Parameters:
  • A (ndarray, shape (dim, n_hists)) – n_hists training distributions a_i of size dim
  • M (ndarray, shape (dim, dim)) – loss matrix for OT
  • reg (float) – Regularization term > 0
  • weights (ndarray, shape (n_hists,)) – Weights of each histogram a_i on the simplex (barycentric coodinates)
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
ot.bregman.barycenter_stabilized(A, M, reg, tau=10000000000.0, weights=None, numItermax=1000, stopThr=0.0001, verbose=False, log=False)[source]
Compute the entropic regularized wasserstein barycenter of distributions A
with stabilization.

The function solves the following optimization problem:

\[\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(W_{reg}(\cdot,\cdot)\) is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
  • \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\)
  • reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_

Parameters:
  • A (ndarray, shape (dim, n_hists)) – n_hists training distributions a_i of size dim
  • M (ndarray, shape (dim, dim)) – loss matrix for OT
  • reg (float) – Regularization term > 0
  • tau (float) – thershold for max value in u or v for log scaling
  • weights (ndarray, shape (n_hists,)) – Weights of each histogram a_i on the simplex (barycentric coodinates)
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
ot.bregman.convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-09, stabThr=1e-30, verbose=False, log=False)[source]

Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images.

The function solves the following optimization problem:
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(W_{reg}(\cdot,\cdot)\) is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
  • \(\mathbf{a}_i\) are training distributions (2D images) in the mast two dimensions of matrix \(\mathbf{A}\)
  • reg is the regularization strength scalar value

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]

Parameters:
  • A (ndarray, shape (n_hists, width, height)) – n distributions (2D images) of size width x height
  • reg (float) – Regularization term >0
  • weights (ndarray, shape (n_hists,)) – Weights of each image on the simplex (barycentric coodinates)
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (> 0)
  • stabThr (float, optional) – Stabilization threshold to avoid numerical precision issue
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a (ndarray, shape (width, height)) – 2D Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[21]Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).

Convolutional wasserstein distances: Efficient optimal transportation on geometric domains ACM Transactions on Graphics (TOG), 34(4), 66

ot.bregman.empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • \(M\) is the (n_samples_a, n_samples_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(a\) and \(b\) are source and target weights (sum to 1)
Parameters:
  • X_s (ndarray, shape (n_samples_a, dim)) – samples in the source domain
  • X_t (ndarray, shape (n_samples_b, dim)) – samples in the target domain
  • reg (float) – Regularization term >0
  • a (ndarray, shape (n_samples_a,)) – samples weights in the source domain
  • b (ndarray, shape (n_samples_b,)) – samples weights in the target domain
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (n_samples_a, n_samples_b)) – Regularized optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> n_samples_a = 2
>>> n_samples_b = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_samples_a), (n_samples_a, 1))
>>> X_t = np.reshape(np.arange(0, n_samples_b), (n_samples_b, 1))
>>> empirical_sinkhorn(X_s, X_t, reg, verbose=False)  # doctest: +NORMALIZE_WHITESPACE
array([[4.99977301e-01,  2.26989344e-05],
       [2.26989344e-05,  4.99977301e-01]])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
ot.bregman.empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem from empirical data and return the OT loss

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • \(M\) is the (n_samples_a, n_samples_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(a\) and \(b\) are source and target weights (sum to 1)
Parameters:
  • X_s (ndarray, shape (n_samples_a, dim)) – samples in the source domain
  • X_t (ndarray, shape (n_samples_b, dim)) – samples in the target domain
  • reg (float) – Regularization term >0
  • a (ndarray, shape (n_samples_a,)) – samples weights in the source domain
  • b (ndarray, shape (n_samples_b,)) – samples weights in the target domain
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (n_samples_a, n_samples_b)) – Regularized optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> n_samples_a = 2
>>> n_samples_b = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_samples_a), (n_samples_a, 1))
>>> X_t = np.reshape(np.arange(0, n_samples_b), (n_samples_b, 1))
>>> empirical_sinkhorn2(X_s, X_t, reg, verbose=False)
array([4.53978687e-05])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
ot.bregman.empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Compute the sinkhorn divergence loss from empirical data

The function solves the following optimization problems and return the sinkhorn divergence \(S\):

\[ \begin{align}\begin{aligned}W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_a)\\W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b)\\S &= W - 1/2 * (W_a + W_b)\end{aligned}\end{align} \]
\[ \begin{align}\begin{aligned}s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\\ \gamma_a 1 = a\\ \gamma_a^T 1= a\\ \gamma_a\geq 0\\ \gamma_b 1 = b\\ \gamma_b^T 1= b\\ \gamma_b\geq 0\end{aligned}\end{align} \]

where :

  • \(M\) (resp. \(M_a, M_b\)) is the (n_samples_a, n_samples_b) metric cost matrix (resp (n_samples_a, n_samples_a) and (n_samples_b, n_samples_b))
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(a\) and \(b\) are source and target weights (sum to 1)
Parameters:
  • X_s (ndarray, shape (n_samples_a, dim)) – samples in the source domain
  • X_t (ndarray, shape (n_samples_b, dim)) – samples in the target domain
  • reg (float) – Regularization term >0
  • a (ndarray, shape (n_samples_a,)) – samples weights in the source domain
  • b (ndarray, shape (n_samples_b,)) – samples weights in the target domain
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (n_samples_a, n_samples_b)) – Regularized optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> n_samples_a = 2
>>> n_samples_b = 4
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_samples_a), (n_samples_a, 1))
>>> X_t = np.reshape(np.arange(0, n_samples_b), (n_samples_b, 1))
>>> empirical_sinkhorn_divergence(X_s, X_t, reg)  # doctest: +ELLIPSIS
array([1.499...])

References

[23]Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018
ot.bregman.geometricBar(weights, alldistribT)[source]

return the weighted geometric mean of distributions

ot.bregman.geometricMean(alldistribT)[source]

return the geometric mean of distributions

ot.bregman.greenkhorn(a, b, M, reg, numItermax=10000, stopThr=1e-09, verbose=False, log=False)[source]

Solve the entropic regularization optimal transport problem and return the OT matrix

The algorithm used is based on the paper

Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration
by Jason Altschuler, Jonathan Weed, Philippe Rigollet appeared at NIPS 2017

which is a stochastic version of the Sinkhorn-Knopp algorithm [2].

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)
Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,) or ndarray, shape (dim_b, n_hists)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (dim_a, dim_b)) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.bregman.greenkhorn(a, b, M, 1)
array([[0.36552929, 0.13447071],
       [0.13447071, 0.36552929]])

References

[2]M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 [22] J. Altschuler, J.Weed, P. Rigollet : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.projC(gamma, q)[source]

return the KL projection on the column constrints

ot.bregman.projR(gamma, p)[source]

return the KL projection on the row constrints

ot.bregman.sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem and return the OT matrix

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_

Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,) or ndarray, shape (dim_b, n_hists)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘greenkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_epsilon_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (dim_a, dim_b)) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn(a, b, M, 1)
array([[0.36552929, 0.13447071],
       [0.13447071, 0.36552929]])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.sinkhorn_knopp()
Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized()
Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling()
Sinkhorn with epslilon scaling [9][10]
ot.bregman.sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem and return the loss

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_

Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,) or ndarray, shape (dim_b, n_hists)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_epsilon_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • W ((n_hists) ndarray or float) – Optimal transportation loss for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn2(a, b, M, 1)
array([0.26894142])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]

Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.

[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.sinkhorn_knopp()
Classic Sinkhorn [2]
ot.bregman.greenkhorn()
Greenkhorn [21]
ot.bregman.sinkhorn_stabilized()
Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling()
Sinkhorn with epslilon scaling [9][10]
ot.bregman.sinkhorn_epsilon_scaling(a, b, M, reg, numItermax=100, epsilon0=10000.0, numInnerItermax=100, tau=1000.0, stopThr=1e-09, warmstart=None, verbose=False, print_period=10, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem with log stabilization and epsilon scaling.

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ but with the log stabilization proposed in [10]_ and the log scaling proposed in [9]_ algorithm 3.2

Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,)) – samples in the target domain
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • tau (float) – thershold for max value in u or v for log scaling
  • warmstart (tuple of vectors) – if given then sarting values for alpha an beta log scalings
  • numItermax (int, optional) – Max number of iterations
  • numInnerItermax (int, optional) – Max number of iterationsin the inner slog stabilized sinkhorn
  • epsilon0 (int, optional) – first epsilon regularization value (then exponential decrease to reg)
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (dim_a, dim_b)) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.bregman.sinkhorn_epsilon_scaling(a, b, M, 1)
array([[0.36552929, 0.13447071],
       [0.13447071, 0.36552929]])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.sinkhorn_knopp(a, b, M, reg, numItermax=1000, stopThr=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization optimal transport problem and return the OT matrix

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_

Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,) or ndarray, shape (dim_b, n_hists)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (dim_a, dim_b)) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn(a, b, M, 1)
array([[0.36552929, 0.13447071],
       [0.13447071, 0.36552929]])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.sinkhorn_stabilized(a, b, M, reg, numItermax=1000, tau=1000.0, stopThr=1e-09, warmstart=None, verbose=False, print_period=20, log=False, **kwargs)[source]

Solve the entropic regularization OT problem with log stabilization

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (histograms, both sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ but with the log stabilization proposed in [10]_ an defined in [9]_ (Algo 3.1) .

Parameters:
  • a (ndarray, shape (dim_a,)) – samples weights in the source domain
  • b (ndarray, shape (dim_b,)) – samples in the target domain
  • M (ndarray, shape (dim_a, dim_b)) – loss matrix
  • reg (float) – Regularization term >0
  • tau (float) – thershold for max value in u or v for log scaling
  • warmstart (tible of vectors) – if given then sarting values for alpha an beta log scalings
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (dim_a, dim_b)) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.bregman.sinkhorn_stabilized(a, b, M, 1)
array([[0.36552929, 0.13447071],
       [0.13447071, 0.36552929]])

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.bregman.unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000, stopThr=0.001, verbose=False, log=False)[source]

Compute the unmixing of an observation with a given dictionary using Wasserstein distance

The function solve the following optimization problem:

\[\begin{split}\mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h})\end{split}\]

where :

  • \(W_{M,reg}(\cdot,\cdot)\) is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
  • math:mathbf{D} is a dictionary of n_atoms atoms of dimension dim_a, its expected shape is (dim_a, n_atoms)
  • \(\mathbf{h}\) is the estimated unmixing of dimension n_atoms
  • \(\mathbf{a}\) is an observed distribution of dimension dim_a
  • \(\mathbf{h}_0\) is a prior on h of dimension dim_prior
  • reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix (dim_a, dim_a) for OT data fitting
  • reg0 and \(\mathbf{M0}\) are respectively the regularization term and the cost matrix (dim_prior, n_atoms) regularization
  • :math:`\alpha`weight data fitting and regularization

The optimization problem is solved suing the algorithm described in [4]

Parameters:
  • a (ndarray, shape (dim_a)) – observed distribution (histogram, sums to 1)
  • D (ndarray, shape (dim_a, n_atoms)) – dictionary matrix
  • M (ndarray, shape (dim_a, dim_a)) – loss matrix
  • M0 (ndarray, shape (n_atoms, dim_prior)) – loss matrix
  • h0 (ndarray, shape (n_atoms,)) – prior on the estimated unmixing h
  • reg (float) – Regularization term >0 (Wasserstein data fitting)
  • reg0 (float) – Regularization term >0 (Wasserstein reg with h0)
  • alpha (float) – How much should we trust the prior ([0,1])
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • h (ndarray, shape (n_atoms,)) – Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[4]
  1. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016.

ot.smooth

Implementation of Smooth and Sparse Optimal Transport. Mathieu Blondel, Vivien Seguy, Antoine Rolet. In Proc. of AISTATS 2018. https://arxiv.org/abs/1710.06276

[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).

Original code from https://github.com/mblondel/smooth-ot/

class ot.smooth.NegEntropy(gamma=1.0)[source]

NegEntropy regularization

Omega(T)[source]

Compute regularization term.

Parameters:T (array, shape = len(a) x len(b)) – Input array.
Returns:value – Regularization term.
Return type:float
delta_Omega(X)[source]

Compute delta_Omega(X[:, j]) for each X[:, j]. delta_Omega(x) = sup_{y >= 0} y^T x - Omega(y).

Parameters:X (array, shape = len(a) x len(b)) – Input array.
Returns:
  • v (array, len(b)) – Values: v[j] = delta_Omega(X[:, j])
  • G (array, len(a) x len(b)) – Gradients: G[:, j] = nabla delta_Omega(X[:, j])
max_Omega(X, b)[source]

Compute max_Omega_j(X[:, j]) for each X[:, j]. max_Omega_j(x) = sup_{y >= 0, sum(y) = 1} y^T x - Omega(b[j] y) / b[j].

Parameters:X (array, shape = len(a) x len(b)) – Input array.
Returns:
  • v (array, len(b)) – Values: v[j] = max_Omega_j(X[:, j])
  • G (array, len(a) x len(b)) – Gradients: G[:, j] = nabla max_Omega_j(X[:, j])
class ot.smooth.Regularization(gamma=1.0)[source]

Base class for Regularization objects

Notes

This class is not intended for direct use but as aparent for true regularizatiojn implementation.

Omega()[source]

Compute regularization term.

Parameters:T (array, shape = len(a) x len(b)) – Input array.
Returns:value – Regularization term.
Return type:float
delta_Omega()[source]

Compute delta_Omega(X[:, j]) for each X[:, j]. delta_Omega(x) = sup_{y >= 0} y^T x - Omega(y).

Parameters:X (array, shape = len(a) x len(b)) – Input array.
Returns:
  • v (array, len(b)) – Values: v[j] = delta_Omega(X[:, j])
  • G (array, len(a) x len(b)) – Gradients: G[:, j] = nabla delta_Omega(X[:, j])
max_Omega(b)[source]

Compute max_Omega_j(X[:, j]) for each X[:, j]. max_Omega_j(x) = sup_{y >= 0, sum(y) = 1} y^T x - Omega(b[j] y) / b[j].

Parameters:X (array, shape = len(a) x len(b)) – Input array.
Returns:
  • v (array, len(b)) – Values: v[j] = max_Omega_j(X[:, j])
  • G (array, len(a) x len(b)) – Gradients: G[:, j] = nabla max_Omega_j(X[:, j])
class ot.smooth.SquaredL2(gamma=1.0)[source]

Squared L2 regularization

Omega(T)[source]

Compute regularization term.

Parameters:T (array, shape = len(a) x len(b)) – Input array.
Returns:value – Regularization term.
Return type:float
delta_Omega(X)[source]

Compute delta_Omega(X[:, j]) for each X[:, j]. delta_Omega(x) = sup_{y >= 0} y^T x - Omega(y).

Parameters:X (array, shape = len(a) x len(b)) – Input array.
Returns:
  • v (array, len(b)) – Values: v[j] = delta_Omega(X[:, j])
  • G (array, len(a) x len(b)) – Gradients: G[:, j] = nabla delta_Omega(X[:, j])
max_Omega(X, b)[source]

Compute max_Omega_j(X[:, j]) for each X[:, j]. max_Omega_j(x) = sup_{y >= 0, sum(y) = 1} y^T x - Omega(b[j] y) / b[j].

Parameters:X (array, shape = len(a) x len(b)) – Input array.
Returns:
  • v (array, len(b)) – Values: v[j] = max_Omega_j(X[:, j])
  • G (array, len(a) x len(b)) – Gradients: G[:, j] = nabla max_Omega_j(X[:, j])
ot.smooth.dual_obj_grad(alpha, beta, a, b, C, regul)[source]

Compute objective value and gradients of dual objective.

Parameters:
  • alpha (array, shape = len(a)) –
  • beta (array, shape = len(b)) – Current iterate of dual potentials.
  • a (array, shape = len(a)) –
  • b (array, shape = len(b)) – Input histograms (should be non-negative and sum to 1).
  • C (array, shape = len(a) x len(b)) – Ground cost matrix.
  • regul (Regularization object) – Should implement a delta_Omega(X) method.
Returns:

  • obj (float) – Objective value (higher is better).
  • grad_alpha (array, shape = len(a)) – Gradient w.r.t. alpha.
  • grad_beta (array, shape = len(b)) – Gradient w.r.t. beta.

ot.smooth.get_plan_from_dual(alpha, beta, C, regul)[source]

Retrieve optimal transportation plan from optimal dual potentials.

Parameters:
  • alpha (array, shape = len(a)) –
  • beta (array, shape = len(b)) – Optimal dual potentials.
  • C (array, shape = len(a) x len(b)) – Ground cost matrix.
  • regul (Regularization object) – Should implement a delta_Omega(X) method.
Returns:

T – Optimal transportation plan.

Return type:

array, shape = len(a) x len(b)

ot.smooth.get_plan_from_semi_dual(alpha, b, C, regul)[source]

Retrieve optimal transportation plan from optimal semi-dual potentials.

Parameters:
  • alpha (array, shape = len(a)) – Optimal semi-dual potentials.
  • b (array, shape = len(b)) – Second input histogram (should be non-negative and sum to 1).
  • C (array, shape = len(a) x len(b)) – Ground cost matrix.
  • regul (Regularization object) – Should implement a delta_Omega(X) method.
Returns:

T – Optimal transportation plan.

Return type:

array, shape = len(a) x len(b)

ot.smooth.projection_simplex(V, z=1, axis=None)[source]

Projection of x onto the simplex, scaled by z

P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2
z: float or array
If array, len(z) must be compatible with V
axis: None or int
  • axis=None: project V by P(V.ravel(); z)
  • axis=1: project each V[i] by P(V[i]; z[i])
  • axis=0: project each V[:, j] by P(V[:, j]; z[j])
ot.smooth.semi_dual_obj_grad(alpha, a, b, C, regul)[source]

Compute objective value and gradient of semi-dual objective.

Parameters:
  • alpha (array, shape = len(a)) – Current iterate of semi-dual potentials.
  • a (array, shape = len(a)) –
  • b (array, shape = len(b)) – Input histograms (should be non-negative and sum to 1).
  • C (array, shape = len(a) x len(b)) – Ground cost matrix.
  • regul (Regularization object) – Should implement a max_Omega(X) method.
Returns:

  • obj (float) – Objective value (higher is better).
  • grad (array, shape = len(a)) – Gradient w.r.t. alpha.

ot.smooth.smooth_ot_dual(a, b, M, reg, reg_type='l2', method='L-BFGS-B', stopThr=1e-09, numItermax=500, verbose=False, log=False)[source]

Solve the regularized OT problem in the dual and return the OT matrix

The function solves the smooth relaxed dual formulation (7) in [17]_ :

\[\max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j)\]

where :

  • \(\mathbf{m}_j\) is the jth column of the cost matrix
  • \(\delta_\Omega\) is the convex conjugate of the regularization term \(\Omega\)
  • a and b are source and target weights (sum to 1)

The OT matrix can is reconstructed from the gradient of \(\delta_\Omega\) (See [17]_ Proposition 1). The optimization algorithm is using gradient decent (L-BFGS by default).

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • b (np.ndarray (nt,) or np.ndarray (nt,nbb)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term >0
  • reg_type (str) – Regularization type, can be the following (default =’l2’): - ‘kl’ : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - ‘l2’ : Squared Euclidean regularization
  • method (str) – Solver to use for scipy.optimize.minimize
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[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).

See also

ot.lp.emd()
Unregularized OT
ot.sinhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.smooth.smooth_ot_semi_dual(a, b, M, reg, reg_type='l2', method='L-BFGS-B', stopThr=1e-09, numItermax=500, verbose=False, log=False)[source]

Solve the regularized OT problem in the semi-dual and return the OT matrix

The function solves the smooth relaxed dual formulation (10) in [17]_ :

\[\max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b)\]

where :

\[OT_\Omega^*(\alpha,b)=\sum_j b_j\]
  • \(\mathbf{m}_j\) is the jth column of the cost matrix
  • \(OT_\Omega^*(\alpha,b)\) is defined in Eq. (9) in [17]
  • a and b are source and target weights (sum to 1)

The OT matrix can is reconstructed using [17]_ Proposition 2. The optimization algorithm is using gradient decent (L-BFGS by default).

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • b (np.ndarray (nt,) or np.ndarray (nt,nbb)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term >0
  • reg_type (str) – Regularization type, can be the following (default =’l2’): - ‘kl’ : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - ‘l2’ : Squared Euclidean regularization
  • method (str) – Solver to use for scipy.optimize.minimize
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[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).

See also

ot.lp.emd()
Unregularized OT
ot.sinhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.smooth.solve_dual(a, b, C, regul, method='L-BFGS-B', tol=0.001, max_iter=500, verbose=False)[source]

Solve the “smoothed” dual objective.

Parameters:
  • a (array, shape = len(a)) –
  • b (array, shape = len(b)) – Input histograms (should be non-negative and sum to 1).
  • C (array, shape = len(a) x len(b)) – Ground cost matrix.
  • regul (Regularization object) – Should implement a delta_Omega(X) method.
  • method (str) – Solver to be used (passed to scipy.optimize.minimize).
  • tol (float) – Tolerance parameter.
  • max_iter (int) – Maximum number of iterations.
Returns:

  • alpha (array, shape = len(a))
  • beta (array, shape = len(b)) – Dual potentials.

ot.smooth.solve_semi_dual(a, b, C, regul, method='L-BFGS-B', tol=0.001, max_iter=500, verbose=False)[source]

Solve the “smoothed” semi-dual objective.

Parameters:
  • a (array, shape = len(a)) –
  • b (array, shape = len(b)) – Input histograms (should be non-negative and sum to 1).
  • C (array, shape = len(a) x len(b)) – Ground cost matrix.
  • regul (Regularization object) – Should implement a max_Omega(X) method.
  • method (str) – Solver to be used (passed to scipy.optimize.minimize).
  • tol (float) – Tolerance parameter.
  • max_iter (int) – Maximum number of iterations.
Returns:

alpha – Semi-dual potentials.

Return type:

array, shape = len(a)

ot.gromov

Gromov-Wasserstein transport method

ot.gromov.entropic_gromov_barycenters(N, Cs, ps, p, lambdas, loss_fun, epsilon, max_iter=1000, tol=1e-09, verbose=False, log=False, init_C=None)[source]

Returns the gromov-wasserstein barycenters of S measured similarity matrices

(Cs)_{s=1}^{s=S}

The function solves the following optimization problem:

\[C = argmin_{C\in R^{NxN}} \sum_s \lambda_s GW(C,C_s,p,p_s)\]

Where :

  • \(C_s\) : metric cost matrix
  • \(p_s\) : distribution
Parameters:
  • N (int) – Size of the targeted barycenter
  • Cs (list of S np.ndarray of shape (ns,ns)) – Metric cost matrices
  • ps (list of S np.ndarray of shape (ns,)) – Sample weights in the S spaces
  • p (ndarray, shape(N,)) – Weights in the targeted barycenter
  • lambdas (list of float) – List of the S spaces’ weights.
  • loss_fun (callable) – Tensor-matrix multiplication function based on specific loss function.
  • update (callable) – function(p,lambdas,T,Cs) that updates C according to a specific Kernel with the S Ts couplings calculated at each iteration
  • epsilon (float) – Regularization term >0
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations.
  • log (bool, optional) – Record log if True.
  • init_C (bool | ndarray, shape (N, N)) – Random initial value for the C matrix provided by user.
Returns:

C – Similarity matrix in the barycenter space (permutated arbitrarily)

Return type:

ndarray, shape (N, N)

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.entropic_gromov_wasserstein(C1, C2, p, q, loss_fun, epsilon, max_iter=1000, tol=1e-09, verbose=False, log=False)[source]

Returns the gromov-wasserstein transport between (C1,p) and (C2,q)

(C1,p) and (C2,q)

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}GW = arg\min_T \sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}-\epsilon(H(T))\\s.t. T 1 = p\\ T^T 1= q\\ T\geq 0\end{aligned}\end{align} \]

Where : - C1 : Metric cost matrix in the source space - C2 : Metric cost matrix in the target space - p : distribution in the source space - q : distribution in the target space - L : loss function to account for the misfit between the similarity matrices - H : entropy

Parameters:
  • C1 (ndarray, shape (ns, ns)) – Metric cost matrix in the source space
  • C2 (ndarray, shape (nt, nt)) – Metric costfr matrix in the target space
  • p (ndarray, shape (ns,)) – Distribution in the source space
  • q (ndarray, shape (nt,)) – Distribution in the target space
  • loss_fun (string) – Loss function used for the solver either ‘square_loss’ or ‘kl_loss’
  • epsilon (float) – Regularization term >0
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshold on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – Record log if True.
Returns:

T – Optimal coupling between the two spaces

Return type:

ndarray, shape (ns, nt)

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.entropic_gromov_wasserstein2(C1, C2, p, q, loss_fun, epsilon, max_iter=1000, tol=1e-09, verbose=False, log=False)[source]

Returns the entropic gromov-wasserstein discrepancy between the two measured similarity matrices

(C1,p) and (C2,q)

The function solves the following optimization problem:

\[GW = \min_T \sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}-\epsilon(H(T))\]

Where : - C1 : Metric cost matrix in the source space - C2 : Metric cost matrix in the target space - p : distribution in the source space - q : distribution in the target space - L : loss function to account for the misfit between the similarity matrices - H : entropy

Parameters:
  • C1 (ndarray, shape (ns, ns)) – Metric cost matrix in the source space
  • C2 (ndarray, shape (nt, nt)) – Metric costfr matrix in the target space
  • p (ndarray, shape (ns,)) – Distribution in the source space
  • q (ndarray, shape (nt,)) – Distribution in the target space
  • loss_fun (str) – Loss function used for the solver either ‘square_loss’ or ‘kl_loss’
  • epsilon (float) – Regularization term >0
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshold on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – Record log if True.
Returns:

gw_dist – Gromov-Wasserstein distance

Return type:

float

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.fgw_barycenters(N, Ys, Cs, ps, lambdas, alpha, fixed_structure=False, fixed_features=False, p=None, loss_fun='square_loss', max_iter=100, tol=1e-09, verbose=False, log=False, init_C=None, init_X=None)[source]

Compute the fgw barycenter as presented eq (5) in [24].

Parameters:
  • N (integer) – Desired number of samples of the target barycenter
  • Ys (list of ndarray, each element has shape (ns,d)) – Features of all samples
  • Cs (list of ndarray, each element has shape (ns,ns)) – Structure matrices of all samples
  • ps (list of ndarray, each element has shape (ns,)) – Masses of all samples.
  • lambdas (list of float) – List of the S spaces’ weights
  • alpha (float) – Alpha parameter for the fgw distance
  • fixed_structure (bool) – Whether to fix the structure of the barycenter during the updates
  • fixed_features (bool) – Whether to fix the feature of the barycenter during the updates
  • init_C (ndarray, shape (N,N), optional) – Initialization for the barycenters’ structure matrix. If not set a random init is used.
  • init_X (ndarray, shape (N,d), optional) – Initialization for the barycenters’ features. If not set a random init is used.
Returns:

  • X (ndarray, shape (N, d)) – Barycenters’ features
  • C (ndarray, shape (N, N)) – Barycenters’ structure matrix
  • log_ (dict) – Only returned when log=True. It contains the keys: T : list of (N,ns) transport matrices Ms : all distance matrices between the feature of the barycenter and the other features dist(X,Ys) shape (N,ns)

References

[24]Vayer Titouan, Chapel Laetitia, Flamary R{‘e}mi, Tavenard Romain and Courty Nicolas “Optimal Transport for structured data with application on graphs” International Conference on Machine Learning (ICML). 2019.
ot.gromov.fused_gromov_wasserstein(M, C1, C2, p, q, loss_fun='square_loss', alpha=0.5, armijo=False, log=False, **kwargs)[source]

Computes the FGW transport between two graphs see [24]

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma (1-\alpha)*<\gamma,M>_F + \alpha* \sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}\\s.t. \gamma 1 = p \gamma^T 1= q \gamma\geq 0\end{aligned}\end{align} \]

where : - M is the (ns,nt) metric cost matrix - \(f\) is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) - L is a loss function to account for the misfit between the similarity matrices

The algorithm used for solving the problem is conditional gradient as discussed in [24]_

Parameters:
  • M (ndarray, shape (ns, nt)) – Metric cost matrix between features across domains
  • C1 (ndarray, shape (ns, ns)) – Metric cost matrix representative of the structure in the source space
  • C2 (ndarray, shape (nt, nt)) – Metric cost matrix representative of the structure in the target space
  • p (ndarray, shape (ns,)) – Distribution in the source space
  • q (ndarray, shape (nt,)) – Distribution in the target space
  • loss_fun (str, optional) – Loss function used for the solver
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshold on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
  • armijo (bool, optional) – If True the steps of the line-search is found via an armijo research. Else closed form is used. If there is convergence issues use False.
  • **kwargs (dict) – parameters can be directly passed to the ot.optim.cg solver
Returns:

  • gamma (ndarray, shape (ns, nt)) – Optimal transportation matrix for the given parameters.
  • log (dict) – Log dictionary return only if log==True in parameters.

References

[24]Vayer Titouan, Chapel Laetitia, Flamary R{‘e}mi, Tavenard Romain and Courty Nicolas “Optimal Transport for structured data with application on graphs”, International Conference on Machine Learning (ICML). 2019.
ot.gromov.fused_gromov_wasserstein2(M, C1, C2, p, q, loss_fun='square_loss', alpha=0.5, armijo=False, log=False, **kwargs)[source]

Computes the FGW distance between two graphs see [24]

\[ \begin{align}\begin{aligned}\min_\gamma (1-\alpha)*<\gamma,M>_F + \alpha* \sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}\\s.t. \gamma 1 = p \gamma^T 1= q \gamma\geq 0\end{aligned}\end{align} \]

where : - M is the (ns,nt) metric cost matrix - \(f\) is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) - L is a loss function to account for the misfit between the similarity matrices The algorithm used for solving the problem is conditional gradient as discussed in [1]_

Parameters:
  • M (ndarray, shape (ns, nt)) – Metric cost matrix between features across domains
  • C1 (ndarray, shape (ns, ns)) – Metric cost matrix respresentative of the structure in the source space.
  • C2 (ndarray, shape (nt, nt)) – Metric cost matrix espresentative of the structure in the target space.
  • p (ndarray, shape (ns,)) – Distribution in the source space.
  • q (ndarray, shape (nt,)) – Distribution in the target space.
  • loss_fun (str, optional) – Loss function used for the solver.
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshold on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – Record log if True.
  • armijo (bool, optional) – If True the steps of the line-search is found via an armijo research. Else closed form is used. If there is convergence issues use False.
  • **kwargs (dict) – Parameters can be directly pased to the ot.optim.cg solver.
Returns:

  • gamma (ndarray, shape (ns, nt)) – Optimal transportation matrix for the given parameters.
  • log (dict) – Log dictionary return only if log==True in parameters.

References

[24]Vayer Titouan, Chapel Laetitia, Flamary R{‘e}mi, Tavenard Romain and Courty Nicolas “Optimal Transport for structured data with application on graphs” International Conference on Machine Learning (ICML). 2019.
ot.gromov.gromov_barycenters(N, Cs, ps, p, lambdas, loss_fun, max_iter=1000, tol=1e-09, verbose=False, log=False, init_C=None)[source]

Returns the gromov-wasserstein barycenters of S measured similarity matrices

(Cs)_{s=1}^{s=S}

The function solves the following optimization problem with block coordinate descent:

\[C = argmin_C\in R^NxN \sum_s \lambda_s GW(C,Cs,p,ps)\]

Where :

  • Cs : metric cost matrix
  • ps : distribution
Parameters:
  • N (int) – Size of the targeted barycenter
  • Cs (list of S np.ndarray of shape (ns, ns)) – Metric cost matrices
  • ps (list of S np.ndarray of shape (ns,)) – Sample weights in the S spaces
  • p (ndarray, shape (N,)) – Weights in the targeted barycenter
  • lambdas (list of float) – List of the S spaces’ weights
  • loss_fun (tensor-matrix multiplication function based on specific loss function) –
  • update (function(p,lambdas,T,Cs) that updates C according to a specific Kernel) – with the S Ts couplings calculated at each iteration
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshol on error (>0).
  • verbose (bool, optional) – Print information along iterations.
  • log (bool, optional) – Record log if True.
  • init_C (bool | ndarray, shape(N,N)) – Random initial value for the C matrix provided by user.
Returns:

C – Similarity matrix in the barycenter space (permutated arbitrarily)

Return type:

ndarray, shape (N, N)

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.gromov_wasserstein(C1, C2, p, q, loss_fun, log=False, armijo=False, **kwargs)[source]

Returns the gromov-wasserstein transport between (C1,p) and (C2,q)

The function solves the following optimization problem:

\[GW = \min_T \sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}\]

Where : - C1 : Metric cost matrix in the source space - C2 : Metric cost matrix in the target space - p : distribution in the source space - q : distribution in the target space - L : loss function to account for the misfit between the similarity matrices - H : entropy

Parameters:
  • C1 (ndarray, shape (ns, ns)) – Metric cost matrix in the source space
  • C2 (ndarray, shape (nt, nt)) – Metric costfr matrix in the target space
  • p (ndarray, shape (ns,)) – Distribution in the source space
  • q (ndarray, shape (nt,)) – Distribution in the target space
  • loss_fun (str) – loss function used for the solver either ‘square_loss’ or ‘kl_loss’
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshold on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
  • armijo (bool, optional) – If True the steps of the line-search is found via an armijo research. Else closed form is used. If there is convergence issues use False.
  • **kwargs (dict) – parameters can be directly passed to the ot.optim.cg solver
Returns:

  • T (ndarray, shape (ns, nt)) –

    Doupling between the two spaces that minimizes:

    sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}

  • log (dict) – Convergence information and loss.

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
[13]Mémoli, Facundo. Gromov–Wasserstein distances and the metric approach to object matching. Foundations of computational mathematics 11.4 (2011): 417-487.
ot.gromov.gromov_wasserstein2(C1, C2, p, q, loss_fun, log=False, armijo=False, **kwargs)[source]

Returns the gromov-wasserstein discrepancy between (C1,p) and (C2,q)

The function solves the following optimization problem:

\[GW = \min_T \sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}\]

Where : - C1 : Metric cost matrix in the source space - C2 : Metric cost matrix in the target space - p : distribution in the source space - q : distribution in the target space - L : loss function to account for the misfit between the similarity matrices - H : entropy

Parameters:
  • C1 (ndarray, shape (ns, ns)) – Metric cost matrix in the source space
  • C2 (ndarray, shape (nt, nt)) – Metric cost matrix in the target space
  • p (ndarray, shape (ns,)) – Distribution in the source space.
  • q (ndarray, shape (nt,)) – Distribution in the target space.
  • loss_fun (str) – loss function used for the solver either ‘square_loss’ or ‘kl_loss’
  • max_iter (int, optional) – Max number of iterations
  • tol (float, optional) – Stop threshold on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
  • armijo (bool, optional) – If True the steps of the line-search is found via an armijo research. Else closed form is used. If there is convergence issues use False.
Returns:

  • gw_dist (float) – Gromov-Wasserstein distance
  • log (dict) – convergence information and Coupling marix

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
[13]Mémoli, Facundo. Gromov–Wasserstein distances and the metric approach to object matching. Foundations of computational mathematics 11.4 (2011): 417-487.
ot.gromov.gwggrad(constC, hC1, hC2, T)[source]

Return the gradient for Gromov-Wasserstein

The gradient is computed as described in Proposition 2 in [12].

Parameters:
  • constC (ndarray, shape (ns, nt)) – Constant C matrix in Eq. (6)
  • hC1 (ndarray, shape (ns, ns)) – h1(C1) matrix in Eq. (6)
  • hC2 (ndarray, shape (nt, nt)) – h2(C) matrix in Eq. (6)
  • T (ndarray, shape (ns, nt)) – Current value of transport matrix T
Returns:

grad – Gromov Wasserstein gradient

Return type:

ndarray, shape (ns, nt)

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.gwloss(constC, hC1, hC2, T)[source]

Return the Loss for Gromov-Wasserstein

The loss is computed as described in Proposition 1 Eq. (6) in [12].

Parameters:
  • constC (ndarray, shape (ns, nt)) – Constant C matrix in Eq. (6)
  • hC1 (ndarray, shape (ns, ns)) – h1(C1) matrix in Eq. (6)
  • hC2 (ndarray, shape (nt, nt)) – h2(C) matrix in Eq. (6)
  • T (ndarray, shape (ns, nt)) – Current value of transport matrix T
Returns:

loss – Gromov Wasserstein loss

Return type:

float

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.init_matrix(C1, C2, p, q, loss_fun='square_loss')[source]

Return loss matrices and tensors for Gromov-Wasserstein fast computation

Returns the value of mathcal{L}(C1,C2) otimes T with the selected loss function as the loss function of Gromow-Wasserstein discrepancy.

The matrices are computed as described in Proposition 1 in [12]

Where :
  • C1 : Metric cost matrix in the source space
  • C2 : Metric cost matrix in the target space
  • T : A coupling between those two spaces
The square-loss function L(a,b)=|a-b|^2 is read as :
L(a,b) = f1(a)+f2(b)-h1(a)*h2(b) with :
  • f1(a)=(a^2)
  • f2(b)=(b^2)
  • h1(a)=a
  • h2(b)=2*b
The kl-loss function L(a,b)=a*log(a/b)-a+b is read as :
L(a,b) = f1(a)+f2(b)-h1(a)*h2(b) with :
  • f1(a)=a*log(a)-a
  • f2(b)=b
  • h1(a)=a
  • h2(b)=log(b)
Parameters:
  • C1 (ndarray, shape (ns, ns)) – Metric cost matrix in the source space
  • C2 (ndarray, shape (nt, nt)) – Metric costfr matrix in the target space
  • T (ndarray, shape (ns, nt)) – Coupling between source and target spaces
  • p (ndarray, shape (ns,)) –
Returns:

  • constC (ndarray, shape (ns, nt)) – Constant C matrix in Eq. (6)
  • hC1 (ndarray, shape (ns, ns)) – h1(C1) matrix in Eq. (6)
  • hC2 (ndarray, shape (nt, nt)) – h2(C) matrix in Eq. (6)

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.tensor_product(constC, hC1, hC2, T)[source]

Return the tensor for Gromov-Wasserstein fast computation

The tensor is computed as described in Proposition 1 Eq. (6) in [12].

Parameters:
  • constC (ndarray, shape (ns, nt)) – Constant C matrix in Eq. (6)
  • hC1 (ndarray, shape (ns, ns)) – h1(C1) matrix in Eq. (6)
  • hC2 (ndarray, shape (nt, nt)) – h2(C) matrix in Eq. (6)
Returns:

tens – mathcal{L}(C1,C2) otimes T tensor-matrix multiplication result

Return type:

ndarray, shape (ns, nt)

References

[12]Peyré, Gabriel, Marco Cuturi, and Justin Solomon, “Gromov-Wasserstein averaging of kernel and distance matrices.” International Conference on Machine Learning (ICML). 2016.
ot.gromov.update_feature_matrix(lambdas, Ys, Ts, p)[source]

Updates the feature with respect to the S Ts couplings.

See “Solving the barycenter problem with Block Coordinate Descent (BCD)” in [24] calculated at each iteration

Parameters:
  • p (ndarray, shape (N,)) – masses in the targeted barycenter
  • lambdas (list of float) – List of the S spaces’ weights
  • Ts (list of S np.ndarray(ns,N)) – the S Ts couplings calculated at each iteration
  • Ys (list of S ndarray, shape(d,ns)) – The features.
Returns:

X

Return type:

ndarray, shape (d, N)

References

[24]
Vayer Titouan, Chapel Laetitia, Flamary R{‘e}mi, Tavenard Romain
and Courty Nicolas

“Optimal Transport for structured data with application on graphs” International Conference on Machine Learning (ICML). 2019.

ot.gromov.update_kl_loss(p, lambdas, T, Cs)[source]

Updates C according to the KL Loss kernel with the S Ts couplings calculated at each iteration

Parameters:
  • p (ndarray, shape (N,)) – Weights in the targeted barycenter.
  • lambdas (list of the S spaces' weights) –
  • T (list of S np.ndarray of shape (ns,N)) – The S Ts couplings calculated at each iteration.
  • Cs (list of S ndarray, shape(ns,ns)) – Metric cost matrices.
Returns:

C – updated C matrix

Return type:

ndarray, shape (ns,ns)

ot.gromov.update_square_loss(p, lambdas, T, Cs)[source]

Updates C according to the L2 Loss kernel with the S Ts couplings calculated at each iteration

Parameters:
  • p (ndarray, shape (N,)) – Masses in the targeted barycenter.
  • lambdas (list of float) – List of the S spaces’ weights.
  • T (list of S np.ndarray of shape (ns,N)) – The S Ts couplings calculated at each iteration.
  • Cs (list of S ndarray, shape(ns,ns)) – Metric cost matrices.
Returns:

C – Updated C matrix.

Return type:

ndarray, shape (nt, nt)

ot.gromov.update_sructure_matrix(p, lambdas, T, Cs)[source]

Updates C according to the L2 Loss kernel with the S Ts couplings.

It is calculated at each iteration

Parameters:
  • p (ndarray, shape (N,)) – Masses in the targeted barycenter.
  • lambdas (list of float) – List of the S spaces’ weights.
  • T (list of S ndarray of shape (ns, N)) – The S Ts couplings calculated at each iteration.
  • Cs (list of S ndarray, shape (ns, ns)) – Metric cost matrices.
Returns:

C – Updated C matrix.

Return type:

ndarray, shape (nt, nt)

ot.optim

Optimization algorithms for OT

ot.optim.cg(a, b, M, reg, f, df, G0=None, numItermax=200, stopThr=1e-09, stopThr2=1e-09, verbose=False, log=False, **kwargs)[source]

Solve the general regularized OT problem with conditional gradient

The function solves the following optimization problem:
\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) metric cost matrix
  • \(f\) is the regularization term ( and df is its gradient)
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is conditional gradient as discussed in [1]_

Parameters:
  • a (ndarray, shape (ns,)) – samples weights in the source domain
  • b (ndarray, shape (nt,)) – samples in the target domain
  • M (ndarray, shape (ns, nt)) – loss matrix
  • reg (float) – Regularization term >0
  • G0 (ndarray, shape (ns,nt), optional) – initial guess (default is indep joint density)
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on the relative variation (>0)
  • stopThr2 (float, optional) – Stop threshol on the absolute variation (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
  • **kwargs (dict) – Parameters for linesearch
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[1]Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882.

See also

ot.lp.emd()
Unregularized optimal ransport
ot.bregman.sinkhorn()
Entropic regularized optimal transport
ot.optim.gcg(a, b, M, reg1, reg2, f, df, G0=None, numItermax=10, numInnerItermax=200, stopThr=1e-09, stopThr2=1e-09, verbose=False, log=False)[source]

Solve the general regularized OT problem with the generalized conditional gradient

The function solves the following optimization problem:
\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(f\) is the regularization term ( and df is its gradient)
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_

Parameters:
  • a (ndarray, shape (ns,)) – samples weights in the source domain
  • b (ndarrayv (nt,)) – samples in the target domain
  • M (ndarray, shape (ns, nt)) – loss matrix
  • reg1 (float) – Entropic Regularization term >0
  • reg2 (float) – Second Regularization term >0
  • G0 (ndarray, shape (ns, nt), optional) – initial guess (default is indep joint density)
  • numItermax (int, optional) – Max number of iterations
  • numInnerItermax (int, optional) – Max number of iterations of Sinkhorn
  • stopThr (float, optional) – Stop threshol on the relative variation (>0)
  • stopThr2 (float, optional) – Stop threshol on the absolute variation (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma (ndarray, shape (ns, nt)) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[5]
  1. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[7]Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.

See also

ot.optim.cg()
conditional gradient
ot.optim.line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=0.0001, alpha0=0.99)[source]

Armijo linesearch function that works with matrices

find an approximate minimum of f(xk+alpha*pk) that satifies the armijo conditions.

Parameters:
  • f (callable) – loss function
  • xk (ndarray) – initial position
  • pk (ndarray) – descent direction
  • gfk (ndarray) – gradient of f at xk
  • old_fval (float) – loss value at xk
  • args (tuple, optional) – arguments given to f
  • c1 (float, optional) – c1 const in armijo rule (>0)
  • alpha0 (float, optional) – initial step (>0)
Returns:

  • alpha (float) – step that satisfy armijo conditions
  • fc (int) – nb of function call
  • fa (float) – loss value at step alpha

ot.optim.solve_1d_linesearch_quad(a, b, c)[source]

For any convex or non-convex 1d quadratic function f, solve on [0,1] the following problem: .. math:

rgmin f(x)=a*x^{2}+b*x+c
Parameters:a,b,c (float) – The coefficients of the quadratic function
Returns:x – The optimal value which leads to the minimal cost
Return type:float
ot.optim.solve_linesearch(cost, G, deltaG, Mi, f_val, armijo=True, C1=None, C2=None, reg=None, Gc=None, constC=None, M=None)[source]

Solve the linesearch in the FW iterations :param cost: Cost in the FW for the linesearch :type cost: method :param G: The transport map at a given iteration of the FW :type G: ndarray, shape(ns,nt) :param deltaG: Difference between the optimal map found by linearization in the FW algorithm and the value at a given iteration :type deltaG: ndarray (ns,nt) :param Mi: Cost matrix of the linearized transport problem. Corresponds to the gradient of the cost :type Mi: ndarray (ns,nt) :param f_val: Value of the cost at G :type f_val: float :param armijo: If True the steps of the line-search is found via an armijo research. Else closed form is used.

If there is convergence issues use False.
Parameters:
  • C1 (ndarray (ns,ns), optional) – Structure matrix in the source domain. Only used and necessary when armijo=False
  • C2 (ndarray (nt,nt), optional) – Structure matrix in the target domain. Only used and necessary when armijo=False
  • reg (float, optional) – Regularization parameter. Only used and necessary when armijo=False
  • Gc (ndarray (ns,nt)) – Optimal map found by linearization in the FW algorithm. Only used and necessary when armijo=False
  • constC (ndarray (ns,nt)) – Constant for the gromov cost. See [24]. Only used and necessary when armijo=False
  • M (ndarray (ns,nt), optional) – Cost matrix between the features. Only used and necessary when armijo=False
Returns:

  • alpha (float) – The optimal step size of the FW
  • fc (int) – nb of function call. Useless here
  • f_val (float) – The value of the cost for the next iteration

References

[24]
Vayer Titouan, Chapel Laetitia, Flamary R{‘e}mi, Tavenard Romain
and Courty Nicolas

“Optimal Transport for structured data with application on graphs” International Conference on Machine Learning (ICML). 2019.

ot.da

Domain adaptation with optimal transport

class ot.da.BaseTransport[source]

Base class for OTDA objects

Notes

All estimators should specify all the parameters that can be set at the class level in their __init__ as explicit keyword arguments (no *args or **kwargs).

fit method should: - estimate a cost matrix and store it in a cost_ attribute - estimate a coupling matrix and store it in a coupling_ attribute - estimate distributions from source and target data and store them in mu_s and mu_t attributes - store Xs and Xt in attributes to be used later on in transform and inverse_transform methods

transform method should always get as input a Xs parameter inverse_transform method should always get as input a Xt parameter

fit(Xs=None, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self.

Return type:

object

fit_transform(Xs=None, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt) and transports source samples Xs onto target ones Xt

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

transp_Xs – The source samples samples.

Return type:

array-like, shape (n_source_samples, n_features)

inverse_transform(Xs=None, ys=None, Xt=None, yt=None, batch_size=128)[source]

Transports target samples Xt onto target samples Xs

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

  • batch_size (int, optional (default=128)) – The batch size for out of sample inverse transform
Returns:

transp_Xt – The transported target samples.

Return type:

array-like, shape (n_source_samples, n_features)

transform(Xs=None, ys=None, Xt=None, yt=None, batch_size=128)[source]

Transports source samples Xs onto target ones Xt

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

  • batch_size (int, optional (default=128)) – The batch size for out of sample inverse transform
Returns:

transp_Xs – The transport source samples.

Return type:

array-like, shape (n_source_samples, n_features)

class ot.da.EMDTransport(metric='sqeuclidean', norm=None, log=False, distribution_estimation=<function distribution_estimation_uniform>, out_of_sample_map='ferradans', limit_max=10, max_iter=100000)[source]

Domain Adapatation OT method based on Earth Mover’s Distance

Parameters:
  • metric (string, optional (default="sqeuclidean")) – The ground metric for the Wasserstein problem
  • norm (string, optional (default=None)) – If given, normalize the ground metric to avoid numerical errors that can occur with large metric values.
  • log (int, optional (default=False)) – Controls the logs of the optimization algorithm
  • distribution_estimation (callable, optional (defaults to the uniform)) – The kind of distribution estimation to employ
  • out_of_sample_map (string, optional (default="ferradans")) – The kind of out of sample mapping to apply to transport samples from a domain into another one. Currently the only possible option is “ferradans” which uses the method proposed in [6].
  • limit_max (float, optional (default=10)) – Controls the semi supervised mode. Transport between labeled source and target samples of different classes will exhibit an infinite cost (10 times the maximum value of the cost matrix)
  • max_iter (int, optional (default=100000)) – The maximum number of iterations before stopping the optimization algorithm if it has not converged.
coupling_

The optimal coupling

Type:array-like, shape (n_source_samples, n_target_samples)

References

[1]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
fit(Xs, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self.

Return type:

object

class ot.da.LinearTransport(reg=1e-08, bias=True, log=False, distribution_estimation=<function distribution_estimation_uniform>)[source]

OT linear operator between empirical distributions

The function estimates the optimal linear operator that aligns the two empirical distributions. This is equivalent to estimating the closed form mapping between two Gaussian distributions \(N(\mu_s,\Sigma_s)\) and \(N(\mu_t,\Sigma_t)\) as proposed in [14] and discussed in remark 2.29 in [15].

The linear operator from source to target \(M\)

\[M(x)=Ax+b\]

where :

\[A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2} \Sigma_s^{-1/2}\]
\[b=\mu_t-A\mu_s\]
Parameters:
  • reg (float,optional) – regularization added to the daigonals of convariances (>0)
  • bias (boolean, optional) – estimate bias b else b=0 (default:True)
  • log (bool, optional) – record log if True

References

[14]Knott, M. and Smith, C. S. “On the optimal mapping of distributions”, Journal of Optimization Theory and Applications Vol 43, 1984
[15]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.
fit(Xs=None, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self.

Return type:

object

inverse_transform(Xs=None, ys=None, Xt=None, yt=None, batch_size=128)[source]

Transports target samples Xt onto target samples Xs

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

  • batch_size (int, optional (default=128)) – The batch size for out of sample inverse transform
Returns:

transp_Xt – The transported target samples.

Return type:

array-like, shape (n_source_samples, n_features)

transform(Xs=None, ys=None, Xt=None, yt=None, batch_size=128)[source]

Transports source samples Xs onto target ones Xt

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

  • batch_size (int, optional (default=128)) – The batch size for out of sample inverse transform
Returns:

transp_Xs – The transport source samples.

Return type:

array-like, shape (n_source_samples, n_features)

class ot.da.MappingTransport(mu=1, eta=0.001, bias=False, metric='sqeuclidean', norm=None, kernel='linear', sigma=1, max_iter=100, tol=1e-05, max_inner_iter=10, inner_tol=1e-06, log=False, verbose=False, verbose2=False)[source]

MappingTransport: DA methods that aims at jointly estimating a optimal transport coupling and the associated mapping

Parameters:
  • mu (float, optional (default=1)) – Weight for the linear OT loss (>0)
  • eta (float, optional (default=0.001)) – Regularization term for the linear mapping L (>0)
  • bias (bool, optional (default=False)) – Estimate linear mapping with constant bias
  • metric (string, optional (default="sqeuclidean")) – The ground metric for the Wasserstein problem
  • norm (string, optional (default=None)) – If given, normalize the ground metric to avoid numerical errors that can occur with large metric values.
  • kernel (string, optional (default="linear")) – The kernel to use either linear or gaussian
  • sigma (float, optional (default=1)) – The gaussian kernel parameter
  • max_iter (int, optional (default=100)) – Max number of BCD iterations
  • tol (float, optional (default=1e-5)) – Stop threshold on relative loss decrease (>0)
  • max_inner_iter (int, optional (default=10)) – Max number of iterations (inner CG solver)
  • inner_tol (float, optional (default=1e-6)) – Stop threshold on error (inner CG solver) (>0)
  • log (bool, optional (default=False)) – record log if True
  • verbose (bool, optional (default=False)) – Print information along iterations
  • verbose2 (bool, optional (default=False)) – Print information along iterations
coupling_

The optimal coupling

Type:array-like, shape (n_source_samples, n_target_samples)
mapping_

(if bias) for kernel == linear The associated mapping array-like, shape (n_source_samples (+ 1), n_features) (if bias) for kernel == gaussian

Type:array-like, shape (n_features (+ 1), n_features)
log_

The dictionary of log, empty dic if parameter log is not True

Type:dictionary

References

[8]M. Perrot, N. Courty, R. Flamary, A. Habrard, “Mapping estimation for discrete optimal transport”, Neural Information Processing Systems (NIPS), 2016.
fit(Xs=None, ys=None, Xt=None, yt=None)[source]

Builds an optimal coupling and estimates the associated mapping from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self

Return type:

object

transform(Xs)[source]

Transports source samples Xs onto target ones Xt

Parameters:Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
Returns:transp_Xs – The transport source samples.
Return type:array-like, shape (n_source_samples, n_features)
ot.da.OT_mapping_linear(xs, xt, reg=1e-06, ws=None, wt=None, bias=True, log=False)[source]

return OT linear operator between samples

The function estimates the optimal linear operator that aligns the two empirical distributions. This is equivalent to estimating the closed form mapping between two Gaussian distributions \(N(\mu_s,\Sigma_s)\) and \(N(\mu_t,\Sigma_t)\) as proposed in [14] and discussed in remark 2.29 in [15].

The linear operator from source to target \(M\)

\[M(x)=Ax+b\]

where :

\[A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2} \Sigma_s^{-1/2}\]
\[b=\mu_t-A\mu_s\]
Parameters:
  • xs (np.ndarray (ns,d)) – samples in the source domain
  • xt (np.ndarray (nt,d)) – samples in the target domain
  • reg (float,optional) – regularization added to the diagonals of convariances (>0)
  • ws (np.ndarray (ns,1), optional) – weights for the source samples
  • wt (np.ndarray (ns,1), optional) – weights for the target samples
  • bias (boolean, optional) – estimate bias b else b=0 (default:True)
  • log (bool, optional) – record log if True
Returns:

  • A ((d x d) ndarray) – Linear operator
  • b ((1 x d) ndarray) – bias
  • log (dict) – log dictionary return only if log==True in parameters

References

[14]Knott, M. and Smith, C. S. “On the optimal mapping of distributions”, Journal of Optimization Theory and Applications Vol 43, 1984
[15]Peyré, G., & Cuturi, M. (2017). “Computational Optimal Transport”, 2018.
class ot.da.SinkhornL1l2Transport(reg_e=1.0, reg_cl=0.1, max_iter=10, max_inner_iter=200, tol=1e-08, verbose=False, log=False, metric='sqeuclidean', norm=None, distribution_estimation=<function distribution_estimation_uniform>, out_of_sample_map='ferradans', limit_max=10)[source]

Domain Adapatation OT method based on sinkhorn algorithm + l1l2 class regularization.

Parameters:
  • reg_e (float, optional (default=1)) – Entropic regularization parameter
  • reg_cl (float, optional (default=0.1)) – Class regularization parameter
  • max_iter (int, float, optional (default=10)) – The minimum number of iteration before stopping the optimization algorithm if no it has not converged
  • max_inner_iter (int, float, optional (default=200)) – The number of iteration in the inner loop
  • tol (float, optional (default=10e-9)) – Stop threshold on error (inner sinkhorn solver) (>0)
  • verbose (bool, optional (default=False)) – Controls the verbosity of the optimization algorithm
  • log (bool, optional (default=False)) – Controls the logs of the optimization algorithm
  • metric (string, optional (default="sqeuclidean")) – The ground metric for the Wasserstein problem
  • norm (string, optional (default=None)) – If given, normalize the ground metric to avoid numerical errors that can occur with large metric values.
  • distribution_estimation (callable, optional (defaults to the uniform)) – The kind of distribution estimation to employ
  • out_of_sample_map (string, optional (default="ferradans")) – The kind of out of sample mapping to apply to transport samples from a domain into another one. Currently the only possible option is “ferradans” which uses the method proposed in [6].
  • limit_max (float, optional (default=10)) – Controls the semi supervised mode. Transport between labeled source and target samples of different classes will exhibit an infinite cost (10 times the maximum value of the cost matrix)
coupling_

The optimal coupling

Type:array-like, shape (n_source_samples, n_target_samples)
log_

The dictionary of log, empty dic if parameter log is not True

Type:dictionary

References

[1]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[2]Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.
fit(Xs, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self.

Return type:

object

class ot.da.SinkhornLpl1Transport(reg_e=1.0, reg_cl=0.1, max_iter=10, max_inner_iter=200, log=False, tol=1e-08, verbose=False, metric='sqeuclidean', norm=None, distribution_estimation=<function distribution_estimation_uniform>, out_of_sample_map='ferradans', limit_max=inf)[source]

Domain Adapatation OT method based on sinkhorn algorithm + LpL1 class regularization.

Parameters:
  • reg_e (float, optional (default=1)) – Entropic regularization parameter
  • reg_cl (float, optional (default=0.1)) – Class regularization parameter
  • max_iter (int, float, optional (default=10)) – The minimum number of iteration before stopping the optimization algorithm if no it has not converged
  • max_inner_iter (int, float, optional (default=200)) – The number of iteration in the inner loop
  • log (bool, optional (default=False)) – Controls the logs of the optimization algorithm
  • tol (float, optional (default=10e-9)) – Stop threshold on error (inner sinkhorn solver) (>0)
  • verbose (bool, optional (default=False)) – Controls the verbosity of the optimization algorithm
  • metric (string, optional (default="sqeuclidean")) – The ground metric for the Wasserstein problem
  • norm (string, optional (default=None)) – If given, normalize the ground metric to avoid numerical errors that can occur with large metric values.
  • distribution_estimation (callable, optional (defaults to the uniform)) – The kind of distribution estimation to employ
  • out_of_sample_map (string, optional (default="ferradans")) – The kind of out of sample mapping to apply to transport samples from a domain into another one. Currently the only possible option is “ferradans” which uses the method proposed in [6].
  • limit_max (float, optional (defaul=np.infty)) – Controls the semi supervised mode. Transport between labeled source and target samples of different classes will exhibit a cost defined by limit_max.
coupling_

The optimal coupling

Type:array-like, shape (n_source_samples, n_target_samples)

References

[1]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[2]Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.
fit(Xs, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self.

Return type:

object

class ot.da.SinkhornTransport(reg_e=1.0, max_iter=1000, tol=1e-08, verbose=False, log=False, metric='sqeuclidean', norm=None, distribution_estimation=<function distribution_estimation_uniform>, out_of_sample_map='ferradans', limit_max=inf)[source]

Domain Adapatation OT method based on Sinkhorn Algorithm

Parameters:
  • reg_e (float, optional (default=1)) – Entropic regularization parameter
  • max_iter (int, float, optional (default=1000)) – The minimum number of iteration before stopping the optimization algorithm if no it has not converged
  • tol (float, optional (default=10e-9)) – The precision required to stop the optimization algorithm.
  • verbose (bool, optional (default=False)) – Controls the verbosity of the optimization algorithm
  • log (int, optional (default=False)) – Controls the logs of the optimization algorithm
  • metric (string, optional (default="sqeuclidean")) – The ground metric for the Wasserstein problem
  • norm (string, optional (default=None)) – If given, normalize the ground metric to avoid numerical errors that can occur with large metric values.
  • distribution_estimation (callable, optional (defaults to the uniform)) – The kind of distribution estimation to employ
  • out_of_sample_map (string, optional (default="ferradans")) – The kind of out of sample mapping to apply to transport samples from a domain into another one. Currently the only possible option is “ferradans” which uses the method proposed in [6].
  • limit_max (float, optional (defaul=np.infty)) – Controls the semi supervised mode. Transport between labeled source and target samples of different classes will exhibit an cost defined by this variable
coupling_

The optimal coupling

Type:array-like, shape (n_source_samples, n_target_samples)
log_

The dictionary of log, empty dic if parameter log is not True

Type:dictionary

References

[1]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[2]M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
fit(Xs=None, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self.

Return type:

object

class ot.da.UnbalancedSinkhornTransport(reg_e=1.0, reg_m=0.1, method='sinkhorn', max_iter=10, tol=1e-09, verbose=False, log=False, metric='sqeuclidean', norm=None, distribution_estimation=<function distribution_estimation_uniform>, out_of_sample_map='ferradans', limit_max=10)[source]

Domain Adapatation unbalanced OT method based on sinkhorn algorithm

Parameters:
  • reg_e (float, optional (default=1)) – Entropic regularization parameter
  • reg_m (float, optional (default=0.1)) – Mass regularization parameter
  • method (str) – method used for the solver either ‘sinkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_epsilon_scaling’, see those function for specific parameters
  • max_iter (int, float, optional (default=10)) – The minimum number of iteration before stopping the optimization algorithm if no it has not converged
  • tol (float, optional (default=10e-9)) – Stop threshold on error (inner sinkhorn solver) (>0)
  • verbose (bool, optional (default=False)) – Controls the verbosity of the optimization algorithm
  • log (bool, optional (default=False)) – Controls the logs of the optimization algorithm
  • metric (string, optional (default="sqeuclidean")) – The ground metric for the Wasserstein problem
  • norm (string, optional (default=None)) – If given, normalize the ground metric to avoid numerical errors that can occur with large metric values.
  • distribution_estimation (callable, optional (defaults to the uniform)) – The kind of distribution estimation to employ
  • out_of_sample_map (string, optional (default="ferradans")) – The kind of out of sample mapping to apply to transport samples from a domain into another one. Currently the only possible option is “ferradans” which uses the method proposed in [6].
  • limit_max (float, optional (default=10)) – Controls the semi supervised mode. Transport between labeled source and target samples of different classes will exhibit an infinite cost (10 times the maximum value of the cost matrix)
coupling_

The optimal coupling

Type:array-like, shape (n_source_samples, n_target_samples)
log_

The dictionary of log, empty dic if parameter log is not True

Type:dictionary

References

[1]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016).

Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.

fit(Xs, ys=None, Xt=None, yt=None)[source]

Build a coupling matrix from source and target sets of samples (Xs, ys) and (Xt, yt)

Parameters:
  • Xs (array-like, shape (n_source_samples, n_features)) – The training input samples.
  • ys (array-like, shape (n_source_samples,)) – The class labels
  • Xt (array-like, shape (n_target_samples, n_features)) – The training input samples.
  • yt (array-like, shape (n_target_samples,)) –

    The class labels. If some target samples are unlabeled, fill the yt’s elements with -1.

    Warning: Note that, due to this convention -1 cannot be used as a class label

Returns:

self – Returns self.

Return type:

object

ot.da.distribution_estimation_uniform(X)[source]

estimates a uniform distribution from an array of samples X

Parameters:X (array-like, shape (n_samples, n_features)) – The array of samples
Returns:mu – The uniform distribution estimated from X
Return type:array-like, shape (n_samples,)
ot.da.joint_OT_mapping_kernel(xs, xt, mu=1, eta=0.001, kerneltype='gaussian', sigma=1, bias=False, verbose=False, verbose2=False, numItermax=100, numInnerItermax=10, stopInnerThr=1e-06, stopThr=1e-05, log=False, **kwargs)[source]

Joint OT and nonlinear mapping estimation with kernels as proposed in [8]

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\min_{\gamma,L\in\mathcal{H}}\quad \|L(X_s) - n_s\gamma X_t\|^2_F + \mu<\gamma,M>_F + \eta \|L\|^2_\mathcal{H}\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) squared euclidean cost matrix between samples in Xs and Xt (scaled by ns)
  • \(L\) is a ns x d linear operator on a kernel matrix that approximates the barycentric mapping
  • a and b are uniform source and target weights

The problem consist in solving jointly an optimal transport matrix \(\gamma\) and the nonlinear mapping that fits the barycentric mapping \(n_s\gamma X_t\).

One can also estimate a mapping with constant bias (see supplementary material of [8]) using the bias optional argument.

The algorithm used for solving the problem is the block coordinate descent that alternates between updates of G (using conditionnal gradient) and the update of L using a classical kernel least square solver.

Parameters:
  • xs (np.ndarray (ns,d)) – samples in the source domain
  • xt (np.ndarray (nt,d)) – samples in the target domain
  • mu (float,optional) – Weight for the linear OT loss (>0)
  • eta (float, optional) – Regularization term for the linear mapping L (>0)
  • kerneltype (str,optional) – kernel used by calling function ot.utils.kernel (gaussian by default)
  • sigma (float, optional) – Gaussian kernel bandwidth.
  • bias (bool,optional) – Estimate linear mapping with constant bias
  • verbose (bool, optional) – Print information along iterations
  • verbose2 (bool, optional) – Print information along iterations
  • numItermax (int, optional) – Max number of BCD iterations
  • numInnerItermax (int, optional) – Max number of iterations (inner CG solver)
  • stopInnerThr (float, optional) – Stop threshold on error (inner CG solver) (>0)
  • stopThr (float, optional) – Stop threshold on relative loss decrease (>0)
  • log (bool, optional) – record log if True
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • L ((ns x d) ndarray) – Nonlinear mapping matrix (ns+1 x d if bias)
  • log (dict) – log dictionary return only if log==True in parameters

References

[8]M. Perrot, N. Courty, R. Flamary, A. Habrard, “Mapping estimation for discrete optimal transport”, Neural Information Processing Systems (NIPS), 2016.

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.da.joint_OT_mapping_linear(xs, xt, mu=1, eta=0.001, bias=False, verbose=False, verbose2=False, numItermax=100, numInnerItermax=10, stopInnerThr=1e-06, stopThr=1e-05, log=False, **kwargs)[source]

Joint OT and linear mapping estimation as proposed in [8]

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\min_{\gamma,L}\quad \|L(X_s) -n_s\gamma X_t\|^2_F + \mu<\gamma,M>_F + \eta \|L -I\|^2_F\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) squared euclidean cost matrix between samples in
    Xs and Xt (scaled by ns)
  • \(L\) is a dxd linear operator that approximates the barycentric mapping
  • \(I\) is the identity matrix (neutral linear mapping)
  • a and b are uniform source and target weights

The problem consist in solving jointly an optimal transport matrix \(\gamma\) and a linear mapping that fits the barycentric mapping \(n_s\gamma X_t\).

One can also estimate a mapping with constant bias (see supplementary material of [8]) using the bias optional argument.

The algorithm used for solving the problem is the block coordinate descent that alternates between updates of G (using conditionnal gradient) and the update of L using a classical least square solver.

Parameters:
  • xs (np.ndarray (ns,d)) – samples in the source domain
  • xt (np.ndarray (nt,d)) – samples in the target domain
  • mu (float,optional) – Weight for the linear OT loss (>0)
  • eta (float, optional) – Regularization term for the linear mapping L (>0)
  • bias (bool,optional) – Estimate linear mapping with constant bias
  • numItermax (int, optional) – Max number of BCD iterations
  • stopThr (float, optional) – Stop threshold on relative loss decrease (>0)
  • numInnerItermax (int, optional) – Max number of iterations (inner CG solver)
  • stopInnerThr (float, optional) – Stop threshold on error (inner CG solver) (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • L ((d x d) ndarray) – Linear mapping matrix (d+1 x d if bias)
  • log (dict) – log dictionary return only if log==True in parameters

References

[8]M. Perrot, N. Courty, R. Flamary, A. Habrard, “Mapping estimation for discrete optimal transport”, Neural Information Processing Systems (NIPS), 2016.

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.da.sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-09, verbose=False, log=False)[source]

Solve the entropic regularization optimal transport problem with group lasso regularization

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+ \eta \Omega_g(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega_e\) is the entropic regularization term \(\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(\Omega_g\) is the group lasso regulaization term \(\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2\) where \(\mathcal{I}_c\) are the index of samples from class c in the source domain.
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • labels_a (np.ndarray (ns,)) – labels of samples in the source domain
  • b (np.ndarray (nt,)) – samples in the target domain
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term for entropic regularization >0
  • eta (float, optional) – Regularization term for group lasso regularization >0
  • numItermax (int, optional) – Max number of iterations
  • numInnerItermax (int, optional) – Max number of iterations (inner sinkhorn solver)
  • stopInnerThr (float, optional) – Stop threshold on error (inner sinkhorn solver) (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[5]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[7]Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.

See also

ot.optim.gcg()
Generalized conditional gradient for OT problems
ot.da.sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-09, verbose=False, log=False)[source]

Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma) + \eta \Omega_g(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega_e\) is the entropic regularization term \(\Omega_e (\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(\Omega_g\) is the group lasso regularization term \(\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1\) where \(\mathcal{I}_c\) are the index of samples from class c in the source domain.
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the generalized conditional gradient as proposed in [5]_ [7]_

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • labels_a (np.ndarray (ns,)) – labels of samples in the source domain
  • b (np.ndarray (nt,)) – samples weights in the target domain
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term for entropic regularization >0
  • eta (float, optional) – Regularization term for group lasso regularization >0
  • numItermax (int, optional) – Max number of iterations
  • numInnerItermax (int, optional) – Max number of iterations (inner sinkhorn solver)
  • stopInnerThr (float, optional) – Stop threshold on error (inner sinkhorn solver) (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[5]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[7]Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.

See also

ot.lp.emd()
Unregularized OT
ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT

ot.gpu

This module provides GPU implementation for several OT solvers and utility functions. The GPU backend in handled by cupy.

Warning

Note that by default the module is not import in ot. In order to use it you need to explicitely import ot.gpu .

By default, the functions in this module accept and return numpy arrays in order to proide drop-in replacement for the other POT function but the transfer between CPU en GPU comes with a significant overhead.

In order to get the best performances, we recommend to give only cupy arrays to the functions and desactivate the conversion to numpy of the result of the function with parameter to_numpy=False.

ot.gpu.dist(x1, x2=None, metric='sqeuclidean', to_numpy=True)[source]

Compute distance between samples in x1 and x2 on gpu

Parameters:
  • x1 (np.array (n1,d)) – matrix with n1 samples of size d
  • x2 (np.array (n2,d), optional) – matrix with n2 samples of size d (if None then x2=x1)
  • metric (str) – Metric from ‘sqeuclidean’, ‘euclidean’,
Returns:

M – distance matrix computed with given metric

Return type:

np.array (n1,n2)

ot.gpu.sinkhorn(a, b, M, reg, numItermax=1000, stopThr=1e-09, verbose=False, log=False, to_numpy=True, **kwargs)

Solve the entropic regularization optimal transport on GPU

If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead.

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • b (np.ndarray (nt,) or np.ndarray (nt,nbb)) – samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log)
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term >0
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
  • to_numpy (boolean, optional (default True)) – If true convert back the GPU array result to numpy format.
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[2]
  1. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.gpu.sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-09, verbose=False, log=False, to_numpy=True)[source]

Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization on GPU

If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead.

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma) + \eta \Omega_g(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega_e\) is the entropic regularization term
    \(\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • \(\Omega_g\) is the group lasso regulaization term \(\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1\) where \(\mathcal{I}_c\) are the index of samples from class c in the source domain.
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • labels_a (np.ndarray (ns,)) – labels of samples in the source domain
  • b (np.ndarray (nt,)) – samples weights in the target domain
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term for entropic regularization >0
  • eta (float, optional) – Regularization term for group lasso regularization >0
  • numItermax (int, optional) – Max number of iterations
  • numInnerItermax (int, optional) – Max number of iterations (inner sinkhorn solver)
  • stopInnerThr (float, optional) – Stop threshold on error (inner sinkhorn solver) (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
  • to_numpy (boolean, optional (default True)) – If true convert back the GPU array result to numpy format.
Returns:

  • gamma ((ns x nt) ndarray) – Optimal transportation matrix for the given parameters
  • log (dict) – log dictionary return only if log==True in parameters

References

[5]N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, “Optimal Transport for Domain Adaptation,” in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1
[7]Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567.

See also

ot.lp.emd()
Unregularized OT
ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT
ot.gpu.to_gpu(*args)[source]

Upload numpy arrays to GPU and return them

ot.gpu.to_np(*args)[source]

convert GPU arras to numpy and return them

ot.dr

Dimension reduction with optimal transport

Warning

Note that by default the module is not import in ot. In order to use it you need to explicitely import ot.dr

ot.dr.dist(x1, x2)[source]

Compute squared euclidean distance between samples (autograd)

ot.dr.fda(X, y, p=2, reg=1e-16)[source]

Fisher Discriminant Analysis

Parameters:
  • X (ndarray, shape (n, d)) – Training samples.
  • y (ndarray, shape (n,)) – Labels for training samples.
  • p (int, optional) – Size of dimensionnality reduction.
  • reg (float, optional) – Regularization term >0 (ridge regularization)
Returns:

  • P (ndarray, shape (d, p)) – Optimal transportation matrix for the given parameters
  • proj (callable) – projection function including mean centering

ot.dr.sinkhorn(w1, w2, M, reg, k)[source]

Sinkhorn algorithm with fixed number of iteration (autograd)

ot.dr.split_classes(X, y)[source]

split samples in X by classes in y

ot.dr.wda(X, y, p=2, reg=1, k=10, solver=None, maxiter=100, verbose=0, P0=None)[source]

Wasserstein Discriminant Analysis [11]

The function solves the following optimization problem:

\[P = \text{arg}\min_P \frac{\sum_i W(PX^i,PX^i)}{\sum_{i,j\neq i} W(PX^i,PX^j)}\]

where :

  • \(P\) is a linear projection operator in the Stiefel(p,d) manifold
  • \(W\) is entropic regularized Wasserstein distances
  • \(X^i\) are samples in the dataset corresponding to class i
Parameters:
  • X (ndarray, shape (n, d)) – Training samples.
  • y (ndarray, shape (n,)) – Labels for training samples.
  • p (int, optional) – Size of dimensionnality reduction.
  • reg (float, optional) – Regularization term >0 (entropic regularization)
  • solver (None | str, optional) – None for steepest descent or ‘TrustRegions’ for trust regions algorithm else should be a pymanopt.solvers
  • P0 (ndarray, shape (d, p)) – Initial starting point for projection.
  • verbose (int, optional) – Print information along iterations.
Returns:

  • P (ndarray, shape (d, p)) – Optimal transportation matrix for the given parameters
  • proj (callable) – Projection function including mean centering.

References

[11]Flamary, R., Cuturi, M., Courty, N., & Rakotomamonjy, A. (2016). Wasserstein Discriminant Analysis. arXiv preprint arXiv:1608.08063.

ot.utils

Various useful functions

class ot.utils.BaseEstimator[source]

Base class for most objects in POT

Code adapted from sklearn BaseEstimator class

Notes

All estimators should specify all the parameters that can be set at the class level in their __init__ as explicit keyword arguments (no *args or **kwargs).

get_params(deep=True)[source]

Get parameters for this estimator.

Parameters:deep (bool, optional) – If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns:params – Parameter names mapped to their values.
Return type:mapping of string to any
set_params(**params)[source]

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Returns:
Return type:self
exception ot.utils.UndefinedParameter[source]

Aim at raising an Exception when a undefined parameter is called

ot.utils.check_params(**kwargs)[source]

check_params: check whether some parameters are missing

ot.utils.check_random_state(seed)[source]

Turn seed into a np.random.RandomState instance

Parameters:seed (None | int | instance of RandomState) – If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError.
ot.utils.clean_zeros(a, b, M)[source]

Remove all components with zeros weights in a and b

ot.utils.cost_normalization(C, norm=None)[source]

Apply normalization to the loss matrix

Parameters:
  • C (ndarray, shape (n1, n2)) – The cost matrix to normalize.
  • norm (str) – Type of normalization from ‘median’, ‘max’, ‘log’, ‘loglog’. Any other value do not normalize.
Returns:

C – The input cost matrix normalized according to given norm.

Return type:

ndarray, shape (n1, n2)

class ot.utils.deprecated(extra='')[source]

Decorator to mark a function or class as deprecated.

deprecated class from scikit-learn package https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/deprecation.py Issue a warning when the function is called/the class is instantiated and adds a warning to the docstring. The optional extra argument will be appended to the deprecation message and the docstring. Note: to use this with the default value for extra, put in an empty of parentheses: >>> from ot.deprecation import deprecated # doctest: +SKIP >>> @deprecated() # doctest: +SKIP … def some_function(): pass # doctest: +SKIP

Parameters:extra (str) – To be added to the deprecation messages.
ot.utils.dist(x1, x2=None, metric='sqeuclidean')[source]

Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist

Parameters:
  • x1 (ndarray, shape (n1,d)) – matrix with n1 samples of size d
  • x2 (array, shape (n2,d), optional) – matrix with n2 samples of size d (if None then x2=x1)
  • metric (str | callable, optional) – Name of the metric to be computed (full list in the doc of scipy), If a string, the distance function can be ‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘cityblock’, ‘correlation’, ‘cosine’, ‘dice’, ‘euclidean’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘matching’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘wminkowski’, ‘yule’.
Returns:

M – distance matrix computed with given metric

Return type:

np.array (n1,n2)

ot.utils.dist0(n, method='lin_square')[source]

Compute standard cost matrices of size (n, n) for OT problems

Parameters:
  • n (int) – Size of the cost matrix.
  • method (str, optional) –

    Type of loss matrix chosen from:

    • ’lin_square’ : linear sampling between 0 and n-1, quadratic loss
Returns:

M – Distance matrix computed with given metric.

Return type:

ndarray, shape (n1,n2)

ot.utils.dots(*args)[source]

dots function for multiple matrix multiply

ot.utils.euclidean_distances(X, Y, squared=False)[source]

Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. :param X: :type X: {array-like}, shape (n_samples_1, n_features) :param Y: :type Y: {array-like}, shape (n_samples_2, n_features) :param squared: Return squared Euclidean distances. :type squared: boolean, optional

Returns:distances
Return type:{array}, shape (n_samples_1, n_samples_2)
ot.utils.fun(f, q_in, q_out)[source]

Utility function for parmap with no serializing problems

ot.utils.kernel(x1, x2, method='gaussian', sigma=1, **kwargs)[source]

Compute kernel matrix

ot.utils.parmap(f, X, nprocs=4)[source]

paralell map for multiprocessing (only map on windows)

ot.utils.tic()[source]

Python implementation of Matlab tic() function

ot.utils.toc(message='Elapsed time : {} s')[source]

Python implementation of Matlab toc() function

ot.utils.toq()[source]

Python implementation of Julia toc() function

ot.utils.unif(n)[source]

return a uniform histogram of length n (simplex)

Parameters:n (int) – number of bins in the histogram
Returns:h – histogram of length n such that h_i=1/n for all i
Return type:np.array (n,)

ot.datasets

Simple example datasets for OT

ot.datasets.make_1D_gauss(n, m, s)[source]

return a 1D histogram for a gaussian distribution (n bins, mean m and std s)

Parameters:
  • n (int) – number of bins in the histogram
  • m (float) – mean value of the gaussian distribution
  • s (float) – standard deviaton of the gaussian distribution
Returns:

h – 1D histogram for a gaussian distribution

Return type:

ndarray (n,)

ot.datasets.make_2D_samples_gauss(n, m, sigma, random_state=None)[source]

Return n samples drawn from 2D gaussian N(m,sigma)

Parameters:
  • n (int) – number of samples to make
  • m (ndarray, shape (2,)) – mean value of the gaussian distribution
  • sigma (ndarray, shape (2, 2)) – covariance matrix of the gaussian distribution
  • random_state (int, RandomState instance or None, optional (default=None)) – If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
Returns:

X – n samples drawn from N(m, sigma).

Return type:

ndarray, shape (n, 2)

ot.datasets.make_data_classif(dataset, n, nz=0.5, theta=0, random_state=None, **kwargs)[source]

Dataset generation for classification problems

Parameters:
  • dataset (str) – type of classification problem (see code)
  • n (int) – number of training samples
  • nz (float) – noise level (>0)
  • random_state (int, RandomState instance or None, optional (default=None)) – If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
Returns:

  • X (ndarray, shape (n, d)) – n observation of size d
  • y (ndarray, shape (n,)) – labels of the samples.

ot.plot

Functions for plotting OT matrices

Warning

Note that by default the module is not import in ot. In order to use it you need to explicitely import ot.plot

ot.plot.plot1D_mat(a, b, M, title='')[source]

Plot matrix M with the source and target 1D distribution

Creates a subplot with the source distribution a on the left and target distribution b on the tot. The matrix M is shown in between.

Parameters:
  • a (ndarray, shape (na,)) – Source distribution
  • b (ndarray, shape (nb,)) – Target distribution
  • M (ndarray, shape (na, nb)) – Matrix to plot
ot.plot.plot2D_samples_mat(xs, xt, G, thr=1e-08, **kwargs)[source]

Plot matrix M in 2D with lines using alpha values

Plot lines between source and target 2D samples with a color proportional to the value of the matrix G between samples.

Parameters:
  • xs (ndarray, shape (ns,2)) – Source samples positions
  • b (ndarray, shape (nt,2)) – Target samples positions
  • G (ndarray, shape (na,nb)) – OT matrix
  • thr (float, optional) – threshold above which the line is drawn
  • **kwargs (dict) – paameters given to the plot functions (default color is black if nothing given)

ot.stochastic

Stochastic solvers for regularized OT.

ot.stochastic.averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None)[source]

Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma \geq 0\end{aligned}\end{align} \]

Where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega\) is the entropic regularization term with \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the ASGD algorithm as proposed in [18]_ [alg.2]

Parameters:
  • b (ndarray, shape (nt,)) – target measure
  • M (ndarray, shape (ns, nt)) – cost matrix
  • reg (float) – Regularization term > 0
  • numItermax (int) – Number of iteration.
  • lr (float) – Learning rate.
Returns:

ave_v – dual variable

Return type:

ndarray, shape (nt,)

Examples

>>> import ot
>>> np.random.seed(0)
>>> n_source = 7
>>> n_target = 4
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> X_source = np.random.randn(n_source, 2)
>>> Y_target = np.random.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> ot.stochastic.solve_semi_dual_entropic(a, b, M, reg=1, method="ASGD", numItermax=300000)
array([[2.53942342e-02, 9.98640673e-02, 1.75945647e-02, 4.27664307e-06],
       [1.21556999e-01, 1.26350515e-02, 1.30491795e-03, 7.36017394e-03],
       [3.54070702e-03, 7.63581358e-02, 6.29581672e-02, 1.32812798e-07],
       [2.60578198e-02, 3.35916645e-02, 8.28023223e-02, 4.05336238e-04],
       [9.86808864e-03, 7.59774324e-04, 1.08702729e-02, 1.21359007e-01],
       [2.17218856e-02, 9.12931802e-04, 1.87962526e-03, 1.18342700e-01],
       [4.14237512e-02, 2.67487857e-02, 7.23016955e-02, 2.38291052e-03]])

References

[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
ot.stochastic.batch_grad_dual(a, b, M, reg, alpha, beta, batch_size, batch_alpha, batch_beta)[source]

Computes the partial gradient of the dual optimal transport problem.

For each (i,j) in a batch of coordinates, the partial gradients are :

\[ \begin{align}\begin{aligned}\partial_{u_i} F = u_i * b_s/l_{v} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j\\\partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j\end{aligned}\end{align} \]

Where :

  • M is the (ns,nt) metric cost matrix
  • u, v are dual variables in R^ixR^J
  • reg is the regularization term
  • \(B_u\) and \(B_v\) are lists of index
  • \(b_s\) is the size of the batchs \(B_u\) and \(B_v\)
  • \(l_u\) and \(l_v\) are the lenghts of \(B_u\) and \(B_v\)
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the dual problem is the SGD algorithm as proposed in [19]_ [alg.1]

Parameters:
  • a (ndarray, shape (ns,)) – source measure
  • b (ndarray, shape (nt,)) – target measure
  • M (ndarray, shape (ns, nt)) – cost matrix
  • reg (float) – Regularization term > 0
  • alpha (ndarray, shape (ns,)) – dual variable
  • beta (ndarray, shape (nt,)) – dual variable
  • batch_size (int) – size of the batch
  • batch_alpha (ndarray, shape (bs,)) – batch of index of alpha
  • batch_beta (ndarray, shape (bs,)) – batch of index of beta
Returns:

grad – partial grad F

Return type:

ndarray, shape (ns,)

Examples

>>> import ot
>>> np.random.seed(0)
>>> n_source = 7
>>> n_target = 4
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> X_source = np.random.randn(n_source, 2)
>>> Y_target = np.random.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = ot.stochastic.solve_dual_entropic(a, b, M, reg=1, batch_size=3, numItermax=30000, lr=0.1, log=True)
>>> log['alpha']
array([0.71759102, 1.57057384, 0.85576566, 0.1208211 , 0.59190466,
       1.197148  , 0.17805133])
>>> log['beta']
array([0.49741367, 0.57478564, 1.40075528, 2.75890102])
>>> sgd_dual_pi
array([[2.09730063e-02, 8.38169324e-02, 7.50365455e-03, 8.72731415e-09],
       [5.58432437e-03, 5.89881299e-04, 3.09558411e-05, 8.35469849e-07],
       [3.26489515e-03, 7.15536035e-02, 2.99778211e-02, 3.02601593e-10],
       [4.05390622e-02, 5.31085068e-02, 6.65191787e-02, 1.55812785e-06],
       [7.82299812e-02, 6.12099102e-03, 4.44989098e-02, 2.37719187e-03],
       [5.06266486e-02, 2.16230494e-03, 2.26215141e-03, 6.81514609e-04],
       [6.06713990e-02, 3.98139808e-02, 5.46829338e-02, 8.62371424e-06]])

References

[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
ot.stochastic.c_transform_entropic(b, M, reg, beta)[source]

The goal is to recover u from the c-transform.

The function computes the c_transform of a dual variable from the other dual variable:

\[u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j\]

Where :

  • M is the (ns,nt) metric cost matrix
  • u, v are dual variables in R^IxR^J
  • reg is the regularization term

It is used to recover an optimal u from optimal v solving the semi dual problem, see Proposition 2.1 of [18]_

Parameters:
  • b (ndarray, shape (nt,)) – Target measure
  • M (ndarray, shape (ns, nt)) – Cost matrix
  • reg (float) – Regularization term > 0
  • v (ndarray, shape (nt,)) – Dual variable.
Returns:

u – Dual variable.

Return type:

ndarray, shape (ns,)

Examples

>>> import ot
>>> np.random.seed(0)
>>> n_source = 7
>>> n_target = 4
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> X_source = np.random.randn(n_source, 2)
>>> Y_target = np.random.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> ot.stochastic.solve_semi_dual_entropic(a, b, M, reg=1, method="ASGD", numItermax=300000)
array([[2.53942342e-02, 9.98640673e-02, 1.75945647e-02, 4.27664307e-06],
       [1.21556999e-01, 1.26350515e-02, 1.30491795e-03, 7.36017394e-03],
       [3.54070702e-03, 7.63581358e-02, 6.29581672e-02, 1.32812798e-07],
       [2.60578198e-02, 3.35916645e-02, 8.28023223e-02, 4.05336238e-04],
       [9.86808864e-03, 7.59774324e-04, 1.08702729e-02, 1.21359007e-01],
       [2.17218856e-02, 9.12931802e-04, 1.87962526e-03, 1.18342700e-01],
       [4.14237512e-02, 2.67487857e-02, 7.23016955e-02, 2.38291052e-03]])

References

[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
ot.stochastic.coordinate_grad_semi_dual(b, M, reg, beta, i)[source]

Compute the coordinate gradient update for regularized discrete distributions for (i, :)

The function computes the gradient of the semi dual problem:

\[\max_v \sum_i (\sum_j v_j * b_j - reg * log(\sum_j exp((v_j - M_{i,j})/reg) * b_j)) * a_i\]

Where :

  • M is the (ns,nt) metric cost matrix
  • v is a dual variable in R^J
  • reg is the regularization term
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the ASGD & SAG algorithms as proposed in [18]_ [alg.1 & alg.2]

Parameters:
  • b (ndarray, shape (nt,)) – Target measure.
  • M (ndarray, shape (ns, nt)) – Cost matrix.
  • reg (float) – Regularization term > 0.
  • v (ndarray, shape (nt,)) – Dual variable.
  • i (int) – Picked number i.
Returns:

coordinate gradient

Return type:

ndarray, shape (nt,)

Examples

>>> import ot
>>> np.random.seed(0)
>>> n_source = 7
>>> n_target = 4
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> X_source = np.random.randn(n_source, 2)
>>> Y_target = np.random.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> ot.stochastic.solve_semi_dual_entropic(a, b, M, reg=1, method="ASGD", numItermax=300000)
array([[2.53942342e-02, 9.98640673e-02, 1.75945647e-02, 4.27664307e-06],
       [1.21556999e-01, 1.26350515e-02, 1.30491795e-03, 7.36017394e-03],
       [3.54070702e-03, 7.63581358e-02, 6.29581672e-02, 1.32812798e-07],
       [2.60578198e-02, 3.35916645e-02, 8.28023223e-02, 4.05336238e-04],
       [9.86808864e-03, 7.59774324e-04, 1.08702729e-02, 1.21359007e-01],
       [2.17218856e-02, 9.12931802e-04, 1.87962526e-03, 1.18342700e-01],
       [4.14237512e-02, 2.67487857e-02, 7.23016955e-02, 2.38291052e-03]])

References

[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
ot.stochastic.sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None)[source]
Compute the SAG algorithm to solve the regularized discrete measures
optimal transport max problem

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1 = b\\ \gamma \geq 0\end{aligned}\end{align} \]

Where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega\) is the entropic regularization term with \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the SAG algorithm as proposed in [18]_ [alg.1]

Parameters:
  • a (ndarray, shape (ns,),) – Source measure.
  • b (ndarray, shape (nt,),) – Target measure.
  • M (ndarray, shape (ns, nt),) – Cost matrix.
  • reg (float) – Regularization term > 0
  • numItermax (int) – Number of iteration.
  • lr (float) – Learning rate.
Returns:

v – Dual variable.

Return type:

ndarray, shape (nt,)

Examples

>>> import ot
>>> np.random.seed(0)
>>> n_source = 7
>>> n_target = 4
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> X_source = np.random.randn(n_source, 2)
>>> Y_target = np.random.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> ot.stochastic.solve_semi_dual_entropic(a, b, M, reg=1, method="ASGD", numItermax=300000)
array([[2.53942342e-02, 9.98640673e-02, 1.75945647e-02, 4.27664307e-06],
       [1.21556999e-01, 1.26350515e-02, 1.30491795e-03, 7.36017394e-03],
       [3.54070702e-03, 7.63581358e-02, 6.29581672e-02, 1.32812798e-07],
       [2.60578198e-02, 3.35916645e-02, 8.28023223e-02, 4.05336238e-04],
       [9.86808864e-03, 7.59774324e-04, 1.08702729e-02, 1.21359007e-01],
       [2.17218856e-02, 9.12931802e-04, 1.87962526e-03, 1.18342700e-01],
       [4.14237512e-02, 2.67487857e-02, 7.23016955e-02, 2.38291052e-03]])

References

[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.
ot.stochastic.sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr)[source]
Compute the sgd algorithm to solve the regularized discrete measures
optimal transport dual problem

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma \geq 0\end{aligned}\end{align} \]

Where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega\) is the entropic regularization term with \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (sum to 1)
Parameters:
  • a (ndarray, shape (ns,)) – source measure
  • b (ndarray, shape (nt,)) – target measure
  • M (ndarray, shape (ns, nt)) – cost matrix
  • reg (float) – Regularization term > 0
  • batch_size (int) – size of the batch
  • numItermax (int) – number of iteration
  • lr (float) – learning rate
Returns:

  • alpha (ndarray, shape (ns,)) – dual variable
  • beta (ndarray, shape (nt,)) – dual variable

Examples

>>> import ot
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = ot.stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log)
>>> log['alpha']
array([0.64171798, 1.27932201, 0.78132257, 0.15638935, 0.54888354,
       1.03663469, 0.20595781])
>>> log['beta']
array([0.51207194, 0.58033189, 1.28922676, 2.26859736])
>>> sgd_dual_pi
array([[1.97276541e-02, 7.81248547e-02, 6.22136048e-03, 4.95442423e-09],
       [4.23494310e-03, 4.43286263e-04, 2.06927079e-05, 3.82389139e-07],
       [3.07542414e-03, 6.67897769e-02, 2.48904999e-02, 1.72030247e-10],
       [4.26271990e-02, 5.53375455e-02, 6.16535024e-02, 9.88812650e-07],
       [7.60423265e-02, 5.89585256e-03, 3.81267087e-02, 1.39458256e-03],
       [4.37557504e-02, 1.85189176e-03, 1.72335760e-03, 3.55491279e-04],
       [6.33096109e-02, 4.11683954e-02, 5.02962051e-02, 5.43097516e-06]])

References

[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
ot.stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1, log=False)[source]
Compute the transportation matrix to solve the regularized discrete measures
optimal transport dual problem

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma \geq 0\end{aligned}\end{align} \]

Where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (sum to 1)
Parameters:
  • a (ndarray, shape (ns,)) – source measure
  • b (ndarray, shape (nt,)) – target measure
  • M (ndarray, shape (ns, nt)) – cost matrix
  • reg (float) – Regularization term > 0
  • batch_size (int) – size of the batch
  • numItermax (int) – number of iteration
  • lr (float) – learning rate
  • log (bool, optional) – record log if True
Returns:

  • pi (ndarray, shape (ns, nt)) – transportation matrix
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 20000
>>> lr = 0.1
>>> batch_size = 3
>>> log = True
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> rng = np.random.RandomState(0)
>>> X_source = rng.randn(n_source, 2)
>>> Y_target = rng.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> sgd_dual_pi, log = ot.stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log)
>>> log['alpha']
array([0.64057733, 1.2683513 , 0.75610161, 0.16024284, 0.54926534,
       1.0514201 , 0.19958936])
>>> log['beta']
array([0.51372571, 0.58843489, 1.27993921, 2.24344807])
>>> sgd_dual_pi
array([[1.97377795e-02, 7.86706853e-02, 6.15682001e-03, 4.82586997e-09],
       [4.19566963e-03, 4.42016865e-04, 2.02777272e-05, 3.68823708e-07],
       [3.00379244e-03, 6.56562018e-02, 2.40462171e-02, 1.63579656e-10],
       [4.28626062e-02, 5.60031599e-02, 6.13193826e-02, 9.67977735e-07],
       [7.61972739e-02, 5.94609051e-03, 3.77886693e-02, 1.36046648e-03],
       [4.44810042e-02, 1.89476742e-03, 1.73285847e-03, 3.51826036e-04],
       [6.30118293e-02, 4.12398660e-02, 4.95148998e-02, 5.26247246e-06]])

References

[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
ot.stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None, log=False)[source]
Compute the transportation matrix to solve the regularized discrete
measures optimal transport max problem

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)\\s.t. \gamma 1 = a\\ \gamma^T 1= b\\ \gamma \geq 0\end{aligned}\end{align} \]

Where :

  • M is the (ns,nt) metric cost matrix
  • \(\Omega\) is the entropic regularization term with \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target weights (sum to 1)

The algorithm used for solving the problem is the SAG or ASGD algorithms as proposed in [18]_

Parameters:
  • a (ndarray, shape (ns,)) – source measure
  • b (ndarray, shape (nt,)) – target measure
  • M (ndarray, shape (ns, nt)) – cost matrix
  • reg (float) – Regularization term > 0
  • methode (str) – used method (SAG or ASGD)
  • numItermax (int) – number of iteration
  • lr (float) – learning rate
  • n_source (int) – size of the source measure
  • n_target (int) – size of the target measure
  • log (bool, optional) – record log if True
Returns:

  • pi (ndarray, shape (ns, nt)) – transportation matrix
  • log (dict) – log dictionary return only if log==True in parameters

Examples

>>> import ot
>>> np.random.seed(0)
>>> n_source = 7
>>> n_target = 4
>>> a = ot.utils.unif(n_source)
>>> b = ot.utils.unif(n_target)
>>> X_source = np.random.randn(n_source, 2)
>>> Y_target = np.random.randn(n_target, 2)
>>> M = ot.dist(X_source, Y_target)
>>> ot.stochastic.solve_semi_dual_entropic(a, b, M, reg=1, method="ASGD", numItermax=300000)
array([[2.53942342e-02, 9.98640673e-02, 1.75945647e-02, 4.27664307e-06],
       [1.21556999e-01, 1.26350515e-02, 1.30491795e-03, 7.36017394e-03],
       [3.54070702e-03, 7.63581358e-02, 6.29581672e-02, 1.32812798e-07],
       [2.60578198e-02, 3.35916645e-02, 8.28023223e-02, 4.05336238e-04],
       [9.86808864e-03, 7.59774324e-04, 1.08702729e-02, 1.21359007e-01],
       [2.17218856e-02, 9.12931802e-04, 1.87962526e-03, 1.18342700e-01],
       [4.14237512e-02, 2.67487857e-02, 7.23016955e-02, 2.38291052e-03]])

References

[Genevay et al., 2016] :
Stochastic Optimization for Large-scale Optimal Transport,
Advances in Neural Information Processing Systems (2016),
arXiv preprint arxiv:1605.08527.

ot.unbalanced

Regularized Unbalanced OT

ot.unbalanced.barycenter_unbalanced(A, M, reg, reg_m, method='sinkhorn', weights=None, numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Compute the entropic unbalanced wasserstein barycenter of A.

The function solves the following optimization problem with a
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i Wu_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(Wu_{reg}(\cdot,\cdot)\) is the unbalanced entropic regularized

Wasserstein distance (see ot.unbalanced.sinkhorn_unbalanced) - \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\) - reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT - reg_mis the marginal relaxation hyperparameter The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10]_

Parameters:
  • A (np.ndarray (dim, n_hists)) – n_hists training distributions a_i of dimension dim
  • M (np.ndarray (dim, dim)) – ground metric matrix for OT.
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • weights (np.ndarray (n_hists,) optional) – Weight of each distribution (barycentric coodinates) If None, uniform weights are used.
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (> 0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Unbalanced Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprin arXiv:1607.05816.
ot.unbalanced.barycenter_unbalanced_sinkhorn(A, M, reg, reg_m, weights=None, numItermax=1000, stopThr=1e-06, verbose=False, log=False)[source]

Compute the entropic unbalanced wasserstein barycenter of A.

The function solves the following optimization problem with a
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i Wu_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(Wu_{reg}(\cdot,\cdot)\) is the unbalanced entropic regularized

Wasserstein distance (see ot.unbalanced.sinkhorn_unbalanced) - \(\mathbf{a}_i\) are training distributions in the columns of matrix \(\mathbf{A}\) - reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT - reg_mis the marginal relaxation hyperparameter The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10]_

Parameters:
  • A (np.ndarray (dim, n_hists)) – n_hists training distributions a_i of dimension dim
  • M (np.ndarray (dim, dim)) – ground metric matrix for OT.
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • weights (np.ndarray (n_hists,) optional) – Weight of each distribution (barycentric coodinates) If None, uniform weights are used.
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (> 0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Unbalanced Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprin arXiv:1607.05816.
ot.unbalanced.barycenter_unbalanced_stabilized(A, M, reg, reg_m, weights=None, tau=1000.0, numItermax=1000, stopThr=1e-06, verbose=False, log=False)[source]

Compute the entropic unbalanced wasserstein barycenter of A with stabilization.

The function solves the following optimization problem:
\[\mathbf{a} = arg\min_\mathbf{a} \sum_i Wu_{reg}(\mathbf{a},\mathbf{a}_i)\]

where :

  • \(Wu_{reg}(\cdot,\cdot)\) is the unbalanced entropic regularized
    Wasserstein distance (see ot.unbalanced.sinkhorn_unbalanced)
  • \(\mathbf{a}_i\) are training distributions in the columns of
    matrix \(\mathbf{A}\)
  • reg and \(\mathbf{M}\) are respectively the regularization term and
    the cost matrix for OT
  • reg_mis the marginal relaxation hyperparameter
    The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10]_
Parameters:
  • A (np.ndarray (dim, n_hists)) – n_hists training distributions a_i of dimension dim
  • M (np.ndarray (dim, dim)) – ground metric matrix for OT.
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • tau (float) – Stabilization threshold for log domain absorption.
  • weights (np.ndarray (n_hists,) optional) – Weight of each distribution (barycentric coodinates) If None, uniform weights are used.
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (> 0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • a ((dim,) ndarray) – Unbalanced Wasserstein barycenter
  • log (dict) – log dictionary return only if log==True in parameters

References

[3]Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
ot.unbalanced.sinkhorn_knopp_unbalanced(a, b, M, reg, reg_m, numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization unbalanced optimal transport problem and return the loss

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + \reg_m KL(\gamma 1, a) + \reg_m KL(\gamma^T 1, b)\\s.t. \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target unbalanced distributions
  • KL is the Kullback-Leibler divergence

The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

Parameters:
  • a (np.ndarray (dim_a,)) – Unnormalized histogram of dimension dim_a
  • b (np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)) – One or multiple unnormalized histograms of dimension dim_b If many, compute all the OT distances (a, b_i)
  • M (np.ndarray (dim_a, dim_b)) – loss matrix
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (> 0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • if n_hists == 1

    gamma : (dim_a x dim_b) ndarray

    Optimal transportation matrix for the given parameters

    log : dict

    log dictionary returned only if log is True

  • else

    ot_distance : (n_hists,) ndarray

    the OT distance between a and each of the histograms b_i

    log : dict

    log dictionary returned only if log is True

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.],[1., 0.]]
>>> ot.unbalanced.sinkhorn_knopp_unbalanced(a, b, M, 1., 1.)
array([[0.51122823, 0.18807035],
       [0.18807035, 0.51122823]])

References

[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[25]Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. : Learning with a Wasserstein Loss, Advances in Neural Information Processing Systems (NIPS) 2015

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.unbalanced.sinkhorn_stabilized_unbalanced(a, b, M, reg, reg_m, tau=100000.0, numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization unbalanced optimal transport problem and return the loss

The function solves the following optimization problem using log-domain stabilization as proposed in [10]:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)\\s.t. \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization
    term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target unbalanced distributions
  • KL is the Kullback-Leibler divergence

The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

Parameters:
  • a (np.ndarray (dim_a,)) – Unnormalized histogram of dimension dim_a
  • b (np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)) – One or multiple unnormalized histograms of dimension dim_b If many, compute all the OT distances (a, b_i)
  • M (np.ndarray (dim_a, dim_b)) – loss matrix
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • tau (float) – thershold for max value in u or v for log scaling
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • if n_hists == 1

    gamma : (dim_a x dim_b) ndarray

    Optimal transportation matrix for the given parameters

    log : dict

    log dictionary returned only if log is True

  • else

    ot_distance : (n_hists,) ndarray

    the OT distance between a and each of the histograms b_i

    log : dict

    log dictionary returned only if log is True

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.],[1., 0.]]
>>> ot.unbalanced.sinkhorn_stabilized_unbalanced(a, b, M, 1., 1.)
array([[0.51122823, 0.18807035],
       [0.18807035, 0.51122823]])

References

[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[25]Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. : Learning with a Wasserstein Loss, Advances in Neural Information Processing Systems (NIPS) 2015

See also

ot.lp.emd()
Unregularized OT
ot.optim.cg()
General regularized OT
ot.unbalanced.sinkhorn_unbalanced(a, b, M, reg, reg_m, method='sinkhorn', numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Solve the unbalanced entropic regularization optimal transport problem and return the OT plan

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)\\s.t. \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization
    term \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target unbalanced distributions
  • KL is the Kullback-Leibler divergence
The algorithm used for solving the problem is the generalized
Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_
Parameters:
  • a (np.ndarray (dim_a,)) – Unnormalized histogram of dimension dim_a
  • b (np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)) – One or multiple unnormalized histograms of dimension dim_b If many, compute all the OT distances (a, b_i)
  • M (np.ndarray (dim_a, dim_b)) – loss matrix
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_reg_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • if n_hists == 1

    gamma : (dim_a x dim_b) ndarray

    Optimal transportation matrix for the given parameters

    log : dict

    log dictionary returned only if log is True

  • else

    ot_distance : (n_hists,) ndarray

    the OT distance between a and each of the histograms b_i

    log : dict

    log dictionary returned only if log is True

Examples

>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn_unbalanced(a, b, M, 1, 1)
array([[0.51122823, 0.18807035],
       [0.18807035, 0.51122823]])

References

[2]M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[25]Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. : Learning with a Wasserstein Loss, Advances in Neural Information Processing Systems (NIPS) 2015

See also

ot.unbalanced.sinkhorn_knopp_unbalanced()
Unbalanced Classic Sinkhorn [10]
ot.unbalanced.sinkhorn_stabilized_unbalanced()
Unbalanced Stabilized sinkhorn [9][10]
ot.unbalanced.sinkhorn_reg_scaling_unbalanced()
Unbalanced Sinkhorn with epslilon scaling [9][10]
ot.unbalanced.sinkhorn_unbalanced2(a, b, M, reg, reg_m, method='sinkhorn', numItermax=1000, stopThr=1e-06, verbose=False, log=False, **kwargs)[source]

Solve the entropic regularization unbalanced optimal transport problem and return the loss

The function solves the following optimization problem:

\[ \begin{align}\begin{aligned}W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) + reg_m KL(\gamma 1, a) + reg_m KL(\gamma^T 1, b)\\s.t. \gamma\geq 0\end{aligned}\end{align} \]

where :

  • M is the (dim_a, dim_b) metric cost matrix
  • \(\Omega\) is the entropic regularization term
    \(\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})\)
  • a and b are source and target unbalanced distributions
  • KL is the Kullback-Leibler divergence

The algorithm used for solving the problem is the generalized Sinkhorn-Knopp matrix scaling algorithm as proposed in [10, 23]_

Parameters:
  • a (np.ndarray (dim_a,)) – Unnormalized histogram of dimension dim_a
  • b (np.ndarray (dim_b,) or np.ndarray (dim_b, n_hists)) – One or multiple unnormalized histograms of dimension dim_b If many, compute all the OT distances (a, b_i)
  • M (np.ndarray (dim_a, dim_b)) – loss matrix
  • reg (float) – Entropy regularization term > 0
  • reg_m (float) – Marginal relaxation term > 0
  • method (str) – method used for the solver either ‘sinkhorn’, ‘sinkhorn_stabilized’ or ‘sinkhorn_reg_scaling’, see those function for specific parameters
  • numItermax (int, optional) – Max number of iterations
  • stopThr (float, optional) – Stop threshol on error (>0)
  • verbose (bool, optional) – Print information along iterations
  • log (bool, optional) – record log if True
Returns:

  • ot_distance ((n_hists,) ndarray) – the OT distance between a and each of the histograms b_i
  • log (dict) – log dictionary returned only if log is True

Examples

>>> import ot
>>> a=[.5, .10]
>>> b=[.5, .5]
>>> M=[[0., 1.],[1., 0.]]
>>> ot.unbalanced.sinkhorn_unbalanced2(a, b, M, 1., 1.)
array([0.31912866])

References

[2]M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
[9]Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
[10]Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[25]Frogner C., Zhang C., Mobahi H., Araya-Polo M., Poggio T. : Learning with a Wasserstein Loss, Advances in Neural Information Processing Systems (NIPS) 2015

See also

ot.unbalanced.sinkhorn_knopp()
Unbalanced Classic Sinkhorn [10]
ot.unbalanced.sinkhorn_stabilized()
Unbalanced Stabilized sinkhorn [9][10]
ot.unbalanced.sinkhorn_reg_scaling()
Unbalanced Sinkhorn with epslilon scaling [9][10]