Python modules

ot

Python Optimal Transport toolbox

ot.emd(a, b, M)[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
Returns:

gamma – Optimal transportation matrix for the given parameters

Return type:

(ns x nt) ndarray

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)[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
Returns:

gamma – Optimal transportation matrix for the given parameters

Return type:

(ns x nt) ndarray

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.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]
  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.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)[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
Returns:

gamma – Optimal transportation matrix for the given parameters

Return type:

(ns x nt) ndarray

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)[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
Returns:

gamma – Optimal transportation matrix for the given parameters

Return type:

(ns x nt) ndarray

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.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.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.OTDA(metric='sqeuclidean')[source]

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

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
fit(xs, xt, ws=None, wt=None, norm=None)[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.

normalizeM(norm)[source]

It may help to normalize the cost matrix self.M if there are numerical errors during the sinkhorn based algorithms.

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(metric='sqeuclidean')[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, norm=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(metric='sqeuclidean')[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, norm=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[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[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(metric='sqeuclidean')[source]

Class for domain adaptation with optimal transport with entropic regularization

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

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

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]
  1. 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]
  1. 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]
  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.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]
  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.lp.emd()
Unregularized OT
ot.bregman.sinkhorn()
Entropic regularized OT
ot.optim.cg()
General regularized OT

ot.dr

ot.utils

Various function that can be usefull

ot.utils.clean_zeros(a, b, M)[source]

Remove all components with zeros weights in a and b

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 (na,)) – Source distribution
  • b (np.array (nb,)) – Target distribution
  • M (np.array (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 (np.array (ns,2)) – Source samples positions
  • b (np.array (nt,2)) – Target samples positions
  • G (np.array (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)