| 1 |
|
| 2 |
""" |
| 3 |
Bregman projections solvers for entropic regularized OT |
| 4 |
""" |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
import warnings |
| 15 |
|
| 16 |
import numpy as np |
| 17 |
|
| 18 |
from ..utils import list_to_array |
| 19 |
from ..backend import get_backend |
| 20 |
|
| 21 |
|
| 22 |
def sinkhorn( |
| 23 |
a, |
| 24 |
b, |
| 25 |
M, |
| 26 |
reg, |
| 27 |
method="sinkhorn", |
| 28 |
numItermax=1000, |
| 29 |
stopThr=1e-9, |
| 30 |
verbose=False, |
| 31 |
log=False, |
| 32 |
warn=True, |
| 33 |
warmstart=None, |
| 34 |
**kwargs, |
| 35 |
): |
| 36 |
r""" |
| 37 |
Solve the entropic regularization optimal transport problem and return the OT matrix |
| 38 |
|
| 39 |
The function solves the following optimization problem: |
| 40 |
|
| 41 |
.. math:: |
| 42 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 43 |
\mathrm{reg}\cdot\Omega(\gamma) |
| 44 |
|
| 45 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 46 |
|
| 47 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 48 |
|
| 49 |
\gamma &\geq 0 |
| 50 |
|
| 51 |
where : |
| 52 |
|
| 53 |
- :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix |
| 54 |
- :math:`\Omega` is the entropic regularization term |
| 55 |
:math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 56 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target |
| 57 |
weights (histograms, both sum to 1) |
| 58 |
|
| 59 |
.. note:: This function is backend-compatible and will work on arrays |
| 60 |
from all compatible backends. |
| 61 |
|
| 62 |
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix |
| 63 |
scaling algorithm as proposed in :ref:`[2] <references-sinkhorn>` |
| 64 |
|
| 65 |
**Choosing a Sinkhorn solver** |
| 66 |
|
| 67 |
By default and when using a regularization parameter that is not too small |
| 68 |
the default sinkhorn solver should be enough. If you need to use a small |
| 69 |
regularization to get sharper OT matrices, you should use the |
| 70 |
:py:func:`ot.bregman.sinkhorn_stabilized` solver that will avoid numerical |
| 71 |
errors. This last solver can be very slow in practice and might not even |
| 72 |
converge to a reasonable OT matrix in a finite time. This is why |
| 73 |
:py:func:`ot.bregman.sinkhorn_epsilon_scaling` that relies on iterating the value |
| 74 |
of the regularization (and using warm start) sometimes leads to better |
| 75 |
solutions. Note that the greedy version of the sinkhorn |
| 76 |
:py:func:`ot.bregman.greenkhorn` can also lead to a speedup and the screening |
| 77 |
version of the sinkhorn :py:func:`ot.bregman.screenkhorn` aim at providing a |
| 78 |
fast approximation of the Sinkhorn problem. For use of GPU and gradient |
| 79 |
computation with small number of iterations we strongly recommend the |
| 80 |
:py:func:`ot.bregman.sinkhorn_log` solver that will no need to check for |
| 81 |
numerical problems. |
| 82 |
|
| 83 |
|
| 84 |
Parameters |
| 85 |
---------- |
| 86 |
a : array-like, shape (dim_a,) |
| 87 |
samples weights in the source domain |
| 88 |
b : array-like, shape (dim_b,) or ndarray, shape (dim_b, n_hists) |
| 89 |
samples in the target domain, compute sinkhorn with multiple targets |
| 90 |
and fixed :math:`\mathbf{M}` if :math:`\mathbf{b}` is a matrix |
| 91 |
(return OT loss + dual variables in log) |
| 92 |
M : array-like, shape (dim_a, dim_b) |
| 93 |
loss matrix |
| 94 |
reg : float |
| 95 |
Regularization term >0 |
| 96 |
method : str |
| 97 |
method used for the solver either 'sinkhorn','sinkhorn_log', |
| 98 |
'greenkhorn', 'sinkhorn_stabilized' or 'sinkhorn_epsilon_scaling', see |
| 99 |
those function for specific parameters |
| 100 |
numItermax : int, optional |
| 101 |
Max number of iterations |
| 102 |
stopThr : float, optional |
| 103 |
Stop threshold on error (>0) |
| 104 |
verbose : bool, optional |
| 105 |
Print information along iterations |
| 106 |
log : bool, optional |
| 107 |
record log if True |
| 108 |
warn : bool, optional |
| 109 |
if True, raises a warning if the algorithm doesn't convergence. |
| 110 |
warmstart: tuple of arrays, shape (dim_a, dim_b), optional |
| 111 |
Initialization of dual potentials. If provided, the dual potentials should be given |
| 112 |
(that is the logarithm of the u,v sinkhorn scaling vectors) |
| 113 |
|
| 114 |
Returns |
| 115 |
------- |
| 116 |
gamma : array-like, shape (dim_a, dim_b) |
| 117 |
Optimal transportation matrix for the given parameters |
| 118 |
log : dict |
| 119 |
log dictionary return only if log==True in parameters |
| 120 |
|
| 121 |
Examples |
| 122 |
-------- |
| 123 |
|
| 124 |
>>> import ot |
| 125 |
>>> a=[.5, .5] |
| 126 |
>>> b=[.5, .5] |
| 127 |
>>> M=[[0., 1.], [1., 0.]] |
| 128 |
>>> ot.sinkhorn(a, b, M, 1) |
| 129 |
array([[0.36552929, 0.13447071], |
| 130 |
[0.13447071, 0.36552929]]) |
| 131 |
|
| 132 |
.. _references-sinkhorn: |
| 133 |
References |
| 134 |
---------- |
| 135 |
|
| 136 |
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation |
| 137 |
of Optimal Transport, Advances in Neural Information Processing |
| 138 |
Systems (NIPS) 26, 2013 |
| 139 |
|
| 140 |
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms |
| 141 |
for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. |
| 142 |
|
| 143 |
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). |
| 144 |
Scaling algorithms for unbalanced transport problems. |
| 145 |
arXiv preprint arXiv:1607.05816. |
| 146 |
|
| 147 |
.. [34] Feydy, J., Séjourné, T., Vialard, F. X., Amari, S. I., Trouvé, |
| 148 |
A., & Peyré, G. (2019, April). Interpolating between optimal transport |
| 149 |
and MMD using Sinkhorn divergences. In The 22nd International Conference |
| 150 |
on Artificial Intelligence and Statistics (pp. 2681-2690). PMLR. |
| 151 |
|
| 152 |
|
| 153 |
See Also |
| 154 |
-------- |
| 155 |
ot.lp.emd : Unregularized OT |
| 156 |
ot.optim.cg : General regularized OT |
| 157 |
ot.bregman.sinkhorn_knopp : Classic Sinkhorn :ref:`[2] <references-sinkhorn>` |
| 158 |
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn |
| 159 |
:ref:`[9] <references-sinkhorn>` :ref:`[10] <references-sinkhorn>` |
| 160 |
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epsilon scaling |
| 161 |
:ref:`[9] <references-sinkhorn>` :ref:`[10] <references-sinkhorn>` |
| 162 |
|
| 163 |
""" |
| 164 |
|
| 165 |
if method.lower() == "sinkhorn": |
| 166 |
return sinkhorn_knopp( |
| 167 |
a, |
| 168 |
b, |
| 169 |
M, |
| 170 |
reg, |
| 171 |
numItermax=numItermax, |
| 172 |
stopThr=stopThr, |
| 173 |
verbose=verbose, |
| 174 |
log=log, |
| 175 |
warn=warn, |
| 176 |
warmstart=warmstart, |
| 177 |
**kwargs, |
| 178 |
) |
| 179 |
elif method.lower() == "sinkhorn_log": |
| 180 |
return sinkhorn_log( |
| 181 |
a, |
| 182 |
b, |
| 183 |
M, |
| 184 |
reg, |
| 185 |
numItermax=numItermax, |
| 186 |
stopThr=stopThr, |
| 187 |
verbose=verbose, |
| 188 |
log=log, |
| 189 |
warn=warn, |
| 190 |
warmstart=warmstart, |
| 191 |
**kwargs, |
| 192 |
) |
| 193 |
elif method.lower() == "greenkhorn": |
| 194 |
return greenkhorn( |
| 195 |
a, |
| 196 |
b, |
| 197 |
M, |
| 198 |
reg, |
| 199 |
numItermax=numItermax, |
| 200 |
stopThr=stopThr, |
| 201 |
verbose=verbose, |
| 202 |
log=log, |
| 203 |
warn=warn, |
| 204 |
warmstart=warmstart, |
| 205 |
) |
| 206 |
elif method.lower() == "sinkhorn_stabilized": |
| 207 |
return sinkhorn_stabilized( |
| 208 |
a, |
| 209 |
b, |
| 210 |
M, |
| 211 |
reg, |
| 212 |
numItermax=numItermax, |
| 213 |
stopThr=stopThr, |
| 214 |
warmstart=warmstart, |
| 215 |
verbose=verbose, |
| 216 |
log=log, |
| 217 |
warn=warn, |
| 218 |
**kwargs, |
| 219 |
) |
| 220 |
elif method.lower() == "sinkhorn_epsilon_scaling": |
| 221 |
return sinkhorn_epsilon_scaling( |
| 222 |
a, |
| 223 |
b, |
| 224 |
M, |
| 225 |
reg, |
| 226 |
numItermax=numItermax, |
| 227 |
stopThr=stopThr, |
| 228 |
warmstart=warmstart, |
| 229 |
verbose=verbose, |
| 230 |
log=log, |
| 231 |
warn=warn, |
| 232 |
**kwargs, |
| 233 |
) |
| 234 |
else: |
| 235 |
raise ValueError("Unknown method '%s'." % method) |
| 236 |
|
| 237 |
|
| 238 |
def sinkhorn2( |
| 239 |
a, |
| 240 |
b, |
| 241 |
M, |
| 242 |
reg, |
| 243 |
method="sinkhorn", |
| 244 |
numItermax=1000, |
| 245 |
stopThr=1e-9, |
| 246 |
verbose=False, |
| 247 |
log=False, |
| 248 |
warn=False, |
| 249 |
warmstart=None, |
| 250 |
**kwargs, |
| 251 |
): |
| 252 |
r""" |
| 253 |
Solve the entropic regularization optimal transport problem and return the loss |
| 254 |
|
| 255 |
The function solves the following optimization problem: |
| 256 |
|
| 257 |
.. math:: |
| 258 |
W = \min_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 259 |
\mathrm{reg}\cdot\Omega(\gamma) |
| 260 |
|
| 261 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 262 |
|
| 263 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 264 |
|
| 265 |
\gamma &\geq 0 |
| 266 |
|
| 267 |
where : |
| 268 |
|
| 269 |
- :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix |
| 270 |
- :math:`\Omega` is the entropic regularization term |
| 271 |
:math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 272 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target |
| 273 |
weights (histograms, both sum to 1) |
| 274 |
|
| 275 |
and returns :math:`\langle \gamma^*, \mathbf{M} \rangle_F` (without |
| 276 |
the entropic contribution). |
| 277 |
|
| 278 |
.. note:: This function is backend-compatible and will work on arrays |
| 279 |
from all compatible backends. |
| 280 |
|
| 281 |
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix |
| 282 |
scaling algorithm as proposed in :ref:`[2] <references-sinkhorn2>` |
| 283 |
|
| 284 |
|
| 285 |
**Choosing a Sinkhorn solver** |
| 286 |
|
| 287 |
By default and when using a regularization parameter that is not too small |
| 288 |
the default sinkhorn solver should be enough. If you need to use a small |
| 289 |
regularization to get sharper OT matrices, you should use the |
| 290 |
:py:func:`ot.bregman.sinkhorn_log` solver that will avoid numerical |
| 291 |
errors. This last solver can be very slow in practice and might not even |
| 292 |
converge to a reasonable OT matrix in a finite time. This is why |
| 293 |
:py:func:`ot.bregman.sinkhorn_epsilon_scaling` that relies on iterating the value |
| 294 |
of the regularization (and using warm start) sometimes leads to better |
| 295 |
solutions. Note that the greedy version of the sinkhorn |
| 296 |
:py:func:`ot.bregman.greenkhorn` can also lead to a speedup and the screening |
| 297 |
version of the sinkhorn :py:func:`ot.bregman.screenkhorn` aim a providing a |
| 298 |
fast approximation of the Sinkhorn problem. For use of GPU and gradient |
| 299 |
computation with small number of iterations we strongly recommend the |
| 300 |
:py:func:`ot.bregman.sinkhorn_log` solver that will no need to check for |
| 301 |
numerical problems. |
| 302 |
|
| 303 |
Parameters |
| 304 |
---------- |
| 305 |
a : array-like, shape (dim_a,) |
| 306 |
samples weights in the source domain |
| 307 |
b : array-like, shape (dim_b,) or ndarray, shape (dim_b, n_hists) |
| 308 |
samples in the target domain, compute sinkhorn with multiple targets |
| 309 |
and fixed :math:`\mathbf{M}` if :math:`\mathbf{b}` is a matrix |
| 310 |
(return OT loss + dual variables in log) |
| 311 |
M : array-like, shape (dim_a, dim_b) |
| 312 |
loss matrix |
| 313 |
reg : float |
| 314 |
Regularization term >0 |
| 315 |
method : str |
| 316 |
method used for the solver either 'sinkhorn','sinkhorn_log', |
| 317 |
'sinkhorn_stabilized', see those function for specific parameters |
| 318 |
numItermax : int, optional |
| 319 |
Max number of iterations |
| 320 |
stopThr : float, optional |
| 321 |
Stop threshold on error (>0) |
| 322 |
verbose : bool, optional |
| 323 |
Print information along iterations |
| 324 |
log : bool, optional |
| 325 |
record log if True |
| 326 |
warn : bool, optional |
| 327 |
if True, raises a warning if the algorithm doesn't convergence. |
| 328 |
warmstart: tuple of arrays, shape (dim_a, dim_b), optional |
| 329 |
Initialization of dual potentials. If provided, the dual potentials should be given |
| 330 |
(that is the logarithm of the u,v sinkhorn scaling vectors) |
| 331 |
|
| 332 |
Returns |
| 333 |
------- |
| 334 |
W : (n_hists) float/array-like |
| 335 |
Optimal transportation loss for the given parameters |
| 336 |
log : dict |
| 337 |
log dictionary return only if log==True in parameters |
| 338 |
|
| 339 |
|
| 340 |
Examples |
| 341 |
-------- |
| 342 |
|
| 343 |
>>> import ot |
| 344 |
>>> a=[.5, .5] |
| 345 |
>>> b=[.5, .5] |
| 346 |
>>> M=[[0., 1.], [1., 0.]] |
| 347 |
>>> ot.sinkhorn2(a, b, M, 1) |
| 348 |
0.26894142136999516 |
| 349 |
|
| 350 |
|
| 351 |
.. _references-sinkhorn2: |
| 352 |
References |
| 353 |
---------- |
| 354 |
|
| 355 |
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of |
| 356 |
Optimal Transport, Advances in Neural Information |
| 357 |
Processing Systems (NIPS) 26, 2013 |
| 358 |
|
| 359 |
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms |
| 360 |
for Entropy Regularized Transport Problems. |
| 361 |
arXiv preprint arXiv:1610.06519. |
| 362 |
|
| 363 |
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). |
| 364 |
Scaling algorithms for unbalanced transport problems. |
| 365 |
arXiv preprint arXiv:1607.05816. |
| 366 |
|
| 367 |
.. [21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation |
| 368 |
algorithms for optimal transport via Sinkhorn iteration, |
| 369 |
Advances in Neural Information Processing Systems (NIPS) 31, 2017 |
| 370 |
|
| 371 |
.. [34] Feydy, J., Séjourné, T., Vialard, F. X., Amari, S. I., |
| 372 |
Trouvé, A., & Peyré, G. (2019, April). |
| 373 |
Interpolating between optimal transport and MMD using Sinkhorn |
| 374 |
divergences. In The 22nd International Conference on Artificial |
| 375 |
Intelligence and Statistics (pp. 2681-2690). PMLR. |
| 376 |
|
| 377 |
|
| 378 |
See Also |
| 379 |
-------- |
| 380 |
ot.lp.emd : Unregularized OT |
| 381 |
ot.optim.cg : General regularized OT |
| 382 |
ot.bregman.sinkhorn_knopp : Classic Sinkhorn :ref:`[2] <references-sinkhorn2>` |
| 383 |
ot.bregman.greenkhorn : Greenkhorn :ref:`[21] <references-sinkhorn2>` |
| 384 |
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn |
| 385 |
:ref:`[9] <references-sinkhorn2>` :ref:`[10] <references-sinkhorn2>` |
| 386 |
""" |
| 387 |
|
| 388 |
M, a, b = list_to_array(M, a, b) |
| 389 |
nx = get_backend(M, a, b) |
| 390 |
|
| 391 |
if len(b.shape) < 2: |
| 392 |
if method.lower() == "sinkhorn": |
| 393 |
res = sinkhorn_knopp( |
| 394 |
a, |
| 395 |
b, |
| 396 |
M, |
| 397 |
reg, |
| 398 |
numItermax=numItermax, |
| 399 |
stopThr=stopThr, |
| 400 |
verbose=verbose, |
| 401 |
log=log, |
| 402 |
warn=warn, |
| 403 |
warmstart=warmstart, |
| 404 |
**kwargs, |
| 405 |
) |
| 406 |
elif method.lower() == "sinkhorn_log": |
| 407 |
res = sinkhorn_log( |
| 408 |
a, |
| 409 |
b, |
| 410 |
M, |
| 411 |
reg, |
| 412 |
numItermax=numItermax, |
| 413 |
stopThr=stopThr, |
| 414 |
verbose=verbose, |
| 415 |
log=log, |
| 416 |
warn=warn, |
| 417 |
warmstart=warmstart, |
| 418 |
**kwargs, |
| 419 |
) |
| 420 |
elif method.lower() == "sinkhorn_stabilized": |
| 421 |
res = sinkhorn_stabilized( |
| 422 |
a, |
| 423 |
b, |
| 424 |
M, |
| 425 |
reg, |
| 426 |
numItermax=numItermax, |
| 427 |
stopThr=stopThr, |
| 428 |
warmstart=warmstart, |
| 429 |
verbose=verbose, |
| 430 |
log=log, |
| 431 |
warn=warn, |
| 432 |
**kwargs, |
| 433 |
) |
| 434 |
else: |
| 435 |
raise ValueError("Unknown method '%s'." % method) |
| 436 |
if log: |
| 437 |
return nx.sum(M * res[0]), res[1] |
| 438 |
else: |
| 439 |
return nx.sum(M * res) |
| 440 |
|
| 441 |
else: |
| 442 |
if method.lower() == "sinkhorn": |
| 443 |
return sinkhorn_knopp( |
| 444 |
a, |
| 445 |
b, |
| 446 |
M, |
| 447 |
reg, |
| 448 |
numItermax=numItermax, |
| 449 |
stopThr=stopThr, |
| 450 |
verbose=verbose, |
| 451 |
log=log, |
| 452 |
warn=warn, |
| 453 |
warmstart=warmstart, |
| 454 |
**kwargs, |
| 455 |
) |
| 456 |
elif method.lower() == "sinkhorn_log": |
| 457 |
return sinkhorn_log( |
| 458 |
a, |
| 459 |
b, |
| 460 |
M, |
| 461 |
reg, |
| 462 |
numItermax=numItermax, |
| 463 |
stopThr=stopThr, |
| 464 |
verbose=verbose, |
| 465 |
log=log, |
| 466 |
warn=warn, |
| 467 |
warmstart=warmstart, |
| 468 |
**kwargs, |
| 469 |
) |
| 470 |
elif method.lower() == "sinkhorn_stabilized": |
| 471 |
return sinkhorn_stabilized( |
| 472 |
a, |
| 473 |
b, |
| 474 |
M, |
| 475 |
reg, |
| 476 |
numItermax=numItermax, |
| 477 |
stopThr=stopThr, |
| 478 |
warmstart=warmstart, |
| 479 |
verbose=verbose, |
| 480 |
log=log, |
| 481 |
warn=warn, |
| 482 |
**kwargs, |
| 483 |
) |
| 484 |
else: |
| 485 |
raise ValueError("Unknown method '%s'." % method) |
| 486 |
|
| 487 |
|
| 488 |
def sinkhorn_knopp( |
| 489 |
a, |
| 490 |
b, |
| 491 |
M, |
| 492 |
reg, |
| 493 |
numItermax=1000, |
| 494 |
stopThr=1e-9, |
| 495 |
verbose=False, |
| 496 |
log=False, |
| 497 |
warn=True, |
| 498 |
warmstart=None, |
| 499 |
**kwargs, |
| 500 |
): |
| 501 |
r""" |
| 502 |
Solve the entropic regularization optimal transport problem and return the OT matrix |
| 503 |
|
| 504 |
The function solves the following optimization problem: |
| 505 |
|
| 506 |
.. math:: |
| 507 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 508 |
\mathrm{reg}\cdot\Omega(\gamma) |
| 509 |
|
| 510 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 511 |
|
| 512 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 513 |
|
| 514 |
\gamma &\geq 0 |
| 515 |
|
| 516 |
where : |
| 517 |
|
| 518 |
- :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix |
| 519 |
- :math:`\Omega` is the entropic regularization term |
| 520 |
:math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 521 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target |
| 522 |
weights (histograms, both sum to 1) |
| 523 |
|
| 524 |
The algorithm used for solving the problem is the Sinkhorn-Knopp |
| 525 |
matrix scaling algorithm as proposed in :ref:`[2] <references-sinkhorn-knopp>` |
| 526 |
|
| 527 |
|
| 528 |
Parameters |
| 529 |
---------- |
| 530 |
a : array-like, shape (dim_a,) |
| 531 |
samples weights in the source domain |
| 532 |
b : array-like, shape (dim_b,) or array-like, shape (dim_b, n_hists) |
| 533 |
samples in the target domain, compute sinkhorn with multiple targets |
| 534 |
and fixed :math:`\mathbf{M}` if :math:`\mathbf{b}` is a matrix |
| 535 |
(return OT loss + dual variables in log) |
| 536 |
M : array-like, shape (dim_a, dim_b) |
| 537 |
loss matrix |
| 538 |
reg : float |
| 539 |
Regularization term >0 |
| 540 |
numItermax : int, optional |
| 541 |
Max number of iterations |
| 542 |
stopThr : float, optional |
| 543 |
Stop threshold on error (>0) |
| 544 |
verbose : bool, optional |
| 545 |
Print information along iterations |
| 546 |
log : bool, optional |
| 547 |
record log if True |
| 548 |
warn : bool, optional |
| 549 |
if True, raises a warning if the algorithm doesn't convergence. |
| 550 |
warmstart: tuple of arrays, shape (dim_a, dim_b), optional |
| 551 |
Initialization of dual potentials. If provided, the dual potentials should be given |
| 552 |
(that is the logarithm of the u,v sinkhorn scaling vectors) |
| 553 |
|
| 554 |
Returns |
| 555 |
------- |
| 556 |
gamma : array-like, shape (dim_a, dim_b) |
| 557 |
Optimal transportation matrix for the given parameters |
| 558 |
log : dict |
| 559 |
log dictionary return only if log==True in parameters |
| 560 |
|
| 561 |
Examples |
| 562 |
-------- |
| 563 |
|
| 564 |
>>> import ot |
| 565 |
>>> a=[.5, .5] |
| 566 |
>>> b=[.5, .5] |
| 567 |
>>> M=[[0., 1.], [1., 0.]] |
| 568 |
>>> ot.sinkhorn(a, b, M, 1) |
| 569 |
array([[0.36552929, 0.13447071], |
| 570 |
[0.13447071, 0.36552929]]) |
| 571 |
|
| 572 |
|
| 573 |
.. _references-sinkhorn-knopp: |
| 574 |
References |
| 575 |
---------- |
| 576 |
|
| 577 |
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation |
| 578 |
of Optimal Transport, Advances in Neural Information |
| 579 |
Processing Systems (NIPS) 26, 2013 |
| 580 |
|
| 581 |
|
| 582 |
See Also |
| 583 |
-------- |
| 584 |
ot.lp.emd : Unregularized OT |
| 585 |
ot.optim.cg : General regularized OT |
| 586 |
|
| 587 |
""" |
| 588 |
|
| 589 |
a, b, M = list_to_array(a, b, M) |
| 590 |
|
| 591 |
nx = get_backend(M, a, b) |
| 592 |
|
| 593 |
if len(a) == 0: |
| 594 |
a = nx.full((M.shape[0],), 1.0 / M.shape[0], type_as=M) |
| 595 |
if len(b) == 0: |
| 596 |
b = nx.full((M.shape[1],), 1.0 / M.shape[1], type_as=M) |
| 597 |
|
| 598 |
|
| 599 |
dim_a = len(a) |
| 600 |
dim_b = b.shape[0] |
| 601 |
|
| 602 |
if len(b.shape) > 1: |
| 603 |
n_hists = b.shape[1] |
| 604 |
else: |
| 605 |
n_hists = 0 |
| 606 |
|
| 607 |
if log: |
| 608 |
log = {"err": []} |
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
if warmstart is None: |
| 613 |
if n_hists: |
| 614 |
u = nx.ones((dim_a, n_hists), type_as=M) / dim_a |
| 615 |
v = nx.ones((dim_b, n_hists), type_as=M) / dim_b |
| 616 |
else: |
| 617 |
u = nx.ones(dim_a, type_as=M) / dim_a |
| 618 |
v = nx.ones(dim_b, type_as=M) / dim_b |
| 619 |
else: |
| 620 |
u, v = nx.exp(warmstart[0]), nx.exp(warmstart[1]) |
| 621 |
|
| 622 |
K = nx.exp(M / (-reg)) |
| 623 |
|
| 624 |
Kp = (1 / a).reshape(-1, 1) * K |
| 625 |
|
| 626 |
err = 1 |
| 627 |
for ii in range(numItermax): |
| 628 |
uprev = u |
| 629 |
vprev = v |
| 630 |
KtransposeU = nx.dot(K.T, u) |
| 631 |
v = b / KtransposeU |
| 632 |
u = 1.0 / nx.dot(Kp, v) |
| 633 |
|
| 634 |
if ( |
| 635 |
nx.any(KtransposeU == 0) |
| 636 |
or nx.any(nx.isnan(u)) |
| 637 |
or nx.any(nx.isnan(v)) |
| 638 |
or nx.any(nx.isinf(u)) |
| 639 |
or nx.any(nx.isinf(v)) |
| 640 |
): |
| 641 |
|
| 642 |
|
| 643 |
warnings.warn("Warning: numerical errors at iteration %d" % ii) |
| 644 |
u = uprev |
| 645 |
v = vprev |
| 646 |
break |
| 647 |
if ii % 10 == 0: |
| 648 |
|
| 649 |
|
| 650 |
if n_hists: |
| 651 |
tmp2 = nx.einsum("ik,ij,jk->jk", u, K, v) |
| 652 |
else: |
| 653 |
|
| 654 |
tmp2 = nx.einsum("i,ij,j->j", u, K, v) |
| 655 |
err = nx.norm(tmp2 - b) |
| 656 |
if log: |
| 657 |
log["err"].append(err) |
| 658 |
|
| 659 |
if err < stopThr: |
| 660 |
break |
| 661 |
if verbose: |
| 662 |
if ii % 200 == 0: |
| 663 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 664 |
print("{:5d}|{:8e}|".format(ii, err)) |
| 665 |
else: |
| 666 |
if warn: |
| 667 |
warnings.warn( |
| 668 |
"Sinkhorn did not converge. You might want to " |
| 669 |
"increase the number of iterations `numItermax` " |
| 670 |
"or the regularization parameter `reg`." |
| 671 |
) |
| 672 |
if log: |
| 673 |
log["niter"] = ii |
| 674 |
log["u"] = u |
| 675 |
log["v"] = v |
| 676 |
|
| 677 |
if n_hists: |
| 678 |
res = nx.einsum("ik,ij,jk,ij->k", u, K, v, M) |
| 679 |
if log: |
| 680 |
return res, log |
| 681 |
else: |
| 682 |
return res |
| 683 |
|
| 684 |
else: |
| 685 |
if log: |
| 686 |
return u.reshape((-1, 1)) * K * v.reshape((1, -1)), log |
| 687 |
else: |
| 688 |
return u.reshape((-1, 1)) * K * v.reshape((1, -1)) |
| 689 |
|
| 690 |
|
| 691 |
def sinkhorn_log( |
| 692 |
a, |
| 693 |
b, |
| 694 |
M, |
| 695 |
reg, |
| 696 |
numItermax=1000, |
| 697 |
stopThr=1e-9, |
| 698 |
verbose=False, |
| 699 |
log=False, |
| 700 |
warn=True, |
| 701 |
warmstart=None, |
| 702 |
**kwargs, |
| 703 |
): |
| 704 |
r""" |
| 705 |
Solve the entropic regularization optimal transport problem in log space |
| 706 |
and return the OT matrix |
| 707 |
|
| 708 |
The function solves the following optimization problem: |
| 709 |
|
| 710 |
.. math:: |
| 711 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 712 |
\mathrm{reg}\cdot\Omega(\gamma) |
| 713 |
|
| 714 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 715 |
|
| 716 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 717 |
|
| 718 |
\gamma &\geq 0 |
| 719 |
|
| 720 |
where : |
| 721 |
|
| 722 |
- :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix |
| 723 |
- :math:`\Omega` is the entropic regularization term |
| 724 |
:math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 725 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (histograms, both sum to 1) |
| 726 |
|
| 727 |
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix |
| 728 |
scaling algorithm :ref:`[2] <references-sinkhorn-log>` with the |
| 729 |
implementation from :ref:`[34] <references-sinkhorn-log>` |
| 730 |
|
| 731 |
|
| 732 |
Parameters |
| 733 |
---------- |
| 734 |
a : array-like, shape (dim_a,) |
| 735 |
samples weights in the source domain |
| 736 |
b : array-like, shape (dim_b,) or array-like, shape (dim_b, n_hists) |
| 737 |
samples in the target domain, compute sinkhorn with multiple targets |
| 738 |
and fixed :math:`\mathbf{M}` if :math:`\mathbf{b}` is a matrix (return OT loss + dual variables in log) |
| 739 |
M : array-like, shape (dim_a, dim_b) |
| 740 |
loss matrix |
| 741 |
reg : float |
| 742 |
Regularization term >0 |
| 743 |
numItermax : int, optional |
| 744 |
Max number of iterations |
| 745 |
stopThr : float, optional |
| 746 |
Stop threshold on error (>0) |
| 747 |
verbose : bool, optional |
| 748 |
Print information along iterations |
| 749 |
log : bool, optional |
| 750 |
record log if True |
| 751 |
warn : bool, optional |
| 752 |
if True, raises a warning if the algorithm doesn't convergence. |
| 753 |
warmstart: tuple of arrays, shape (dim_a, dim_b), optional |
| 754 |
Initialization of dual potentials. If provided, the dual potentials should be given |
| 755 |
(that is the logarithm of the u,v sinkhorn scaling vectors) |
| 756 |
|
| 757 |
Returns |
| 758 |
------- |
| 759 |
gamma : array-like, shape (dim_a, dim_b) |
| 760 |
Optimal transportation matrix for the given parameters |
| 761 |
log : dict |
| 762 |
log dictionary return only if log==True in parameters |
| 763 |
|
| 764 |
Examples |
| 765 |
-------- |
| 766 |
|
| 767 |
>>> import ot |
| 768 |
>>> a=[.5, .5] |
| 769 |
>>> b=[.5, .5] |
| 770 |
>>> M=[[0., 1.], [1., 0.]] |
| 771 |
>>> ot.sinkhorn(a, b, M, 1) |
| 772 |
array([[0.36552929, 0.13447071], |
| 773 |
[0.13447071, 0.36552929]]) |
| 774 |
|
| 775 |
|
| 776 |
.. _references-sinkhorn-log: |
| 777 |
References |
| 778 |
---------- |
| 779 |
|
| 780 |
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of |
| 781 |
Optimal Transport, Advances in Neural Information Processing |
| 782 |
Systems (NIPS) 26, 2013 |
| 783 |
|
| 784 |
.. [34] Feydy, J., Séjourné, T., Vialard, F. X., Amari, S. I., |
| 785 |
Trouvé, A., & Peyré, G. (2019, April). Interpolating between |
| 786 |
optimal transport and MMD using Sinkhorn divergences. In The |
| 787 |
22nd International Conference on Artificial Intelligence and |
| 788 |
Statistics (pp. 2681-2690). PMLR. |
| 789 |
|
| 790 |
|
| 791 |
See Also |
| 792 |
-------- |
| 793 |
ot.lp.emd : Unregularized OT |
| 794 |
ot.optim.cg : General regularized OT |
| 795 |
|
| 796 |
""" |
| 797 |
|
| 798 |
a, b, M = list_to_array(a, b, M) |
| 799 |
|
| 800 |
nx = get_backend(M, a, b) |
| 801 |
|
| 802 |
if len(a) == 0: |
| 803 |
a = nx.full((M.shape[0],), 1.0 / M.shape[0], type_as=M) |
| 804 |
if len(b) == 0: |
| 805 |
b = nx.full((M.shape[1],), 1.0 / M.shape[1], type_as=M) |
| 806 |
|
| 807 |
|
| 808 |
dim_a = len(a) |
| 809 |
dim_b = b.shape[0] |
| 810 |
|
| 811 |
if len(b.shape) > 1: |
| 812 |
n_hists = b.shape[1] |
| 813 |
else: |
| 814 |
n_hists = 0 |
| 815 |
|
| 816 |
|
| 817 |
if n_hists > 1 and warmstart is None: |
| 818 |
warmstart = [None] * n_hists |
| 819 |
|
| 820 |
if n_hists: |
| 821 |
lst_loss = [] |
| 822 |
lst_u = [] |
| 823 |
lst_v = [] |
| 824 |
|
| 825 |
for k in range(n_hists): |
| 826 |
res = sinkhorn_log( |
| 827 |
a, |
| 828 |
b[:, k], |
| 829 |
M, |
| 830 |
reg, |
| 831 |
numItermax=numItermax, |
| 832 |
stopThr=stopThr, |
| 833 |
verbose=verbose, |
| 834 |
log=log, |
| 835 |
warmstart=warmstart[k], |
| 836 |
**kwargs, |
| 837 |
) |
| 838 |
|
| 839 |
if log: |
| 840 |
lst_loss.append(nx.sum(M * res[0])) |
| 841 |
lst_u.append(res[1]["log_u"]) |
| 842 |
lst_v.append(res[1]["log_v"]) |
| 843 |
else: |
| 844 |
lst_loss.append(nx.sum(M * res)) |
| 845 |
res = nx.stack(lst_loss) |
| 846 |
if log: |
| 847 |
log = { |
| 848 |
"log_u": nx.stack(lst_u, 1), |
| 849 |
"log_v": nx.stack(lst_v, 1), |
| 850 |
} |
| 851 |
log["u"] = nx.exp(log["log_u"]) |
| 852 |
log["v"] = nx.exp(log["log_v"]) |
| 853 |
return res, log |
| 854 |
else: |
| 855 |
return res |
| 856 |
|
| 857 |
else: |
| 858 |
if log: |
| 859 |
log = {"err": []} |
| 860 |
|
| 861 |
Mr = -M / reg |
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
if warmstart is None: |
| 866 |
u = nx.zeros(dim_a, type_as=M) |
| 867 |
v = nx.zeros(dim_b, type_as=M) |
| 868 |
else: |
| 869 |
u, v = warmstart |
| 870 |
|
| 871 |
def get_logT(u, v): |
| 872 |
if n_hists: |
| 873 |
return Mr[:, :, None] + u + v |
| 874 |
else: |
| 875 |
return Mr + u[:, None] + v[None, :] |
| 876 |
|
| 877 |
loga = nx.log(a) |
| 878 |
logb = nx.log(b) |
| 879 |
|
| 880 |
err = 1 |
| 881 |
for ii in range(numItermax): |
| 882 |
v = logb - nx.logsumexp(Mr + u[:, None], 0) |
| 883 |
u = loga - nx.logsumexp(Mr + v[None, :], 1) |
| 884 |
|
| 885 |
if ii % 10 == 0: |
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
tmp2 = nx.sum(nx.exp(get_logT(u, v)), 0) |
| 891 |
err = nx.norm(tmp2 - b) |
| 892 |
if log: |
| 893 |
log["err"].append(err) |
| 894 |
|
| 895 |
if verbose: |
| 896 |
if ii % 200 == 0: |
| 897 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 898 |
print("{:5d}|{:8e}|".format(ii, err)) |
| 899 |
if err < stopThr: |
| 900 |
break |
| 901 |
else: |
| 902 |
if warn: |
| 903 |
warnings.warn( |
| 904 |
"Sinkhorn did not converge. You might want to " |
| 905 |
"increase the number of iterations `numItermax` " |
| 906 |
"or the regularization parameter `reg`." |
| 907 |
) |
| 908 |
|
| 909 |
if log: |
| 910 |
log["niter"] = ii |
| 911 |
log["log_u"] = u |
| 912 |
log["log_v"] = v |
| 913 |
log["u"] = nx.exp(u) |
| 914 |
log["v"] = nx.exp(v) |
| 915 |
|
| 916 |
return nx.exp(get_logT(u, v)), log |
| 917 |
|
| 918 |
else: |
| 919 |
return nx.exp(get_logT(u, v)) |
| 920 |
|
| 921 |
|
| 922 |
def greenkhorn( |
| 923 |
a, |
| 924 |
b, |
| 925 |
M, |
| 926 |
reg, |
| 927 |
numItermax=10000, |
| 928 |
stopThr=1e-9, |
| 929 |
verbose=False, |
| 930 |
log=False, |
| 931 |
warn=True, |
| 932 |
warmstart=None, |
| 933 |
): |
| 934 |
r""" |
| 935 |
Solve the entropic regularization optimal transport problem and return the OT matrix |
| 936 |
|
| 937 |
The algorithm used is based on the paper :ref:`[22] <references-greenkhorn>` |
| 938 |
which is a stochastic version of the Sinkhorn-Knopp |
| 939 |
algorithm :ref:`[2] <references-greenkhorn>` |
| 940 |
|
| 941 |
The function solves the following optimization problem: |
| 942 |
|
| 943 |
.. math:: |
| 944 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 945 |
\mathrm{reg}\cdot\Omega(\gamma) |
| 946 |
|
| 947 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 948 |
|
| 949 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 950 |
|
| 951 |
\gamma &\geq 0 |
| 952 |
|
| 953 |
where : |
| 954 |
|
| 955 |
- :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix |
| 956 |
- :math:`\Omega` is the entropic regularization term |
| 957 |
:math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 958 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target |
| 959 |
weights (histograms, both sum to 1) |
| 960 |
|
| 961 |
|
| 962 |
Parameters |
| 963 |
---------- |
| 964 |
a : array-like, shape (dim_a,) |
| 965 |
samples weights in the source domain |
| 966 |
b : array-like, shape (dim_b,) or array-like, shape (dim_b, n_hists) |
| 967 |
samples in the target domain, compute sinkhorn with multiple targets |
| 968 |
and fixed :math:`\mathbf{M}` if :math:`\mathbf{b}` is a matrix |
| 969 |
(return OT loss + dual variables in log) |
| 970 |
M : array-like, shape (dim_a, dim_b) |
| 971 |
loss matrix |
| 972 |
reg : float |
| 973 |
Regularization term >0 |
| 974 |
numItermax : int, optional |
| 975 |
Max number of iterations |
| 976 |
stopThr : float, optional |
| 977 |
Stop threshold on error (>0) |
| 978 |
log : bool, optional |
| 979 |
record log if True |
| 980 |
warn : bool, optional |
| 981 |
if True, raises a warning if the algorithm doesn't convergence. |
| 982 |
warmstart: tuple of arrays, shape (dim_a, dim_b), optional |
| 983 |
Initialization of dual potentials. If provided, the dual potentials should be given |
| 984 |
(that is the logarithm of the u,v sinkhorn scaling vectors) |
| 985 |
|
| 986 |
Returns |
| 987 |
------- |
| 988 |
gamma : array-like, shape (dim_a, dim_b) |
| 989 |
Optimal transportation matrix for the given parameters |
| 990 |
log : dict |
| 991 |
log dictionary return only if log==True in parameters |
| 992 |
|
| 993 |
Examples |
| 994 |
-------- |
| 995 |
|
| 996 |
>>> import ot |
| 997 |
>>> a=[.5, .5] |
| 998 |
>>> b=[.5, .5] |
| 999 |
>>> M=[[0., 1.], [1., 0.]] |
| 1000 |
>>> ot.bregman.greenkhorn(a, b, M, 1) |
| 1001 |
array([[0.36552929, 0.13447071], |
| 1002 |
[0.13447071, 0.36552929]]) |
| 1003 |
|
| 1004 |
|
| 1005 |
.. _references-greenkhorn: |
| 1006 |
References |
| 1007 |
---------- |
| 1008 |
|
| 1009 |
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation |
| 1010 |
of Optimal Transport, Advances in Neural Information |
| 1011 |
Processing Systems (NIPS) 26, 2013 |
| 1012 |
|
| 1013 |
.. [22] J. Altschuler, J.Weed, P. Rigollet : Near-linear time |
| 1014 |
approximation algorithms for optimal transport via Sinkhorn |
| 1015 |
iteration, Advances in Neural Information Processing |
| 1016 |
Systems (NIPS) 31, 2017 |
| 1017 |
|
| 1018 |
|
| 1019 |
See Also |
| 1020 |
-------- |
| 1021 |
ot.lp.emd : Unregularized OT |
| 1022 |
ot.optim.cg : General regularized OT |
| 1023 |
|
| 1024 |
""" |
| 1025 |
|
| 1026 |
a, b, M = list_to_array(a, b, M) |
| 1027 |
|
| 1028 |
nx = get_backend(M, a, b) |
| 1029 |
if nx.__name__ in ("jax", "tf"): |
| 1030 |
raise TypeError( |
| 1031 |
"JAX or TF arrays have been received. Greenkhorn is not " |
| 1032 |
"compatible with neither JAX nor TF" |
| 1033 |
) |
| 1034 |
|
| 1035 |
if len(a) == 0: |
| 1036 |
a = nx.ones((M.shape[0],), type_as=M) / M.shape[0] |
| 1037 |
if len(b) == 0: |
| 1038 |
b = nx.ones((M.shape[1],), type_as=M) / M.shape[1] |
| 1039 |
|
| 1040 |
dim_a = a.shape[0] |
| 1041 |
dim_b = b.shape[0] |
| 1042 |
|
| 1043 |
K = nx.exp(-M / reg) |
| 1044 |
|
| 1045 |
if warmstart is None: |
| 1046 |
u = nx.full((dim_a,), 1.0 / dim_a, type_as=K) |
| 1047 |
v = nx.full((dim_b,), 1.0 / dim_b, type_as=K) |
| 1048 |
else: |
| 1049 |
u, v = nx.exp(warmstart[0]), nx.exp(warmstart[1]) |
| 1050 |
G = u[:, None] * K * v[None, :] |
| 1051 |
|
| 1052 |
viol = nx.sum(G, axis=1) - a |
| 1053 |
viol_2 = nx.sum(G, axis=0) - b |
| 1054 |
stopThr_val = 1 |
| 1055 |
if log: |
| 1056 |
log = dict() |
| 1057 |
log["u"] = u |
| 1058 |
log["v"] = v |
| 1059 |
|
| 1060 |
for ii in range(numItermax): |
| 1061 |
i_1 = nx.argmax(nx.abs(viol)) |
| 1062 |
i_2 = nx.argmax(nx.abs(viol_2)) |
| 1063 |
m_viol_1 = nx.abs(viol[i_1]) |
| 1064 |
m_viol_2 = nx.abs(viol_2[i_2]) |
| 1065 |
stopThr_val = nx.maximum(m_viol_1, m_viol_2) |
| 1066 |
|
| 1067 |
if m_viol_1 > m_viol_2: |
| 1068 |
old_u = u[i_1] |
| 1069 |
new_u = a[i_1] / nx.dot(K[i_1, :], v) |
| 1070 |
G[i_1, :] = new_u * K[i_1, :] * v |
| 1071 |
|
| 1072 |
viol[i_1] = nx.dot(new_u * K[i_1, :], v) - a[i_1] |
| 1073 |
viol_2 += K[i_1, :].T * (new_u - old_u) * v |
| 1074 |
u[i_1] = new_u |
| 1075 |
else: |
| 1076 |
old_v = v[i_2] |
| 1077 |
new_v = b[i_2] / nx.dot(K[:, i_2].T, u) |
| 1078 |
G[:, i_2] = u * K[:, i_2] * new_v |
| 1079 |
|
| 1080 |
|
| 1081 |
viol += (-old_v + new_v) * K[:, i_2] * u |
| 1082 |
viol_2[i_2] = new_v * nx.dot(K[:, i_2], u) - b[i_2] |
| 1083 |
v[i_2] = new_v |
| 1084 |
|
| 1085 |
if stopThr_val <= stopThr: |
| 1086 |
break |
| 1087 |
else: |
| 1088 |
if warn: |
| 1089 |
warnings.warn( |
| 1090 |
"Sinkhorn did not converge. You might want to " |
| 1091 |
"increase the number of iterations `numItermax` " |
| 1092 |
"or the regularization parameter `reg`." |
| 1093 |
) |
| 1094 |
|
| 1095 |
if log: |
| 1096 |
log["n_iter"] = ii |
| 1097 |
log["u"] = u |
| 1098 |
log["v"] = v |
| 1099 |
|
| 1100 |
if log: |
| 1101 |
return G, log |
| 1102 |
else: |
| 1103 |
return G |
| 1104 |
|
| 1105 |
|
| 1106 |
def sinkhorn_stabilized( |
| 1107 |
a, |
| 1108 |
b, |
| 1109 |
M, |
| 1110 |
reg, |
| 1111 |
numItermax=1000, |
| 1112 |
tau=1e3, |
| 1113 |
stopThr=1e-9, |
| 1114 |
warmstart=None, |
| 1115 |
verbose=False, |
| 1116 |
print_period=20, |
| 1117 |
log=False, |
| 1118 |
warn=True, |
| 1119 |
**kwargs, |
| 1120 |
): |
| 1121 |
r""" |
| 1122 |
Solve the entropic regularization OT problem with log stabilization |
| 1123 |
|
| 1124 |
The function solves the following optimization problem: |
| 1125 |
|
| 1126 |
.. math:: |
| 1127 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 1128 |
\mathrm{reg}\cdot\Omega(\gamma) |
| 1129 |
|
| 1130 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 1131 |
|
| 1132 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 1133 |
|
| 1134 |
\gamma &\geq 0 |
| 1135 |
|
| 1136 |
where : |
| 1137 |
|
| 1138 |
- :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix |
| 1139 |
- :math:`\Omega` is the entropic regularization term |
| 1140 |
:math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 1141 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target |
| 1142 |
weights (histograms, both sum to 1) |
| 1143 |
|
| 1144 |
|
| 1145 |
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix |
| 1146 |
scaling algorithm as proposed in :ref:`[2] <references-sinkhorn-stabilized>` |
| 1147 |
but with the log stabilization |
| 1148 |
proposed in :ref:`[10] <references-sinkhorn-stabilized>` an defined in |
| 1149 |
:ref:`[9] <references-sinkhorn-stabilized>` (Algo 3.1) . |
| 1150 |
|
| 1151 |
|
| 1152 |
Parameters |
| 1153 |
---------- |
| 1154 |
a : array-like, shape (dim_a,) |
| 1155 |
samples weights in the source domain |
| 1156 |
b : array-like, shape (dim_b,) |
| 1157 |
samples in the target domain |
| 1158 |
M : array-like, shape (dim_a, dim_b) |
| 1159 |
loss matrix |
| 1160 |
reg : float |
| 1161 |
Regularization term >0 |
| 1162 |
tau : float |
| 1163 |
threshold for max value in :math:`\mathbf{u}` or :math:`\mathbf{v}` |
| 1164 |
for log scaling |
| 1165 |
warmstart : table of vectors |
| 1166 |
if given then starting values for alpha and beta log scalings |
| 1167 |
numItermax : int, optional |
| 1168 |
Max number of iterations |
| 1169 |
stopThr : float, optional |
| 1170 |
Stop threshold on error (>0) |
| 1171 |
verbose : bool, optional |
| 1172 |
Print information along iterations |
| 1173 |
log : bool, optional |
| 1174 |
record log if True |
| 1175 |
warn : bool, optional |
| 1176 |
if True, raises a warning if the algorithm doesn't convergence. |
| 1177 |
|
| 1178 |
Returns |
| 1179 |
------- |
| 1180 |
gamma : array-like, shape (dim_a, dim_b) |
| 1181 |
Optimal transportation matrix for the given parameters |
| 1182 |
log : dict |
| 1183 |
log dictionary return only if log==True in parameters |
| 1184 |
|
| 1185 |
Examples |
| 1186 |
-------- |
| 1187 |
|
| 1188 |
>>> import ot |
| 1189 |
>>> a=[.5,.5] |
| 1190 |
>>> b=[.5,.5] |
| 1191 |
>>> M=[[0.,1.],[1.,0.]] |
| 1192 |
>>> ot.bregman.sinkhorn_stabilized(a, b, M, 1) |
| 1193 |
array([[0.36552929, 0.13447071], |
| 1194 |
[0.13447071, 0.36552929]]) |
| 1195 |
|
| 1196 |
|
| 1197 |
.. _references-sinkhorn-stabilized: |
| 1198 |
References |
| 1199 |
---------- |
| 1200 |
|
| 1201 |
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of |
| 1202 |
Optimal Transport, Advances in Neural Information Processing |
| 1203 |
Systems (NIPS) 26, 2013 |
| 1204 |
|
| 1205 |
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms |
| 1206 |
for Entropy Regularized Transport Problems. |
| 1207 |
arXiv preprint arXiv:1610.06519. |
| 1208 |
|
| 1209 |
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). |
| 1210 |
Scaling algorithms for unbalanced transport problems. |
| 1211 |
arXiv preprint arXiv:1607.05816. |
| 1212 |
|
| 1213 |
|
| 1214 |
See Also |
| 1215 |
-------- |
| 1216 |
ot.lp.emd : Unregularized OT |
| 1217 |
ot.optim.cg : General regularized OT |
| 1218 |
|
| 1219 |
""" |
| 1220 |
|
| 1221 |
a, b, M = list_to_array(a, b, M) |
| 1222 |
|
| 1223 |
nx = get_backend(M, a, b) |
| 1224 |
|
| 1225 |
if len(a) == 0: |
| 1226 |
a = nx.ones((M.shape[0],), type_as=M) / M.shape[0] |
| 1227 |
if len(b) == 0: |
| 1228 |
b = nx.ones((M.shape[1],), type_as=M) / M.shape[1] |
| 1229 |
|
| 1230 |
|
| 1231 |
if len(b.shape) > 1: |
| 1232 |
n_hists = b.shape[1] |
| 1233 |
a = a[:, None] |
| 1234 |
else: |
| 1235 |
n_hists = 0 |
| 1236 |
|
| 1237 |
|
| 1238 |
dim_a = len(a) |
| 1239 |
dim_b = len(b) |
| 1240 |
|
| 1241 |
if log: |
| 1242 |
log = {"err": []} |
| 1243 |
|
| 1244 |
|
| 1245 |
|
| 1246 |
if warmstart is None: |
| 1247 |
alpha, beta = nx.zeros(dim_a, type_as=M), nx.zeros(dim_b, type_as=M) |
| 1248 |
else: |
| 1249 |
alpha, beta = warmstart |
| 1250 |
|
| 1251 |
if n_hists: |
| 1252 |
u = nx.ones((dim_a, n_hists), type_as=M) / dim_a |
| 1253 |
v = nx.ones((dim_b, n_hists), type_as=M) / dim_b |
| 1254 |
else: |
| 1255 |
u, v = nx.ones(dim_a, type_as=M), nx.ones(dim_b, type_as=M) |
| 1256 |
u /= dim_a |
| 1257 |
v /= dim_b |
| 1258 |
|
| 1259 |
def get_K(alpha, beta): |
| 1260 |
"""log space computation""" |
| 1261 |
return nx.exp(-(M - alpha.reshape((dim_a, 1)) - beta.reshape((1, dim_b))) / reg) |
| 1262 |
|
| 1263 |
def get_Gamma(alpha, beta, u, v): |
| 1264 |
"""log space gamma computation""" |
| 1265 |
return nx.exp( |
| 1266 |
-(M - alpha.reshape((dim_a, 1)) - beta.reshape((1, dim_b))) / reg |
| 1267 |
+ nx.log(u.reshape((dim_a, 1))) |
| 1268 |
+ nx.log(v.reshape((1, dim_b))) |
| 1269 |
) |
| 1270 |
|
| 1271 |
K = get_K(alpha, beta) |
| 1272 |
transp = K |
| 1273 |
err = 1 |
| 1274 |
for ii in range(numItermax): |
| 1275 |
uprev = u |
| 1276 |
vprev = v |
| 1277 |
|
| 1278 |
|
| 1279 |
v = b / (nx.dot(K.T, u)) |
| 1280 |
u = a / (nx.dot(K, v)) |
| 1281 |
|
| 1282 |
|
| 1283 |
if nx.max(nx.abs(u)) > tau or nx.max(nx.abs(v)) > tau: |
| 1284 |
if n_hists: |
| 1285 |
alpha, beta = ( |
| 1286 |
alpha + reg * nx.max(nx.log(u), 1), |
| 1287 |
beta + reg * nx.max(nx.log(v)), |
| 1288 |
) |
| 1289 |
else: |
| 1290 |
alpha, beta = alpha + reg * nx.log(u), beta + reg * nx.log(v) |
| 1291 |
if n_hists: |
| 1292 |
u = nx.ones((dim_a, n_hists), type_as=M) / dim_a |
| 1293 |
v = nx.ones((dim_b, n_hists), type_as=M) / dim_b |
| 1294 |
else: |
| 1295 |
u = nx.ones(dim_a, type_as=M) / dim_a |
| 1296 |
v = nx.ones(dim_b, type_as=M) / dim_b |
| 1297 |
K = get_K(alpha, beta) |
| 1298 |
|
| 1299 |
if ii % print_period == 0: |
| 1300 |
|
| 1301 |
|
| 1302 |
if n_hists: |
| 1303 |
err_u = nx.max(nx.abs(u - uprev)) |
| 1304 |
err_u /= max(nx.max(nx.abs(u)), nx.max(nx.abs(uprev)), 1.0) |
| 1305 |
err_v = nx.max(nx.abs(v - vprev)) |
| 1306 |
err_v /= max(nx.max(nx.abs(v)), nx.max(nx.abs(vprev)), 1.0) |
| 1307 |
err = 0.5 * (err_u + err_v) |
| 1308 |
else: |
| 1309 |
transp = get_Gamma(alpha, beta, u, v) |
| 1310 |
err = nx.norm(nx.sum(transp, axis=0) - b) |
| 1311 |
if log: |
| 1312 |
log["err"].append(err) |
| 1313 |
|
| 1314 |
if verbose: |
| 1315 |
if ii % (print_period * 20) == 0: |
| 1316 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1317 |
print("{:5d}|{:8e}|".format(ii, err)) |
| 1318 |
|
| 1319 |
if err <= stopThr: |
| 1320 |
break |
| 1321 |
|
| 1322 |
if nx.any(nx.isnan(u)) or nx.any(nx.isnan(v)): |
| 1323 |
|
| 1324 |
|
| 1325 |
warnings.warn("Numerical errors at iteration %d" % ii) |
| 1326 |
u = uprev |
| 1327 |
v = vprev |
| 1328 |
break |
| 1329 |
else: |
| 1330 |
if warn: |
| 1331 |
warnings.warn( |
| 1332 |
"Sinkhorn did not converge. You might want to " |
| 1333 |
"increase the number of iterations `numItermax` " |
| 1334 |
"or the regularization parameter `reg`." |
| 1335 |
) |
| 1336 |
if log: |
| 1337 |
if n_hists: |
| 1338 |
alpha = alpha[:, None] |
| 1339 |
beta = beta[:, None] |
| 1340 |
logu = alpha / reg + nx.log(u) |
| 1341 |
logv = beta / reg + nx.log(v) |
| 1342 |
log["n_iter"] = ii |
| 1343 |
log["logu"] = logu |
| 1344 |
log["logv"] = logv |
| 1345 |
log["alpha"] = alpha + reg * nx.log(u) |
| 1346 |
log["beta"] = beta + reg * nx.log(v) |
| 1347 |
log["warmstart"] = (log["alpha"], log["beta"]) |
| 1348 |
if n_hists: |
| 1349 |
res = nx.stack( |
| 1350 |
[ |
| 1351 |
nx.sum(get_Gamma(alpha, beta, u[:, i], v[:, i]) * M) |
| 1352 |
for i in range(n_hists) |
| 1353 |
] |
| 1354 |
) |
| 1355 |
return res, log |
| 1356 |
|
| 1357 |
else: |
| 1358 |
return get_Gamma(alpha, beta, u, v), log |
| 1359 |
else: |
| 1360 |
if n_hists: |
| 1361 |
res = nx.stack( |
| 1362 |
[ |
| 1363 |
nx.sum(get_Gamma(alpha, beta, u[:, i], v[:, i]) * M) |
| 1364 |
for i in range(n_hists) |
| 1365 |
] |
| 1366 |
) |
| 1367 |
return res |
| 1368 |
else: |
| 1369 |
return get_Gamma(alpha, beta, u, v) |
| 1370 |
|
| 1371 |
|
| 1372 |
def sinkhorn_epsilon_scaling( |
| 1373 |
a, |
| 1374 |
b, |
| 1375 |
M, |
| 1376 |
reg, |
| 1377 |
numItermax=100, |
| 1378 |
epsilon0=1e4, |
| 1379 |
numInnerItermax=100, |
| 1380 |
tau=1e3, |
| 1381 |
stopThr=1e-9, |
| 1382 |
warmstart=None, |
| 1383 |
verbose=False, |
| 1384 |
print_period=10, |
| 1385 |
log=False, |
| 1386 |
warn=True, |
| 1387 |
**kwargs, |
| 1388 |
): |
| 1389 |
r""" |
| 1390 |
Solve the entropic regularization optimal transport problem with log |
| 1391 |
stabilization and epsilon scaling. |
| 1392 |
The function solves the following optimization problem: |
| 1393 |
|
| 1394 |
.. math:: |
| 1395 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 1396 |
\mathrm{reg}\cdot\Omega(\gamma) |
| 1397 |
|
| 1398 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 1399 |
|
| 1400 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 1401 |
|
| 1402 |
\gamma &\geq 0 |
| 1403 |
|
| 1404 |
where : |
| 1405 |
|
| 1406 |
- :math:`\mathbf{M}` is the (`dim_a`, `dim_b`) metric cost matrix |
| 1407 |
- :math:`\Omega` is the entropic regularization term |
| 1408 |
:math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 1409 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (histograms, both sum to 1) |
| 1410 |
|
| 1411 |
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix |
| 1412 |
scaling algorithm as proposed in :ref:`[2] <references-sinkhorn-epsilon-scaling>` |
| 1413 |
but with the log stabilization |
| 1414 |
proposed in :ref:`[10] <references-sinkhorn-epsilon-scaling>` and the log scaling |
| 1415 |
proposed in :ref:`[9] <references-sinkhorn-epsilon-scaling>` algorithm 3.2 |
| 1416 |
|
| 1417 |
Parameters |
| 1418 |
---------- |
| 1419 |
a : array-like, shape (dim_a,) |
| 1420 |
samples weights in the source domain |
| 1421 |
b : array-like, shape (dim_b,) |
| 1422 |
samples in the target domain |
| 1423 |
M : array-like, shape (dim_a, dim_b) |
| 1424 |
loss matrix |
| 1425 |
reg : float |
| 1426 |
Regularization term >0 |
| 1427 |
tau : float |
| 1428 |
threshold for max value in :math:`\mathbf{u}` or :math:`\mathbf{b}` |
| 1429 |
for log scaling |
| 1430 |
warmstart : tuple of vectors |
| 1431 |
if given then starting values for alpha and beta log scalings |
| 1432 |
numItermax : int, optional |
| 1433 |
Max number of iterations |
| 1434 |
numInnerItermax : int, optional |
| 1435 |
Max number of iterations in the inner slog stabilized sinkhorn |
| 1436 |
epsilon0 : int, optional |
| 1437 |
first epsilon regularization value (then exponential decrease to reg) |
| 1438 |
stopThr : float, optional |
| 1439 |
Stop threshold on error (>0) |
| 1440 |
verbose : bool, optional |
| 1441 |
Print information along iterations |
| 1442 |
log : bool, optional |
| 1443 |
record log if True |
| 1444 |
warn : bool, optional |
| 1445 |
if True, raises a warning if the algorithm doesn't convergence. |
| 1446 |
|
| 1447 |
Returns |
| 1448 |
------- |
| 1449 |
gamma : array-like, shape (dim_a, dim_b) |
| 1450 |
Optimal transportation matrix for the given parameters |
| 1451 |
log : dict |
| 1452 |
log dictionary return only if log==True in parameters |
| 1453 |
Examples |
| 1454 |
-------- |
| 1455 |
>>> import ot |
| 1456 |
>>> a=[.5, .5] |
| 1457 |
>>> b=[.5, .5] |
| 1458 |
>>> M=[[0., 1.], [1., 0.]] |
| 1459 |
>>> ot.bregman.sinkhorn_epsilon_scaling(a, b, M, 1) |
| 1460 |
array([[0.36552929, 0.13447071], |
| 1461 |
[0.13447071, 0.36552929]]) |
| 1462 |
|
| 1463 |
.. _references-sinkhorn-epsilon-scaling: |
| 1464 |
References |
| 1465 |
---------- |
| 1466 |
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal |
| 1467 |
Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 |
| 1468 |
|
| 1469 |
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for |
| 1470 |
Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. |
| 1471 |
|
| 1472 |
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). |
| 1473 |
Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. |
| 1474 |
|
| 1475 |
See Also |
| 1476 |
-------- |
| 1477 |
ot.lp.emd : Unregularized OT |
| 1478 |
ot.optim.cg : General regularized OT |
| 1479 |
""" |
| 1480 |
|
| 1481 |
a, b, M = list_to_array(a, b, M) |
| 1482 |
|
| 1483 |
nx = get_backend(M, a, b) |
| 1484 |
|
| 1485 |
if len(a) == 0: |
| 1486 |
a = nx.ones((M.shape[0],), type_as=M) / M.shape[0] |
| 1487 |
if len(b) == 0: |
| 1488 |
b = nx.ones((M.shape[1],), type_as=M) / M.shape[1] |
| 1489 |
|
| 1490 |
|
| 1491 |
dim_a = len(a) |
| 1492 |
dim_b = len(b) |
| 1493 |
|
| 1494 |
|
| 1495 |
numItermin = 35 |
| 1496 |
numItermax = max(numItermin, numItermax) |
| 1497 |
|
| 1498 |
ii = 0 |
| 1499 |
if log: |
| 1500 |
log = {"err": []} |
| 1501 |
|
| 1502 |
|
| 1503 |
|
| 1504 |
if warmstart is None: |
| 1505 |
alpha, beta = nx.zeros(dim_a, type_as=M), nx.zeros(dim_b, type_as=M) |
| 1506 |
else: |
| 1507 |
alpha, beta = warmstart |
| 1508 |
|
| 1509 |
|
| 1510 |
def get_reg(n): |
| 1511 |
return (epsilon0 - reg) * np.exp(-n) + reg |
| 1512 |
|
| 1513 |
err = 1 |
| 1514 |
for ii in range(numItermax): |
| 1515 |
regi = get_reg(ii) |
| 1516 |
|
| 1517 |
G, logi = sinkhorn_stabilized( |
| 1518 |
a, |
| 1519 |
b, |
| 1520 |
M, |
| 1521 |
regi, |
| 1522 |
numItermax=numInnerItermax, |
| 1523 |
stopThr=stopThr, |
| 1524 |
warmstart=(alpha, beta), |
| 1525 |
verbose=False, |
| 1526 |
print_period=20, |
| 1527 |
tau=tau, |
| 1528 |
log=True, |
| 1529 |
) |
| 1530 |
|
| 1531 |
alpha = logi["alpha"] |
| 1532 |
beta = logi["beta"] |
| 1533 |
|
| 1534 |
if ii % (print_period) == 0: |
| 1535 |
|
| 1536 |
|
| 1537 |
transp = G |
| 1538 |
err = ( |
| 1539 |
nx.norm(nx.sum(transp, axis=0) - b) ** 2 |
| 1540 |
+ nx.norm(nx.sum(transp, axis=1) - a) ** 2 |
| 1541 |
) |
| 1542 |
if log: |
| 1543 |
log["err"].append(err) |
| 1544 |
|
| 1545 |
if verbose: |
| 1546 |
if ii % (print_period * 10) == 0: |
| 1547 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1548 |
print("{:5d}|{:8e}|".format(ii, err)) |
| 1549 |
|
| 1550 |
if err <= stopThr and ii > numItermin: |
| 1551 |
break |
| 1552 |
else: |
| 1553 |
if warn: |
| 1554 |
warnings.warn( |
| 1555 |
"Sinkhorn did not converge. You might want to " |
| 1556 |
"increase the number of iterations `numItermax` " |
| 1557 |
"or the regularization parameter `reg`." |
| 1558 |
) |
| 1559 |
if log: |
| 1560 |
log["alpha"] = alpha |
| 1561 |
log["beta"] = beta |
| 1562 |
log["warmstart"] = (log["alpha"], log["beta"]) |
| 1563 |
log["niter"] = ii |
| 1564 |
return G, log |
| 1565 |
else: |
| 1566 |
return G |