Python modules

ot

Python Optimal Transport toolbox

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

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) ndarray, float64) – Source histogram (uniform weigth if empty list)
  • b ((nt,) ndarray, float64) – Target histogram (uniform weigth if empty list)
  • M ((ns,nt) ndarray, float64) – loss matrix
  • 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 matrix.
Returns:

  • gamma ((ns x nt) 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

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) ndarray, float64) – Source histogram (uniform weigth if empty list)
  • b ((nt,) ndarray, float64) – Target histogram (uniform weigth if empty list)
  • M ((ns,nt) ndarray, float64) – loss matrix
  • 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 (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.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.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 (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
  • 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:

  • gamma ((ns x nt) ndarray) – 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 (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
  • 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 ((nt) ndarray or float) – 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.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.

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.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.dist(x1, x2=None, metric='sqeuclidean')[source]

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

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, fun, 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, 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 (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)
  • 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 ((d,) 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 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
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.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

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) ndarray, float64) – Source histogram (uniform weigth if empty list)
  • b ((nt,) ndarray, float64) – Target histogram (uniform weigth if empty list)
  • M ((ns,nt) ndarray, float64) – loss matrix
  • 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 matrix.
Returns:

  • gamma ((ns x nt) 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

Uses the algorithm proposed in [1]_

Parameters:
  • a ((ns,) ndarray, float64) – Source histogram (uniform weigth if empty list)
  • b ((nt,) ndarray, float64) – Target histogram (uniform weigth if empty list)
  • M ((ns,nt) ndarray, float64) – loss matrix
  • 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 (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.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) np.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,) np.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 threshol 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.bregman

Bregman projections for regularized OT

ot.bregman.barycenter(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 (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)
  • 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 ((d,) 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.geometricBar(weights, alldistribT)[source]

return the weighted geometric mean of distributions

ot.bregman.geometricMean(alldistribT)[source]

return the geometric mean of distributions

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 (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
  • 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:

  • gamma ((ns x nt) ndarray) – 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 (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
  • 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 ((nt) ndarray or float) – 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.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.

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.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 (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]_ but with the log stabilization proposed in [10]_ and the log scaling proposed in [9]_ algorithm 3.2

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • b (np.ndarray (nt,)) – samples in the target domain
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term >0
  • tau (float) – thershold for max value in u or v for log scaling
  • tau – 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
  • 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 ((ns x nt) ndarray) – 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 (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
Returns:

  • gamma ((ns x nt) ndarray) – 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 (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]_ but with the log stabilization proposed in [10]_ an defined in [9]_ (Algo 3.1) .

Parameters:
  • a (np.ndarray (ns,)) – samples weights in the source domain
  • b (np.ndarray (nt,)) – samples in the target domain
  • M (np.ndarray (ns,nt)) – 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 ((ns x nt) ndarray) – 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:

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

where :

  • \(W_{M,reg}(\cdot,\cdot)\) is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
  • \(\mathbf{a}\) is an observed distribution, \(\mathbf{h}_0\) is aprior on unmixing
  • reg and \(\mathbf{M}\) are respectively the regularization term and the cost matrix for OT data fitting
  • reg0 and \(\mathbf{M0}\) are respectively the regularization term and the cost matrix for regularization
  • :math:`alpha`weight data fitting and regularization

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

Parameters:
  • a (np.ndarray (d)) – observed distribution
  • D (np.ndarray (d,n)) – dictionary matrix
  • M (np.ndarray (d,d)) – loss matrix
  • M0 (np.ndarray (n,n)) – loss matrix
  • h0 (np.ndarray (n,)) – prior on 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:

  • a ((d,) ndarray) – 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.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,Cs,p,ps)\]

Where :

Cs : metric cost matrix ps : distribution
Parameters:
  • N (Integer) – Size of the targeted barycenter
  • Cs (list of S np.ndarray(ns,ns)) – Metric cost matrices
  • ps (list of S np.ndarray(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
  • 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. \GW 1 = p\\ \GW^T 1= q\\ \GW\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

coupling between the two spaces that minimizes :

sum_{i,j,k,l} L(C1_{i,k},C2_{j,l})*T_{i,j}*T_{k,l}-epsilon(H(T))

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_Dist = \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 (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:

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.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 (Integer) – Size of the targeted barycenter
  • Cs (list of S np.ndarray(ns,ns)) – Metric cost matrices
  • ps (list of S np.ndarray(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, **kwargs)[source]

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

The function solves the following optimization problem:

\[\GW_Dist = \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 (string) – 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
  • **kwargs (dict) – parameters can be directly pased to the ot.optim.cg solver
Returns:

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

    coupling 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, **kwargs)[source]

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

The function solves the following optimization problem:

\[\GW_Dist = \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 (string) – 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
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, T, 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)=(1/2)*|a-b|^2 is read as :
L(a,b) = f1(a)+f2(b)-h1(a)*h2(b) with :
  • f1(a)=(a^2)/2
  • f2(b)=(b^2)/2
  • h1(a)=a
  • h2(b)=b
The kl-loss function L(a,b)=(1/2)*|a-b|^2 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_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(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(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, verbose=False, log=False)[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 (np.ndarray (ns,)) – samples weights in the source domain
  • b (np.ndarray (nt,)) – samples in the target domain
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg (float) – Regularization term >0
  • G0 (np.ndarray (ns,nt), optional) – initial guess (default is indep joint density)
  • 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

[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, 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 (np.ndarray (ns,)) – samples weights in the source domain
  • b (np.ndarray (nt,)) – samples in the target domain
  • M (np.ndarray (ns,nt)) – loss matrix
  • reg1 (float) – Entropic Regularization term >0
  • reg2 (float) – Second Regularization term >0
  • G0 (np.ndarray (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 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

[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 (function) – loss function
  • xk (np.ndarray) – initial position
  • pk (np.ndarray) – descent direction
  • gfk (np.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.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:
  • mapping (string, optional (default="barycentric")) – The kind of mapping to apply to transport samples from a domain into another one. if “barycentric” only the samples used to estimate the coupling can be transported from a domain to another one.
  • 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 (string, optional (default="uniform")) – The kind of distribution estimation to employ
  • verbose (int, optional (default=0)) – Controls the verbosity of the optimization algorithm
  • log (int, optional (default=0)) – Controls the logs of the optimization algorithm
  • 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_

array-like, shape (n_source_samples, n_target_samples) – The optimal coupling

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)
  • verbose (bool, optional (default=False)) – Print information along iterations
  • log (bool, optional (default=False)) – record log if True
coupling_

array-like, shape (n_source_samples, n_target_samples) – The optimal coupling

mapping_

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

log_

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

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)
class ot.da.OTDA(**kwargs)[source]

Class for domain adaptation with optimal transport as proposed in [5]

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
fit(xs, xt, ws=None, wt=None, max_iter=100000)[source]

Fit domain adaptation between samples is xs and xt (with optional weights)

interp(direction=1)[source]

Barycentric interpolation for the source (1) or target (-1) samples

This Barycentric interpolation solves for each source (resp target) sample xs (resp xt) the following optimization problem:

\[arg\min_x \sum_i \gamma_{k,i} c(x,x_i^t)\]

where k is the index of the sample in xs

For the moment only squared euclidean distance is provided but more metric could be used in the future.

predict(x, direction=1)[source]

Out of sample mapping using the formulation from [6]

For each sample x to map, it finds the nearest source sample xs and map the samle x to the position xst+(x-xs) wher xst is the barycentric interpolation of source sample xs.

References

[6]Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882.
class ot.da.OTDA_l1l2(**kwargs)[source]

Class for domain adaptation with optimal transport with entropic and group lasso regularization

fit(xs, ys, xt, reg=1, eta=1, ws=None, wt=None, **kwargs)[source]

Fit regularized domain adaptation between samples is xs and xt (with optional weights), See ot.da.sinkhorn_lpl1_gl for fit parameters

class ot.da.OTDA_lpl1(**kwargs)[source]

Class for domain adaptation with optimal transport with entropic and group regularization

fit(xs, ys, xt, reg=1, eta=1, ws=None, wt=None, **kwargs)[source]

Fit regularized domain adaptation between samples is xs and xt (with optional weights), See ot.da.sinkhorn_lpl1_mm for fit parameters

class ot.da.OTDA_mapping_kernel(**kwargs)[source]

Class for optimal transport with joint nonlinear mapping estimation as in [8]

fit(xs, xt, mu=1, eta=1, bias=False, kerneltype='gaussian', sigma=1, **kwargs)[source]

Fit domain adaptation between samples is xs and xt

predict(x)[source]

Out of sample mapping estimated during the call to fit

class ot.da.OTDA_mapping_linear(**kwargs)[source]

Class for optimal transport with joint linear mapping estimation as in [8]

fit(xs, xt, mu=1, eta=1, bias=False, **kwargs)[source]

Fit domain adaptation between samples is xs and xt (with optional weights)

predict(x)[source]

Out of sample mapping estimated during the call to fit

class ot.da.OTDA_sinkhorn(**kwargs)[source]

Class for domain adaptation with optimal transport with entropic regularization

fit(xs, xt, reg=1, ws=None, wt=None, **kwargs)[source]

Fit regularized domain adaptation between samples is xs and xt (with optional weights)

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
  • mapping (string, optional (default="barycentric")) – The kind of mapping to apply to transport samples from a domain into another one. if “barycentric” only the samples used to estimate the coupling can be transported from a domain to another one.
  • 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 (string, optional (default="uniform")) – The kind of distribution estimation to employ
  • 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
  • verbose (int, optional (default=0)) – Controls the verbosity of the optimization algorithm
  • log (int, optional (default=0)) – Controls the logs of the optimization algorithm
  • 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_

array-like, shape (n_source_samples, n_target_samples) – The optimal coupling

log_

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

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
  • mapping (string, optional (default="barycentric")) – The kind of mapping to apply to transport samples from a domain into another one. if “barycentric” only the samples used to estimate the coupling can be transported from a domain to another one.
  • 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 (string, optional (default="uniform")) – The kind of distribution estimation to employ
  • 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
  • verbose (int, optional (default=0)) – Controls the verbosity of the optimization algorithm
  • 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 infinite cost
coupling_

array-like, shape (n_source_samples, n_target_samples) – The optimal coupling

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.
  • mapping (string, optional (default="barycentric")) – The kind of mapping to apply to transport samples from a domain into another one. if “barycentric” only the samples used to estimate the coupling can be transported from a domain to another one.
  • 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 (string, optional (default="uniform")) – The kind of distribution estimation to employ
  • verbose (int, optional (default=0)) – Controls the verbosity of the optimization algorithm
  • log (int, optional (default=0)) – Controls the logs of the optimization algorithm
  • 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 infinite cost
coupling_

array-like, shape (n_source_samples, n_target_samples) – The optimal coupling

log_

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

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

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)
  • bias (bool,optional) – Estimate linear mapping with constant bias
  • kerneltype (str,optional) – kernel used by calling function ot.utils.kernel (gaussian by default)
  • sigma (float, optional) – Gaussian kernel bandwidth.
  • 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 ((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 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
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.dr

Dimension reduction with optimal transport

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 (numpy.ndarray (n,d)) – Training samples
  • y (np.ndarray (n,)) – labels for training samples
  • p (int, optional) – size of dimensionnality reduction
  • reg (float, optional) – Regularization term >0 (ridge regularization)
Returns:

  • P ((d x p) ndarray) – Optimal transportation matrix for the given parameters
  • proj (fun) – 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 (numpy.ndarray (n,d)) – Training samples
  • y (np.ndarray (n,)) – labels for training samples
  • p (int, optional) – size of dimensionnality reduction
  • reg (float, optional) – Regularization term >0 (entropic regularization)
  • solver (str, optional) – None for steepest decsent or ‘TrustRegions’ for trust regions algorithm else shoudl be a pymanopt.solvers
  • P0 (numpy.ndarray (d,p)) – Initial starting point for projection
  • verbose (int, optional) – Print information along iterations
Returns:

  • P ((d x p) ndarray) – Optimal transportation matrix for the given parameters
  • proj (fun) – 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 function that can be usefull

class ot.utils.BaseEstimator[source]

Base class for most objects in POT 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 (boolean, 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
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 :param seed: 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 (np.array (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:

np.array (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 >>> @deprecated() … def some_function(): pass

Parameters:extra (string) – 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 (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, fun, 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:

np.array (n1,n2)

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

dots function for multiple matrix multiply

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

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:

np.array (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 (np.array (2,)) – mean value of the gaussian distribution
  • sigma (np.array (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:

np.array (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 (np.array (n,d)) – n observation of size d
  • y (np.array (n,)) – labels of the samples

ot.plot

Functions for plotting OT matrices

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 (np.array, shape (na,)) – Source distribution
  • b (np.array, shape (nb,)) – Target distribution
  • M (np.array, 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

ot.stochastic.averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None)[source]
Compute the ASGD algorithm to solve the regularized semi contibous measures
optimal transport max problem

The function solves the following optimization problem:

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

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 ASGD algorithm as proposed in [18]_ [alg.2]

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

ave_v – optimization vector

Return type:

np.ndarray(nt,)

Examples

>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> 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)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
                                                  method, numItermax)
>>> print(asgd_pi)

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_alpha(M, reg, alpha, beta, batch_size, batch_alpha, batch_beta)[source]

Computes the partial gradient of F_W_varepsilon

Compute the partial gradient of the dual problem:

..math:

orall i in batch_alpha,
grad_alpha_i = 1 * batch_size -
sum_{j in batch_beta} exp((alpha_i + beta_j - M_{i,j})/reg)

where : - M is the (ns,nt) metric cost matrix - alpha, beta are dual variables in R^ixR^J - reg is the regularization term - batch_alpha and batch_beta are list of index

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

reg : float number,
Regularization term > 0
M : np.ndarray(ns, nt),
cost matrix
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
batch_size : int number
size of the batch
batch_alpha : np.ndarray(bs,)
batch of index of alpha
batch_beta : np.ndarray(bs,)
batch of index of beta
grad : np.ndarray(ns,)
partial grad F in alpha
>>> 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 = stochastic.solve_dual_entropic(a, b, M, reg,
                                                        batch_size,
                                                        numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
[Seguy et al., 2018] :
International Conference on Learning Representation (2018),
arXiv preprint arxiv:1711.02283.
ot.stochastic.batch_grad_dual_beta(M, reg, alpha, beta, batch_size, batch_alpha, batch_beta)[source]

Computes the partial gradient of F_W_varepsilon

Compute the partial gradient of the dual problem:

..math:

orall j in batch_beta,
grad_beta_j = 1 * batch_size -
sum_{i in batch_alpha} exp((alpha_i + beta_j - M_{i,j})/reg)

where : - M is the (ns,nt) metric cost matrix - alpha, beta are dual variables in R^ixR^J - reg is the regularization term - batch_alpha and batch_beta are list of index

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

M : np.ndarray(ns, nt),
cost matrix
reg : float number,
Regularization term > 0
alpha : np.ndarray(ns,)
dual variable
beta : np.ndarray(nt,)
dual variable
batch_size : int number
size of the batch
batch_alpha : np.ndarray(bs,)
batch of index of alpha
batch_beta : np.ndarray(bs,)
batch of index of beta
grad : np.ndarray(ns,)
partial grad F in beta
>>> 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 = stochastic.solve_dual_entropic(a, b, M, reg,
                                                        batch_size,
                                                        numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)
[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 (np.ndarray(nt,)) – target measure
  • M (np.ndarray(ns, nt)) – cost matrix
  • reg (float) – regularization term > 0
  • v (np.ndarray(nt,)) – dual variable
Returns:

u

Return type:

np.ndarray(ns,)

Examples

>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> 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)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
                                                  method, numItermax)
>>> print(asgd_pi)

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:

\[\W_\]
arepsilon(a, b) = max_
sum_i (sum_j v_j * b_j

eg 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]

b : np.ndarray(nt,),
target measure
M : np.ndarray(ns, nt),
cost matrix
reg : float nu,
Regularization term > 0
v : np.ndarray(nt,),
optimization vector
i : number int,
picked number i

coordinate gradient : np.ndarray(nt,)

>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> 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)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
                                                  method, numItermax)
>>> print(asgd_pi)
[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:

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

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 SAG algorithm as proposed in [18]_ [alg.1]

Parameters:
  • a (np.ndarray(ns,),) – source measure
  • b (np.ndarray(nt,),) – target measure
  • M (np.ndarray(ns, nt),) – cost matrix
  • reg (float number,) – Regularization term > 0
  • numItermax (int number) – number of iteration
  • lr (float number) – learning rate
Returns:

v – dual variable

Return type:

np.ndarray(nt,)

Examples

>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> 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)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
                                                  method, numItermax)
>>> print(asgd_pi)

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(M, reg, batch_size, numItermax, lr, alternate=True)[source]
Compute the sgd algorithm to solve the regularized discrete measures
optimal transport dual problem

The function solves the following optimization problem:

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

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:
  • M (np.ndarray(ns, nt),) – cost matrix
  • reg (float number,) – Regularization term > 0
  • batch_size (int number) – size of the batch
  • numItermax (int number) – number of iteration
  • lr (float number) – learning rate
  • alternate (bool, optional) – alternating algorithm
Returns:

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

Examples

>>> 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 = stochastic.solve_dual_entropic(a, b, M, reg,
                                                        batch_size,
                                                        numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)

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:

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

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 (np.ndarray(ns,),) – source measure
  • b (np.ndarray(nt,),) – target measure
  • M (np.ndarray(ns, nt),) – cost matrix
  • reg (float number,) – Regularization term > 0
  • batch_size (int number) – size of the batch
  • numItermax (int number) – number of iteration
  • lr (float number) – learning rate
  • log (bool, optional) – record log if True
Returns:

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

Examples

>>> 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 = stochastic.solve_dual_entropic(a, b, M, reg,
                                                        batch_size,
                                                        numItermax, lr, log)
>>> print(log['alpha'], log['beta'])
>>> print(sgd_dual_pi)

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:

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

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 SAG or ASGD algorithms as proposed in [18]_

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

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

Examples

>>> n_source = 7
>>> n_target = 4
>>> reg = 1
>>> numItermax = 300000
>>> 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)
>>> method = "ASGD"
>>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg,
                                                  method, numItermax)
>>> print(asgd_pi)

References

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