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 of size d
  • M (np.ndarray (d,d)) – loss matrix for OT
  • 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:

  • 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.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 of size d
  • M (np.ndarray (d,d)) – loss matrix for OT
  • 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:

  • 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.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.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(*args, **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(*args, **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(*args, **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(*args, **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(*args, **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(*args, **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)

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.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.get_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.get_2D_samples_gauss(n, m, sigma)[source]

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

Parameters:
  • n (int) – number of bins in the histogram
  • m (np.array (2,)) – mean value of the gaussian distribution
  • sigma (np.array (2,2)) – covariance matrix of the gaussian distribution
Returns:

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

Return type:

np.array (n,2)

ot.datasets.get_data_classif(dataset, n, nz=0.5, theta=0, **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)
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)