| 1 |
|
| 2 |
""" |
| 3 |
Generic solvers for regularized OT or its semi-relaxed version. |
| 4 |
""" |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
> |
| 9 |
|
| 10 |
|
| 11 |
import numpy as np |
| 12 |
import warnings |
| 13 |
from .lp import emd |
| 14 |
from .bregman import sinkhorn |
| 15 |
from .backend import get_backend |
| 16 |
|
| 17 |
with warnings.catch_warnings(): |
| 18 |
warnings.simplefilter("ignore") |
| 19 |
try: |
| 20 |
from scipy.optimize._linesearch import scalar_search_armijo |
| 21 |
except ModuleNotFoundError: |
| 22 |
|
| 23 |
from scipy.optimize.linesearch import scalar_search_armijo |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
def line_search_armijo( |
| 29 |
f, |
| 30 |
xk, |
| 31 |
pk, |
| 32 |
gfk, |
| 33 |
old_fval, |
| 34 |
args=(), |
| 35 |
c1=1e-4, |
| 36 |
alpha0=0.99, |
| 37 |
alpha_min=0.0, |
| 38 |
alpha_max=None, |
| 39 |
nx=None, |
| 40 |
**kwargs, |
| 41 |
): |
| 42 |
r""" |
| 43 |
Armijo linesearch function that works with matrices |
| 44 |
|
| 45 |
Find an approximate minimum of :math:`f(x_k + \alpha \cdot p_k)` that satisfies the |
| 46 |
armijo conditions. |
| 47 |
|
| 48 |
.. note:: If the loss function f returns a float (resp. a 1d array) then |
| 49 |
the returned alpha and fa are float (resp. 1d arrays). |
| 50 |
|
| 51 |
Parameters |
| 52 |
---------- |
| 53 |
f : callable |
| 54 |
loss function |
| 55 |
xk : array-like |
| 56 |
initial position |
| 57 |
pk : array-like |
| 58 |
descent direction |
| 59 |
gfk : array-like |
| 60 |
gradient of `f` at :math:`x_k` |
| 61 |
old_fval : float or 1d array |
| 62 |
loss value at :math:`x_k` |
| 63 |
args : tuple, optional |
| 64 |
arguments given to `f` |
| 65 |
c1 : float, optional |
| 66 |
:math:`c_1` const in armijo rule (>0) |
| 67 |
alpha0 : float, optional |
| 68 |
initial step (>0) |
| 69 |
alpha_min : float, default=0. |
| 70 |
minimum value for alpha |
| 71 |
alpha_max : float, optional |
| 72 |
maximum value for alpha |
| 73 |
nx : backend, optional |
| 74 |
If let to its default value None, a backend test will be conducted. |
| 75 |
Returns |
| 76 |
------- |
| 77 |
alpha : float or 1d array |
| 78 |
step that satisfy armijo conditions |
| 79 |
fc : int |
| 80 |
nb of function call |
| 81 |
fa : float or 1d array |
| 82 |
loss value at step alpha |
| 83 |
|
| 84 |
""" |
| 85 |
if nx is None: |
| 86 |
xk0, pk0 = xk, pk |
| 87 |
nx = get_backend(xk0, pk0) |
| 88 |
else: |
| 89 |
xk0, pk0 = xk, pk |
| 90 |
|
| 91 |
if len(xk.shape) == 0: |
| 92 |
xk = nx.reshape(xk, (-1,)) |
| 93 |
|
| 94 |
xk = nx.to_numpy(xk) |
| 95 |
pk = nx.to_numpy(pk) |
| 96 |
gfk = nx.to_numpy(gfk) |
| 97 |
|
| 98 |
fc = [0] |
| 99 |
|
| 100 |
def phi(alpha1): |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
alpha1 = np.clip(alpha1, alpha_min, alpha_max) |
| 109 |
|
| 110 |
fc[0] += 1 |
| 111 |
alpha10 = nx.from_numpy(alpha1) |
| 112 |
fval = f(xk0 + alpha10 * pk0, *args) |
| 113 |
if isinstance(fval, float): |
| 114 |
|
| 115 |
return fval |
| 116 |
else: |
| 117 |
return nx.to_numpy(fval) |
| 118 |
|
| 119 |
if old_fval is None: |
| 120 |
phi0 = phi(0.0) |
| 121 |
elif isinstance(old_fval, float): |
| 122 |
|
| 123 |
phi0 = old_fval |
| 124 |
else: |
| 125 |
phi0 = nx.to_numpy(old_fval) |
| 126 |
|
| 127 |
derphi0 = np.sum(pk * gfk) |
| 128 |
alpha, phi1 = scalar_search_armijo( |
| 129 |
phi, phi0, derphi0, c1=c1, alpha0=alpha0, amin=alpha_min |
| 130 |
) |
| 131 |
|
| 132 |
if alpha is None: |
| 133 |
return 0.0, fc[0], nx.from_numpy(phi0, type_as=xk0) |
| 134 |
else: |
| 135 |
alpha = np.clip(alpha, alpha_min, alpha_max) |
| 136 |
return ( |
| 137 |
nx.from_numpy(alpha, type_as=xk0), |
| 138 |
fc[0], |
| 139 |
nx.from_numpy(phi1, type_as=xk0), |
| 140 |
) |
| 141 |
|
| 142 |
|
| 143 |
def generic_conditional_gradient( |
| 144 |
a, |
| 145 |
b, |
| 146 |
M, |
| 147 |
f, |
| 148 |
df, |
| 149 |
reg1, |
| 150 |
reg2, |
| 151 |
lp_solver, |
| 152 |
line_search, |
| 153 |
G0=None, |
| 154 |
numItermax=200, |
| 155 |
stopThr=1e-9, |
| 156 |
stopThr2=1e-9, |
| 157 |
verbose=False, |
| 158 |
log=False, |
| 159 |
nx=None, |
| 160 |
**kwargs, |
| 161 |
): |
| 162 |
r""" |
| 163 |
Solve the general regularized OT problem or its semi-relaxed version with |
| 164 |
conditional gradient or generalized conditional gradient depending on the |
| 165 |
provided linear program solver. |
| 166 |
|
| 167 |
The function solves the following optimization problem if set as a conditional gradient: |
| 168 |
|
| 169 |
.. math:: |
| 170 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 171 |
\mathrm{reg_1} \cdot f(\gamma) |
| 172 |
|
| 173 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 174 |
|
| 175 |
\gamma^T \mathbf{1} &= \mathbf{b} (optional constraint) |
| 176 |
|
| 177 |
\gamma &\geq 0 |
| 178 |
|
| 179 |
where : |
| 180 |
|
| 181 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix |
| 182 |
- :math:`f` is the regularization term (and `df` is its gradient) |
| 183 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1) |
| 184 |
|
| 185 |
The algorithm used for solving the problem is conditional gradient as discussed in :ref:`[1] <references-cg>` |
| 186 |
|
| 187 |
The function solves the following optimization problem if set a generalized conditional gradient: |
| 188 |
|
| 189 |
.. math:: |
| 190 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 191 |
\mathrm{reg_1}\cdot f(\gamma) + \mathrm{reg_2}\cdot\Omega(\gamma) |
| 192 |
|
| 193 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 194 |
|
| 195 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 196 |
|
| 197 |
\gamma &\geq 0 |
| 198 |
|
| 199 |
where : |
| 200 |
|
| 201 |
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 202 |
|
| 203 |
The algorithm used for solving the problem is the generalized conditional gradient as discussed in :ref:`[5, 7] <references-gcg>` |
| 204 |
|
| 205 |
Parameters |
| 206 |
---------- |
| 207 |
a : array-like, shape (ns,) |
| 208 |
samples weights in the source domain |
| 209 |
b : array-like, shape (nt,) |
| 210 |
samples weights in the target domain |
| 211 |
M : array-like, shape (ns, nt) |
| 212 |
loss matrix |
| 213 |
f : function |
| 214 |
Regularization function taking a transportation matrix as argument |
| 215 |
df: function |
| 216 |
Gradient of the regularization function taking a transportation matrix as argument |
| 217 |
reg1 : float |
| 218 |
Regularization term >0 |
| 219 |
reg2 : float, |
| 220 |
Entropic Regularization term >0. Ignored if set to None. |
| 221 |
lp_solver: function, |
| 222 |
linear program solver for direction finding of the (generalized) conditional gradient. |
| 223 |
This function must take the form `lp_solver(a, b, Mi, **kwargs)` with p: |
| 224 |
`a` and `b` are sample weights in both domains; `Mi` is the gradient of |
| 225 |
the regularized objective; optimal arguments via kwargs. |
| 226 |
It must output an admissible transport plan. |
| 227 |
|
| 228 |
For instance, for the general regularized OT problem with conditional gradient :ref:`[1] <references-cg>`: |
| 229 |
|
| 230 |
def lp_solver(a, b, M, **kwargs): |
| 231 |
return ot.emd(a, b, M) |
| 232 |
|
| 233 |
or with the generalized conditional gradient instead :ref:`[5, 7] <references-gcg>`: |
| 234 |
|
| 235 |
def lp_solver(a, b, Mi, **kwargs): |
| 236 |
return ot.sinkhorn(a, b, Mi) |
| 237 |
|
| 238 |
line_search: function, |
| 239 |
Function to find the optimal step. This function must take the form |
| 240 |
`line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs)` with: `cost` |
| 241 |
the cost function, `G` the transport plan, `deltaG` the conditional |
| 242 |
gradient direction given by lp_solver, `Mi` the gradient of regularized |
| 243 |
objective, `cost_G` the cost at G, `df_G` the gradient of the regularizer |
| 244 |
at G. Two types of outputs are supported: |
| 245 |
|
| 246 |
Instances such as `ot.optim.line_search_armijo` (generic solver), |
| 247 |
`ot.gromov.solve_gromov_linesearch` (FGW problems), |
| 248 |
`solve_semirelaxed_gromov_linesearch` (srFGW problems) and |
| 249 |
`gcg_linesearch` (generalized cg), output : the line-search step alpha, |
| 250 |
the number of iterations used in the solver if applicable and the loss |
| 251 |
value at step alpha. These can be called e.g as: |
| 252 |
|
| 253 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 254 |
return ot.optim.line_search_armijo(cost, G, deltaG, Mi, cost_G, **kwargs) |
| 255 |
|
| 256 |
Instances such as `ot.gromov.solve_partial_gromov_linesearch` for partial |
| 257 |
(F)GW problems add as finale output, the next step gradient reading as |
| 258 |
a convex combination of previously computed gradients, taking advantage of the regularizer |
| 259 |
quadratic form. |
| 260 |
|
| 261 |
G0 : array-like, shape (ns,nt), optional |
| 262 |
initial guess (default is indep joint density) |
| 263 |
numItermax : int, optional |
| 264 |
Max number of iterations |
| 265 |
stopThr : float, optional |
| 266 |
Stop threshold on the relative variation (>0) |
| 267 |
stopThr2 : float, optional |
| 268 |
Stop threshold on the absolute variation (>0) |
| 269 |
verbose : bool, optional |
| 270 |
Print information along iterations |
| 271 |
log : bool, optional |
| 272 |
record log if True |
| 273 |
nx : backend, optional |
| 274 |
If let to its default value None, the backend will be deduced from other inputs. |
| 275 |
**kwargs : dict |
| 276 |
Parameters for linesearch |
| 277 |
|
| 278 |
Returns |
| 279 |
------- |
| 280 |
gamma : (ns x nt) ndarray |
| 281 |
Optimal transportation matrix for the given parameters |
| 282 |
log : dict |
| 283 |
log dictionary return only if log==True in parameters |
| 284 |
|
| 285 |
|
| 286 |
.. _references-cg: |
| 287 |
.. _references_gcg: |
| 288 |
References |
| 289 |
---------- |
| 290 |
|
| 291 |
.. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882. |
| 292 |
|
| 293 |
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 |
| 294 |
|
| 295 |
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. |
| 296 |
|
| 297 |
See Also |
| 298 |
-------- |
| 299 |
ot.lp.emd : Unregularized optimal transport |
| 300 |
ot.bregman.sinkhorn : Entropic regularized optimal transport |
| 301 |
""" |
| 302 |
|
| 303 |
if nx is None: |
| 304 |
if isinstance(M, int) or isinstance(M, float): |
| 305 |
nx = get_backend(a, b) |
| 306 |
else: |
| 307 |
nx = get_backend(a, b, M) |
| 308 |
|
| 309 |
loop = 1 |
| 310 |
|
| 311 |
if log: |
| 312 |
log = {"loss": []} |
| 313 |
|
| 314 |
if G0 is None: |
| 315 |
G = nx.outer(a, b) |
| 316 |
else: |
| 317 |
|
| 318 |
G = nx.copy(G0) |
| 319 |
|
| 320 |
if reg2 is None: |
| 321 |
|
| 322 |
def cost(G): |
| 323 |
return nx.sum(M * G) + reg1 * f(G) |
| 324 |
else: |
| 325 |
|
| 326 |
def cost(G): |
| 327 |
return nx.sum(M * G) + reg1 * f(G) + reg2 * nx.sum(G * nx.log(G)) |
| 328 |
|
| 329 |
cost_G = cost(G) |
| 330 |
if log: |
| 331 |
log["loss"].append(cost_G) |
| 332 |
|
| 333 |
df_G = None |
| 334 |
it = 0 |
| 335 |
|
| 336 |
if verbose: |
| 337 |
print( |
| 338 |
"{:5s}|{:12s}|{:8s}|{:8s}".format( |
| 339 |
"It.", "Loss", "Relative loss", "Absolute loss" |
| 340 |
) |
| 341 |
+ "\n" |
| 342 |
+ "-" * 48 |
| 343 |
) |
| 344 |
print("{:5d}|{:8e}|{:8e}|{:8e}".format(it, cost_G, 0, 0)) |
| 345 |
|
| 346 |
while loop: |
| 347 |
it += 1 |
| 348 |
old_cost_G = cost_G |
| 349 |
|
| 350 |
if df_G is None: |
| 351 |
df_G = df(G) |
| 352 |
Mi = M + reg1 * df_G |
| 353 |
|
| 354 |
if reg2 is not None: |
| 355 |
Mi = Mi + reg2 * (1 + nx.log(G)) |
| 356 |
|
| 357 |
|
| 358 |
Gc, innerlog_ = lp_solver(a, b, Mi, **kwargs) |
| 359 |
|
| 360 |
deltaG = Gc - G |
| 361 |
|
| 362 |
res_line_search = line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs) |
| 363 |
if len(res_line_search) == 3: |
| 364 |
|
| 365 |
alpha, fc, cost_G = res_line_search |
| 366 |
df_G = None |
| 367 |
else: |
| 368 |
|
| 369 |
|
| 370 |
alpha, fc, cost_G, df_G = res_line_search |
| 371 |
|
| 372 |
G = G + alpha * deltaG |
| 373 |
|
| 374 |
|
| 375 |
if it >= numItermax: |
| 376 |
loop = 0 |
| 377 |
|
| 378 |
abs_delta_cost_G = abs(cost_G - old_cost_G) |
| 379 |
relative_delta_cost_G = ( |
| 380 |
abs_delta_cost_G / abs(cost_G) if cost_G != 0.0 else np.nan |
| 381 |
) |
| 382 |
if relative_delta_cost_G < stopThr or abs_delta_cost_G < stopThr2: |
| 383 |
loop = 0 |
| 384 |
|
| 385 |
if log: |
| 386 |
log["loss"].append(cost_G) |
| 387 |
|
| 388 |
if verbose: |
| 389 |
if it % 20 == 0: |
| 390 |
print( |
| 391 |
"{:5s}|{:12s}|{:8s}|{:8s}".format( |
| 392 |
"It.", "Loss", "Relative loss", "Absolute loss" |
| 393 |
) |
| 394 |
+ "\n" |
| 395 |
+ "-" * 48 |
| 396 |
) |
| 397 |
print( |
| 398 |
"{:5d}|{:8e}|{:8e}|{:8e}".format( |
| 399 |
it, cost_G, relative_delta_cost_G, abs_delta_cost_G |
| 400 |
) |
| 401 |
) |
| 402 |
|
| 403 |
if log: |
| 404 |
log.update(innerlog_) |
| 405 |
return G, log |
| 406 |
else: |
| 407 |
return G |
| 408 |
|
| 409 |
|
| 410 |
def cg( |
| 411 |
a, |
| 412 |
b, |
| 413 |
M, |
| 414 |
reg, |
| 415 |
f, |
| 416 |
df, |
| 417 |
G0=None, |
| 418 |
line_search=None, |
| 419 |
numItermax=200, |
| 420 |
numItermaxEmd=100000, |
| 421 |
stopThr=1e-9, |
| 422 |
stopThr2=1e-9, |
| 423 |
verbose=False, |
| 424 |
log=False, |
| 425 |
nx=None, |
| 426 |
**kwargs, |
| 427 |
): |
| 428 |
r""" |
| 429 |
Solve the general regularized OT problem with conditional gradient |
| 430 |
|
| 431 |
The function solves the following optimization problem: |
| 432 |
|
| 433 |
.. math:: |
| 434 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 435 |
\mathrm{reg} \cdot f(\gamma) |
| 436 |
|
| 437 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 438 |
|
| 439 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 440 |
|
| 441 |
\gamma &\geq 0 |
| 442 |
|
| 443 |
where : |
| 444 |
|
| 445 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix |
| 446 |
- :math:`f` is the regularization term (and `df` is its gradient) |
| 447 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1) |
| 448 |
|
| 449 |
The algorithm used for solving the problem is conditional gradient as discussed in :ref:`[1] <references-cg>` |
| 450 |
|
| 451 |
|
| 452 |
Parameters |
| 453 |
---------- |
| 454 |
a : array-like, shape (ns,) |
| 455 |
samples weights in the source domain |
| 456 |
b : array-like, shape (nt,) |
| 457 |
samples in the target domain |
| 458 |
M : array-like, shape (ns, nt) |
| 459 |
loss matrix |
| 460 |
reg : float |
| 461 |
Regularization term >0 |
| 462 |
G0 : array-like, shape (ns,nt), optional |
| 463 |
initial guess (default is indep joint density) |
| 464 |
line_search: function, |
| 465 |
Function to find the optimal step. |
| 466 |
Default is None and calls a wrapper to line_search_armijo. |
| 467 |
numItermax : int, optional |
| 468 |
Max number of iterations |
| 469 |
numItermaxEmd : int, optional |
| 470 |
Max number of iterations for emd |
| 471 |
stopThr : float, optional |
| 472 |
Stop threshold on the relative variation (>0) |
| 473 |
stopThr2 : float, optional |
| 474 |
Stop threshold on the absolute variation (>0) |
| 475 |
verbose : bool, optional |
| 476 |
Print information along iterations |
| 477 |
log : bool, optional |
| 478 |
record log if True |
| 479 |
nx : backend, optional |
| 480 |
If let to its default value None, the backend will be deduced from other inputs. |
| 481 |
**kwargs : dict |
| 482 |
Parameters for linesearch |
| 483 |
|
| 484 |
Returns |
| 485 |
------- |
| 486 |
gamma : (ns x nt) ndarray |
| 487 |
Optimal transportation matrix for the given parameters |
| 488 |
log : dict |
| 489 |
log dictionary return only if log==True in parameters |
| 490 |
|
| 491 |
|
| 492 |
.. _references-cg: |
| 493 |
References |
| 494 |
---------- |
| 495 |
|
| 496 |
.. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882. |
| 497 |
|
| 498 |
See Also |
| 499 |
-------- |
| 500 |
ot.lp.emd : Unregularized optimal transport |
| 501 |
ot.bregman.sinkhorn : Entropic regularized optimal transport |
| 502 |
|
| 503 |
""" |
| 504 |
if nx is None: |
| 505 |
if isinstance(M, int) or isinstance(M, float): |
| 506 |
nx = get_backend(a, b) |
| 507 |
else: |
| 508 |
nx = get_backend(a, b, M) |
| 509 |
|
| 510 |
if line_search is None: |
| 511 |
|
| 512 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 513 |
return line_search_armijo(cost, G, deltaG, Mi, cost_G, nx=nx, **kwargs) |
| 514 |
|
| 515 |
def lp_solver(a, b, M, **kwargs): |
| 516 |
return emd(a, b, M, numItermaxEmd, log=True) |
| 517 |
|
| 518 |
return generic_conditional_gradient( |
| 519 |
a, |
| 520 |
b, |
| 521 |
M, |
| 522 |
f, |
| 523 |
df, |
| 524 |
reg, |
| 525 |
None, |
| 526 |
lp_solver, |
| 527 |
line_search, |
| 528 |
G0=G0, |
| 529 |
numItermax=numItermax, |
| 530 |
stopThr=stopThr, |
| 531 |
stopThr2=stopThr2, |
| 532 |
verbose=verbose, |
| 533 |
log=log, |
| 534 |
nx=nx, |
| 535 |
**kwargs, |
| 536 |
) |
| 537 |
|
| 538 |
|
| 539 |
def semirelaxed_cg( |
| 540 |
a, |
| 541 |
b, |
| 542 |
M, |
| 543 |
reg, |
| 544 |
f, |
| 545 |
df, |
| 546 |
G0=None, |
| 547 |
line_search=None, |
| 548 |
numItermax=200, |
| 549 |
stopThr=1e-9, |
| 550 |
stopThr2=1e-9, |
| 551 |
verbose=False, |
| 552 |
log=False, |
| 553 |
nx=None, |
| 554 |
**kwargs, |
| 555 |
): |
| 556 |
r""" |
| 557 |
Solve the general regularized and semi-relaxed OT problem with conditional gradient |
| 558 |
|
| 559 |
The function solves the following optimization problem: |
| 560 |
|
| 561 |
.. math:: |
| 562 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 563 |
\mathrm{reg} \cdot f(\gamma) |
| 564 |
|
| 565 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 566 |
|
| 567 |
\gamma &\geq 0 |
| 568 |
|
| 569 |
where : |
| 570 |
|
| 571 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix |
| 572 |
- :math:`f` is the regularization term (and `df` is its gradient) |
| 573 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1) |
| 574 |
|
| 575 |
The algorithm used for solving the problem is conditional gradient as discussed in :ref:`[1] <references-cg>` |
| 576 |
|
| 577 |
|
| 578 |
Parameters |
| 579 |
---------- |
| 580 |
a : array-like, shape (ns,) |
| 581 |
samples weights in the source domain |
| 582 |
b : array-like, shape (nt,) |
| 583 |
currently estimated samples weights in the target domain |
| 584 |
M : array-like, shape (ns, nt) |
| 585 |
loss matrix |
| 586 |
reg : float |
| 587 |
Regularization term >0 |
| 588 |
G0 : array-like, shape (ns,nt), optional |
| 589 |
initial guess (default is indep joint density) |
| 590 |
line_search: function, |
| 591 |
Function to find the optimal step. |
| 592 |
Default is None and calls a wrapper to line_search_armijo. |
| 593 |
numItermax : int, optional |
| 594 |
Max number of iterations |
| 595 |
stopThr : float, optional |
| 596 |
Stop threshold on the relative variation (>0) |
| 597 |
stopThr2 : float, optional |
| 598 |
Stop threshold on the absolute variation (>0) |
| 599 |
verbose : bool, optional |
| 600 |
Print information along iterations |
| 601 |
log : bool, optional |
| 602 |
record log if True |
| 603 |
nx : backend, optional |
| 604 |
If let to its default value None, the backend will be deduced from other inputs. |
| 605 |
**kwargs : dict |
| 606 |
Parameters for linesearch |
| 607 |
|
| 608 |
Returns |
| 609 |
------- |
| 610 |
gamma : (ns x nt) ndarray |
| 611 |
Optimal transportation matrix for the given parameters |
| 612 |
log : dict |
| 613 |
log dictionary return only if log==True in parameters |
| 614 |
|
| 615 |
|
| 616 |
.. _references-cg: |
| 617 |
References |
| 618 |
---------- |
| 619 |
|
| 620 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 621 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 622 |
International Conference on Learning Representations (ICLR), 2021. |
| 623 |
|
| 624 |
""" |
| 625 |
if nx is None: |
| 626 |
if isinstance(M, int) or isinstance(M, float): |
| 627 |
nx = get_backend(a, b) |
| 628 |
else: |
| 629 |
nx = get_backend(a, b, M) |
| 630 |
|
| 631 |
if line_search is None: |
| 632 |
|
| 633 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 634 |
return line_search_armijo(cost, G, deltaG, Mi, cost_G, nx=nx, **kwargs) |
| 635 |
|
| 636 |
def lp_solver(a, b, Mi, **kwargs): |
| 637 |
|
| 638 |
min_ = nx.reshape(nx.min(Mi, axis=1), (-1, 1)) |
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
Gc = nx.ones(1, type_as=a) * (Mi <= min_ + 1e-15) |
| 643 |
Gc *= nx.reshape((a / nx.sum(Gc, axis=1)), (-1, 1)) |
| 644 |
|
| 645 |
return Gc, {} |
| 646 |
|
| 647 |
return generic_conditional_gradient( |
| 648 |
a, |
| 649 |
b, |
| 650 |
M, |
| 651 |
f, |
| 652 |
df, |
| 653 |
reg, |
| 654 |
None, |
| 655 |
lp_solver, |
| 656 |
line_search, |
| 657 |
G0=G0, |
| 658 |
numItermax=numItermax, |
| 659 |
stopThr=stopThr, |
| 660 |
stopThr2=stopThr2, |
| 661 |
verbose=verbose, |
| 662 |
log=log, |
| 663 |
nx=nx, |
| 664 |
**kwargs, |
| 665 |
) |
| 666 |
|
| 667 |
|
| 668 |
def partial_cg( |
| 669 |
a, |
| 670 |
b, |
| 671 |
a_extended, |
| 672 |
b_extended, |
| 673 |
M, |
| 674 |
reg, |
| 675 |
f, |
| 676 |
df, |
| 677 |
G0=None, |
| 678 |
line_search=line_search_armijo, |
| 679 |
numItermax=200, |
| 680 |
stopThr=1e-9, |
| 681 |
stopThr2=1e-9, |
| 682 |
warn=True, |
| 683 |
verbose=False, |
| 684 |
log=False, |
| 685 |
**kwargs, |
| 686 |
): |
| 687 |
r""" |
| 688 |
Solve the general regularized partial OT problem with conditional gradient |
| 689 |
|
| 690 |
The function solves the following optimization problem: |
| 691 |
|
| 692 |
.. math:: |
| 693 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 694 |
\mathrm{reg} \cdot f(\gamma) |
| 695 |
|
| 696 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 697 |
|
| 698 |
\gamma \mathbf{1} &= \mathbf{b} |
| 699 |
|
| 700 |
\mathbf{1}^T \gamma^T \mathbf{1} = m &\leq \min\{\|\mathbf{p}\|_1, \|\mathbf{q}\|_1\} |
| 701 |
|
| 702 |
\gamma &\geq 0 |
| 703 |
|
| 704 |
where : |
| 705 |
|
| 706 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix |
| 707 |
- :math:`f` is the regularization term (and `df` is its gradient) |
| 708 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights |
| 709 |
- `m` is the amount of mass to be transported |
| 710 |
|
| 711 |
The algorithm used for solving the problem is conditional gradient as discussed in :ref:`[1] <references-cg>` |
| 712 |
|
| 713 |
Parameters |
| 714 |
---------- |
| 715 |
a : array-like, shape (ns,) |
| 716 |
samples weights in the source domain |
| 717 |
b : array-like, shape (nt,) |
| 718 |
currently estimated samples weights in the target domain |
| 719 |
a_extended : array-like, shape (ns + nb_dummies,) |
| 720 |
samples weights in the source domain with added dummy nodes |
| 721 |
b_extended : array-like, shape (nt + nb_dummies,) |
| 722 |
currently estimated samples weights in the target domain with added dummy nodes |
| 723 |
M : array-like, shape (ns, nt) |
| 724 |
loss matrix |
| 725 |
reg : float |
| 726 |
Regularization term >0 |
| 727 |
G0 : array-like, shape (ns,nt), optional |
| 728 |
initial guess (default is indep joint density) |
| 729 |
line_search: function, |
| 730 |
Function to find the optimal step. |
| 731 |
Default is the armijo line-search. |
| 732 |
numItermax : int, optional |
| 733 |
Max number of iterations |
| 734 |
stopThr : float, optional |
| 735 |
Stop threshold on the relative variation (>0) |
| 736 |
stopThr2 : float, optional |
| 737 |
Stop threshold on the absolute variation (>0) |
| 738 |
warn: bool, optional. |
| 739 |
Whether to raise a warning when EMD did not converge. |
| 740 |
verbose : bool, optional |
| 741 |
Print information along iterations |
| 742 |
log : bool, optional |
| 743 |
record log if True |
| 744 |
**kwargs : dict |
| 745 |
Parameters for linesearch |
| 746 |
|
| 747 |
Returns |
| 748 |
------- |
| 749 |
gamma : (ns x nt) ndarray |
| 750 |
Optimal transportation matrix for the given parameters |
| 751 |
log : dict |
| 752 |
log dictionary return only if log==True in parameters |
| 753 |
|
| 754 |
|
| 755 |
.. _references-partial-cg: |
| 756 |
References |
| 757 |
---------- |
| 758 |
|
| 759 |
.. [29] Chapel, L., Alaya, M., Gasso, G. (2020). "Partial Optimal |
| 760 |
Transport with Applications on Positive-Unlabeled Learning". |
| 761 |
NeurIPS. |
| 762 |
|
| 763 |
""" |
| 764 |
n, m = a.shape[0], b.shape[0] |
| 765 |
n_extended, m_extended = a_extended.shape[0], b_extended.shape[0] |
| 766 |
nb_dummies = n_extended - n |
| 767 |
|
| 768 |
def lp_solver(a, b, Mi, **kwargs): |
| 769 |
|
| 770 |
Mi_extended = np.zeros((n_extended, m_extended), dtype=Mi.dtype) |
| 771 |
Mi_extended[:n, :m] = Mi |
| 772 |
Mi_extended[-nb_dummies:, -nb_dummies:] = np.max(M) * 1e2 |
| 773 |
|
| 774 |
G_extended, log_ = emd( |
| 775 |
a_extended, b_extended, Mi_extended, numItermax, log=True |
| 776 |
) |
| 777 |
Gc = G_extended[:n, :m] |
| 778 |
|
| 779 |
if warn: |
| 780 |
if log_["warning"] is not None: |
| 781 |
raise ValueError( |
| 782 |
"Error in the EMD resolution: try to increase the" |
| 783 |
" number of dummy points" |
| 784 |
) |
| 785 |
|
| 786 |
return Gc, log_ |
| 787 |
|
| 788 |
return generic_conditional_gradient( |
| 789 |
a, |
| 790 |
b, |
| 791 |
M, |
| 792 |
f, |
| 793 |
df, |
| 794 |
reg, |
| 795 |
None, |
| 796 |
lp_solver, |
| 797 |
line_search, |
| 798 |
G0=G0, |
| 799 |
numItermax=numItermax, |
| 800 |
stopThr=stopThr, |
| 801 |
stopThr2=stopThr2, |
| 802 |
verbose=verbose, |
| 803 |
log=log, |
| 804 |
**kwargs, |
| 805 |
) |
| 806 |
|
| 807 |
|
| 808 |
def gcg( |
| 809 |
a, |
| 810 |
b, |
| 811 |
M, |
| 812 |
reg1, |
| 813 |
reg2, |
| 814 |
f, |
| 815 |
df, |
| 816 |
G0=None, |
| 817 |
numItermax=10, |
| 818 |
numInnerItermax=200, |
| 819 |
stopThr=1e-9, |
| 820 |
stopThr2=1e-9, |
| 821 |
verbose=False, |
| 822 |
log=False, |
| 823 |
**kwargs, |
| 824 |
): |
| 825 |
r""" |
| 826 |
Solve the general regularized OT problem with the generalized conditional gradient |
| 827 |
|
| 828 |
The function solves the following optimization problem: |
| 829 |
|
| 830 |
.. math:: |
| 831 |
\gamma = \mathop{\arg \min}_\gamma \quad \langle \gamma, \mathbf{M} \rangle_F + |
| 832 |
\mathrm{reg_1}\cdot\Omega(\gamma) + \mathrm{reg_2}\cdot f(\gamma) |
| 833 |
|
| 834 |
s.t. \ \gamma \mathbf{1} &= \mathbf{a} |
| 835 |
|
| 836 |
\gamma^T \mathbf{1} &= \mathbf{b} |
| 837 |
|
| 838 |
\gamma &\geq 0 |
| 839 |
|
| 840 |
where : |
| 841 |
|
| 842 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix |
| 843 |
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` |
| 844 |
- :math:`f` is the regularization term (and `df` is its gradient) |
| 845 |
- :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target weights (sum to 1) |
| 846 |
|
| 847 |
The algorithm used for solving the problem is the generalized conditional gradient as discussed in :ref:`[5, 7] <references-gcg>` |
| 848 |
|
| 849 |
|
| 850 |
Parameters |
| 851 |
---------- |
| 852 |
a : array-like, shape (ns,) |
| 853 |
samples weights in the source domain |
| 854 |
b : array-like, (nt,) |
| 855 |
samples in the target domain |
| 856 |
M : array-like, shape (ns, nt) |
| 857 |
loss matrix |
| 858 |
reg1 : float |
| 859 |
Entropic Regularization term >0 |
| 860 |
reg2 : float |
| 861 |
Second Regularization term >0 |
| 862 |
G0 : array-like, shape (ns, nt), optional |
| 863 |
initial guess (default is indep joint density) |
| 864 |
numItermax : int, optional |
| 865 |
Max number of iterations |
| 866 |
numInnerItermax : int, optional |
| 867 |
Max number of iterations of Sinkhorn |
| 868 |
stopThr : float, optional |
| 869 |
Stop threshold on the relative variation (>0) |
| 870 |
stopThr2 : float, optional |
| 871 |
Stop threshold on the absolute variation (>0) |
| 872 |
verbose : bool, optional |
| 873 |
Print information along iterations |
| 874 |
log : bool, optional |
| 875 |
record log if True |
| 876 |
|
| 877 |
Returns |
| 878 |
------- |
| 879 |
gamma : ndarray, shape (ns, nt) |
| 880 |
Optimal transportation matrix for the given parameters |
| 881 |
log : dict |
| 882 |
log dictionary return only if log==True in parameters |
| 883 |
|
| 884 |
|
| 885 |
.. _references-gcg: |
| 886 |
References |
| 887 |
---------- |
| 888 |
|
| 889 |
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 |
| 890 |
|
| 891 |
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. |
| 892 |
|
| 893 |
See Also |
| 894 |
-------- |
| 895 |
ot.optim.cg : conditional gradient |
| 896 |
|
| 897 |
""" |
| 898 |
|
| 899 |
def lp_solver(a, b, Mi, **kwargs): |
| 900 |
return sinkhorn(a, b, Mi, reg1, numItermax=numInnerItermax, log=True, **kwargs) |
| 901 |
|
| 902 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 903 |
return line_search_armijo(cost, G, deltaG, Mi, cost_G, **kwargs) |
| 904 |
|
| 905 |
return generic_conditional_gradient( |
| 906 |
a, |
| 907 |
b, |
| 908 |
M, |
| 909 |
f, |
| 910 |
df, |
| 911 |
reg2, |
| 912 |
reg1, |
| 913 |
lp_solver, |
| 914 |
line_search, |
| 915 |
G0=G0, |
| 916 |
numItermax=numItermax, |
| 917 |
stopThr=stopThr, |
| 918 |
stopThr2=stopThr2, |
| 919 |
verbose=verbose, |
| 920 |
log=log, |
| 921 |
**kwargs, |
| 922 |
) |
| 923 |
|
| 924 |
|
| 925 |
def solve_1d_linesearch_quad(a, b): |
| 926 |
r""" |
| 927 |
For any convex or non-convex 1d quadratic function `f`, solve the following problem: |
| 928 |
|
| 929 |
.. math:: |
| 930 |
|
| 931 |
\mathop{\arg \min}_{0 \leq x \leq 1} \quad f(x) = ax^{2} + bx + c |
| 932 |
|
| 933 |
Parameters |
| 934 |
---------- |
| 935 |
a,b : float or tensors (1,) |
| 936 |
The coefficients of the quadratic function |
| 937 |
|
| 938 |
Returns |
| 939 |
------- |
| 940 |
x : float |
| 941 |
The optimal value which leads to the minimal cost |
| 942 |
""" |
| 943 |
if a > 0: |
| 944 |
minimum = min(1.0, max(0.0, -b / (2.0 * a))) |
| 945 |
return minimum |
| 946 |
else: |
| 947 |
if a + b < 0: |
| 948 |
return 1.0 |
| 949 |
else: |
| 950 |
return 0.0 |