| 1 |
|
| 2 |
""" |
| 3 |
Gromov-Wasserstein and Fused-Gromov-Wasserstein conditional gradient solvers. |
| 4 |
""" |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
> |
| 9 |
|
| 10 |
> |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
import numpy as np |
| 15 |
import warnings |
| 16 |
|
| 17 |
|
| 18 |
from ..utils import dist, UndefinedParameter, list_to_array |
| 19 |
from ..optim import cg, line_search_armijo, solve_1d_linesearch_quad |
| 20 |
from ..utils import check_random_state, unif |
| 21 |
from ..backend import get_backend, NumpyBackend |
| 22 |
|
| 23 |
from ._utils import init_matrix, gwloss, gwggrad |
| 24 |
from ._utils import update_barycenter_structure, update_barycenter_feature |
| 25 |
|
| 26 |
|
| 27 |
def gromov_wasserstein( |
| 28 |
C1, |
| 29 |
C2, |
| 30 |
p=None, |
| 31 |
q=None, |
| 32 |
loss_fun="square_loss", |
| 33 |
symmetric=None, |
| 34 |
log=False, |
| 35 |
armijo=False, |
| 36 |
G0=None, |
| 37 |
max_iter=1e4, |
| 38 |
tol_rel=1e-9, |
| 39 |
tol_abs=1e-9, |
| 40 |
**kwargs, |
| 41 |
): |
| 42 |
r""" |
| 43 |
Returns the Gromov-Wasserstein transport between :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`. |
| 44 |
|
| 45 |
The function solves the following optimization problem using Conditional Gradient: |
| 46 |
|
| 47 |
.. math:: |
| 48 |
\mathbf{T}^* \in \mathop{\arg \min}_\mathbf{T} \quad \sum_{i,j,k,l} |
| 49 |
L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 50 |
|
| 51 |
s.t. \ \mathbf{\gamma} \mathbf{1} &= \mathbf{p} |
| 52 |
|
| 53 |
\mathbf{\gamma}^T \mathbf{1} &= \mathbf{q} |
| 54 |
|
| 55 |
\mathbf{\gamma} &\geq 0 |
| 56 |
|
| 57 |
Where : |
| 58 |
|
| 59 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space. |
| 60 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space. |
| 61 |
- :math:`\mathbf{p}`: Distribution in the source space. |
| 62 |
- :math:`\mathbf{q}`: Distribution in the target space. |
| 63 |
- `L`: Loss function to account for the misfit between the similarity matrices. |
| 64 |
|
| 65 |
.. note:: This function is backend-compatible and will work on arrays |
| 66 |
from all compatible backends. But the algorithm uses the C++ CPU backend |
| 67 |
which can lead to copy overhead on GPU arrays. |
| 68 |
.. note:: All computations in the conjugate gradient solver are done with |
| 69 |
numpy to limit memory overhead. |
| 70 |
.. note:: This function will cast the computed transport plan to the data |
| 71 |
type of the provided input :math:`\mathbf{C}_1`. Casting to an integer |
| 72 |
tensor might result in a loss of precision. If this behaviour is |
| 73 |
unwanted, please make sure to provide a floating point input. |
| 74 |
|
| 75 |
Parameters |
| 76 |
---------- |
| 77 |
C1 : array-like, shape (ns, ns) |
| 78 |
Metric cost matrix in the source space. |
| 79 |
C2 : array-like, shape (nt, nt) |
| 80 |
Metric cost matrix in the target space. |
| 81 |
p : array-like, shape (ns,), optional |
| 82 |
Distribution in the source space. |
| 83 |
If let to its default value None, uniform distribution is taken. |
| 84 |
q : array-like, shape (nt,), optional |
| 85 |
Distribution in the target space. |
| 86 |
If let to its default value None, uniform distribution is taken. |
| 87 |
loss_fun : str, optional |
| 88 |
Loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 89 |
symmetric : bool, optional |
| 90 |
Either C1 and C2 are to be assumed symmetric or not. |
| 91 |
If let to its default None value, a symmetry test will be conducted. |
| 92 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 93 |
verbose : bool, optional |
| 94 |
Print information along iterations. |
| 95 |
log : bool, optional |
| 96 |
Record log if True. |
| 97 |
armijo : bool, optional |
| 98 |
If True, the step of the line-search is found via an armijo search. Else closed form is used. |
| 99 |
If there are convergence issues, use False. |
| 100 |
G0: array-like, shape (ns,nt), optional |
| 101 |
If None, the initial transport plan of the solver is pq^T. |
| 102 |
Otherwise G0 must satisfy marginal constraints and will be used as initial transport of the solver. |
| 103 |
max_iter : int, optional |
| 104 |
Max number of iterations. |
| 105 |
tol_rel : float, optional |
| 106 |
Stop threshold on relative error (>0). |
| 107 |
tol_abs : float, optional |
| 108 |
Stop threshold on absolute error (>0). |
| 109 |
**kwargs : dict |
| 110 |
Parameters can be directly passed to the ot.optim.cg solver. |
| 111 |
|
| 112 |
Returns |
| 113 |
------- |
| 114 |
T : array-like, shape (`ns`, `nt`) |
| 115 |
Coupling between the two spaces that minimizes: |
| 116 |
|
| 117 |
:math:`\sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}` |
| 118 |
log : dict |
| 119 |
Convergence information and loss. |
| 120 |
|
| 121 |
References |
| 122 |
---------- |
| 123 |
.. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon, |
| 124 |
"Gromov-Wasserstein averaging of kernel and distance matrices." |
| 125 |
International Conference on Machine Learning (ICML). 2016. |
| 126 |
|
| 127 |
.. [13] Mémoli, Facundo. Gromov–Wasserstein distances and the |
| 128 |
metric approach to object matching. Foundations of computational |
| 129 |
mathematics 11.4 (2011): 417-487. |
| 130 |
|
| 131 |
.. [47] Chowdhury, S., & Mémoli, F. (2019). The gromov–wasserstein |
| 132 |
distance between networks and stable network invariants. |
| 133 |
Information and Inference: A Journal of the IMA, 8(4), 757-787. |
| 134 |
""" |
| 135 |
arr = [C1, C2] |
| 136 |
if p is not None: |
| 137 |
arr.append(list_to_array(p)) |
| 138 |
else: |
| 139 |
p = unif(C1.shape[0], type_as=C1) |
| 140 |
if q is not None: |
| 141 |
arr.append(list_to_array(q)) |
| 142 |
else: |
| 143 |
q = unif(C2.shape[0], type_as=C1) |
| 144 |
if G0 is not None: |
| 145 |
G0_ = G0 |
| 146 |
arr.append(G0) |
| 147 |
|
| 148 |
nx = get_backend(*arr) |
| 149 |
p0, q0, C10, C20 = p, q, C1, C2 |
| 150 |
|
| 151 |
p = nx.to_numpy(p0) |
| 152 |
q = nx.to_numpy(q0) |
| 153 |
C1 = nx.to_numpy(C10) |
| 154 |
C2 = nx.to_numpy(C20) |
| 155 |
if symmetric is None: |
| 156 |
symmetric = np.allclose(C1, C1.T, atol=1e-10) and np.allclose( |
| 157 |
C2, C2.T, atol=1e-10 |
| 158 |
) |
| 159 |
|
| 160 |
if G0 is None: |
| 161 |
G0 = p[:, None] * q[None, :] |
| 162 |
else: |
| 163 |
G0 = nx.to_numpy(G0_) |
| 164 |
|
| 165 |
np.testing.assert_allclose(G0.sum(axis=1), p, atol=1e-08) |
| 166 |
np.testing.assert_allclose(G0.sum(axis=0), q, atol=1e-08) |
| 167 |
|
| 168 |
np_ = NumpyBackend() |
| 169 |
|
| 170 |
constC, hC1, hC2 = init_matrix(C1, C2, p, q, loss_fun, np_) |
| 171 |
|
| 172 |
def f(G): |
| 173 |
return gwloss(constC, hC1, hC2, G, np_) |
| 174 |
|
| 175 |
if symmetric: |
| 176 |
|
| 177 |
def df(G): |
| 178 |
return gwggrad(constC, hC1, hC2, G, np_) |
| 179 |
else: |
| 180 |
constCt, hC1t, hC2t = init_matrix(C1.T, C2.T, p, q, loss_fun, np_) |
| 181 |
|
| 182 |
def df(G): |
| 183 |
return 0.5 * ( |
| 184 |
gwggrad(constC, hC1, hC2, G, np_) + gwggrad(constCt, hC1t, hC2t, G, np_) |
| 185 |
) |
| 186 |
|
| 187 |
if armijo: |
| 188 |
|
| 189 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 190 |
return line_search_armijo(cost, G, deltaG, Mi, cost_G, nx=np_, **kwargs) |
| 191 |
else: |
| 192 |
|
| 193 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 194 |
return solve_gromov_linesearch( |
| 195 |
G, |
| 196 |
deltaG, |
| 197 |
cost_G, |
| 198 |
hC1, |
| 199 |
hC2, |
| 200 |
M=0.0, |
| 201 |
reg=1.0, |
| 202 |
nx=np_, |
| 203 |
symmetric=symmetric, |
| 204 |
**kwargs, |
| 205 |
) |
| 206 |
|
| 207 |
if not nx.is_floating_point(C10): |
| 208 |
warnings.warn( |
| 209 |
"Input structure matrix consists of integers. The transport plan will be " |
| 210 |
"casted accordingly, possibly resulting in a loss of precision. " |
| 211 |
"If this behaviour is unwanted, please make sure your input " |
| 212 |
"structure matrix consists of floating point elements.", |
| 213 |
stacklevel=2, |
| 214 |
) |
| 215 |
|
| 216 |
if log: |
| 217 |
res, log = cg( |
| 218 |
p, |
| 219 |
q, |
| 220 |
0.0, |
| 221 |
1.0, |
| 222 |
f, |
| 223 |
df, |
| 224 |
G0, |
| 225 |
line_search, |
| 226 |
log=True, |
| 227 |
numItermax=max_iter, |
| 228 |
stopThr=tol_rel, |
| 229 |
stopThr2=tol_abs, |
| 230 |
**kwargs, |
| 231 |
) |
| 232 |
log["gw_dist"] = nx.from_numpy(log["loss"][-1], type_as=C10) |
| 233 |
log["u"] = nx.from_numpy(log["u"], type_as=C10) |
| 234 |
log["v"] = nx.from_numpy(log["v"], type_as=C10) |
| 235 |
return nx.from_numpy(res, type_as=C10), log |
| 236 |
else: |
| 237 |
return nx.from_numpy( |
| 238 |
cg( |
| 239 |
p, |
| 240 |
q, |
| 241 |
0.0, |
| 242 |
1.0, |
| 243 |
f, |
| 244 |
df, |
| 245 |
G0, |
| 246 |
line_search, |
| 247 |
log=False, |
| 248 |
numItermax=max_iter, |
| 249 |
stopThr=tol_rel, |
| 250 |
stopThr2=tol_abs, |
| 251 |
**kwargs, |
| 252 |
), |
| 253 |
type_as=C10, |
| 254 |
) |
| 255 |
|
| 256 |
|
| 257 |
def gromov_wasserstein2( |
| 258 |
C1, |
| 259 |
C2, |
| 260 |
p=None, |
| 261 |
q=None, |
| 262 |
loss_fun="square_loss", |
| 263 |
symmetric=None, |
| 264 |
log=False, |
| 265 |
armijo=False, |
| 266 |
G0=None, |
| 267 |
max_iter=1e4, |
| 268 |
tol_rel=1e-9, |
| 269 |
tol_abs=1e-9, |
| 270 |
**kwargs, |
| 271 |
): |
| 272 |
r""" |
| 273 |
Returns the Gromov-Wasserstein loss :math:`\mathbf{GW}` between :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`. |
| 274 |
To recover the Gromov-Wasserstein distance as defined in [13] compute :math:`d_{GW} = \frac{1}{2} \sqrt{\mathbf{GW}}`. |
| 275 |
|
| 276 |
The function solves the following optimization problem using Conditional Gradient: |
| 277 |
|
| 278 |
.. math:: |
| 279 |
\mathbf{GW} = \min_\mathbf{T} \quad \sum_{i,j,k,l} |
| 280 |
L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 281 |
|
| 282 |
s.t. \ \mathbf{\gamma} \mathbf{1} &= \mathbf{p} |
| 283 |
|
| 284 |
\mathbf{\gamma}^T \mathbf{1} &= \mathbf{q} |
| 285 |
|
| 286 |
\mathbf{\gamma} &\geq 0 |
| 287 |
|
| 288 |
Where : |
| 289 |
|
| 290 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 291 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 292 |
- :math:`\mathbf{p}`: distribution in the source space |
| 293 |
- :math:`\mathbf{q}`: distribution in the target space |
| 294 |
- `L`: loss function to account for the misfit between the similarity |
| 295 |
matrices |
| 296 |
|
| 297 |
Note that when using backends, this loss function is differentiable wrt the |
| 298 |
matrices (C1, C2) and weights (p, q) for quadratic loss using the gradients from [38]_. |
| 299 |
|
| 300 |
.. note:: This function is backend-compatible and will work on arrays |
| 301 |
from all compatible backends. But the algorithm uses the C++ CPU backend |
| 302 |
which can lead to copy overhead on GPU arrays. |
| 303 |
.. note:: All computations in the conjugate gradient solver are done with |
| 304 |
numpy to limit memory overhead. |
| 305 |
.. note:: This function will cast the computed transport plan to the data |
| 306 |
type of the provided input :math:`\mathbf{C}_1`. Casting to an integer |
| 307 |
tensor might result in a loss of precision. If this behaviour is |
| 308 |
unwanted, please make sure to provide a floating point input. |
| 309 |
|
| 310 |
Parameters |
| 311 |
---------- |
| 312 |
C1 : array-like, shape (ns, ns) |
| 313 |
Metric cost matrix in the source space |
| 314 |
C2 : array-like, shape (nt, nt) |
| 315 |
Metric cost matrix in the target space |
| 316 |
p : array-like, shape (ns,), optional |
| 317 |
Distribution in the source space. |
| 318 |
If let to its default value None, uniform distribution is taken. |
| 319 |
q : array-like, shape (nt,), optional |
| 320 |
Distribution in the target space. |
| 321 |
If let to its default value None, uniform distribution is taken. |
| 322 |
loss_fun : str |
| 323 |
loss function used for the solver either 'square_loss' or 'kl_loss' |
| 324 |
symmetric : bool, optional |
| 325 |
Either C1 and C2 are to be assumed symmetric or not. |
| 326 |
If let to its default None value, a symmetry test will be conducted. |
| 327 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 328 |
verbose : bool, optional |
| 329 |
Print information along iterations |
| 330 |
log : bool, optional |
| 331 |
record log if True |
| 332 |
armijo : bool, optional |
| 333 |
If True the step of the line-search is found via an armijo research. Else closed form is used. |
| 334 |
If there are convergence issues use False. |
| 335 |
G0: array-like, shape (ns,nt), optional |
| 336 |
If None the initial transport plan of the solver is pq^T. |
| 337 |
Otherwise G0 must satisfy marginal constraints and will be used as initial transport of the solver. |
| 338 |
max_iter : int, optional |
| 339 |
Max number of iterations |
| 340 |
tol_rel : float, optional |
| 341 |
Stop threshold on relative error (>0) |
| 342 |
tol_abs : float, optional |
| 343 |
Stop threshold on absolute error (>0) |
| 344 |
**kwargs : dict |
| 345 |
parameters can be directly passed to the ot.optim.cg solver |
| 346 |
|
| 347 |
Returns |
| 348 |
------- |
| 349 |
gw_dist : float |
| 350 |
Gromov-Wasserstein distance |
| 351 |
log : dict |
| 352 |
convergence information and Coupling matrix |
| 353 |
|
| 354 |
References |
| 355 |
---------- |
| 356 |
.. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon, |
| 357 |
"Gromov-Wasserstein averaging of kernel and distance matrices." |
| 358 |
International Conference on Machine Learning (ICML). 2016. |
| 359 |
|
| 360 |
.. [13] Mémoli, Facundo. Gromov–Wasserstein distances and the |
| 361 |
metric approach to object matching. Foundations of computational |
| 362 |
mathematics 11.4 (2011): 417-487. |
| 363 |
|
| 364 |
.. [38] C. Vincent-Cuaz, T. Vayer, R. Flamary, M. Corneli, N. Courty, Online |
| 365 |
Graph Dictionary Learning, International Conference on Machine Learning |
| 366 |
(ICML), 2021. |
| 367 |
|
| 368 |
.. [47] Chowdhury, S., & Mémoli, F. (2019). The gromov–wasserstein |
| 369 |
distance between networks and stable network invariants. |
| 370 |
Information and Inference: A Journal of the IMA, 8(4), 757-787. |
| 371 |
""" |
| 372 |
|
| 373 |
nx = get_backend(C1, C2) |
| 374 |
|
| 375 |
|
| 376 |
if p is None: |
| 377 |
p = unif(C1.shape[0], type_as=C1) |
| 378 |
if q is None: |
| 379 |
q = unif(C2.shape[0], type_as=C1) |
| 380 |
|
| 381 |
T, log_gw = gromov_wasserstein( |
| 382 |
C1, |
| 383 |
C2, |
| 384 |
p, |
| 385 |
q, |
| 386 |
loss_fun, |
| 387 |
symmetric, |
| 388 |
log=True, |
| 389 |
armijo=armijo, |
| 390 |
G0=G0, |
| 391 |
max_iter=max_iter, |
| 392 |
tol_rel=tol_rel, |
| 393 |
tol_abs=tol_abs, |
| 394 |
**kwargs, |
| 395 |
) |
| 396 |
|
| 397 |
log_gw["T"] = T |
| 398 |
gw = log_gw["gw_dist"] |
| 399 |
|
| 400 |
if loss_fun == "square_loss": |
| 401 |
gC1 = 2 * C1 * nx.outer(p, p) - 2 * nx.dot(T, nx.dot(C2, T.T)) |
| 402 |
gC2 = 2 * C2 * nx.outer(q, q) - 2 * nx.dot(T.T, nx.dot(C1, T)) |
| 403 |
elif loss_fun == "kl_loss": |
| 404 |
gC1 = nx.log(C1 + 1e-15) * nx.outer(p, p) - nx.dot( |
| 405 |
T, nx.dot(nx.log(C2 + 1e-15), T.T) |
| 406 |
) |
| 407 |
gC2 = -nx.dot(T.T, nx.dot(C1, T)) / (C2 + 1e-15) + nx.outer(q, q) |
| 408 |
|
| 409 |
gw = nx.set_gradients( |
| 410 |
gw, |
| 411 |
(p, q, C1, C2), |
| 412 |
( |
| 413 |
log_gw["u"] - nx.mean(log_gw["u"]), |
| 414 |
log_gw["v"] - nx.mean(log_gw["v"]), |
| 415 |
gC1, |
| 416 |
gC2, |
| 417 |
), |
| 418 |
) |
| 419 |
|
| 420 |
if log: |
| 421 |
return gw, log_gw |
| 422 |
else: |
| 423 |
return gw |
| 424 |
|
| 425 |
|
| 426 |
def fused_gromov_wasserstein( |
| 427 |
M, |
| 428 |
C1, |
| 429 |
C2, |
| 430 |
p=None, |
| 431 |
q=None, |
| 432 |
loss_fun="square_loss", |
| 433 |
symmetric=None, |
| 434 |
alpha=0.5, |
| 435 |
armijo=False, |
| 436 |
G0=None, |
| 437 |
log=False, |
| 438 |
max_iter=1e4, |
| 439 |
tol_rel=1e-9, |
| 440 |
tol_abs=1e-9, |
| 441 |
**kwargs, |
| 442 |
): |
| 443 |
r""" |
| 444 |
Returns the Fused Gromov-Wasserstein transport between :math:`(\mathbf{C_1}, \mathbf{Y_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{Y_2}, \mathbf{q})` |
| 445 |
with pairwise distance matrix :math:`\mathbf{M}` between node feature matrices :math:`\mathbf{Y_1}` and :math:`\mathbf{Y_2}` (see :ref:`[24] <references-fused-gromov-wasserstein>`). |
| 446 |
|
| 447 |
The function solves the following optimization problem using Conditional Gradient: |
| 448 |
|
| 449 |
.. math:: |
| 450 |
\mathbf{T}^* \in\mathop{\arg\min}_\mathbf{T} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F + |
| 451 |
\alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 452 |
|
| 453 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 454 |
|
| 455 |
\mathbf{T}^T \mathbf{1} &= \mathbf{q} |
| 456 |
|
| 457 |
\mathbf{T} &\geq 0 |
| 458 |
Where : |
| 459 |
|
| 460 |
- :math:`\mathbf{M}`: metric cost matrix between features across domains |
| 461 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 462 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 463 |
- :math:`\mathbf{p}`: distribution in the source space |
| 464 |
- :math:`\mathbf{q}`: distribution in the target space |
| 465 |
- `L`: loss function to account for the misfit between the similarity and feature matrices |
| 466 |
- :math:`\alpha`: trade-off parameter |
| 467 |
|
| 468 |
.. note:: This function is backend-compatible and will work on arrays |
| 469 |
from all compatible backends. But the algorithm uses the C++ CPU backend |
| 470 |
which can lead to copy overhead on GPU arrays. |
| 471 |
.. note:: All computations in the conjugate gradient solver are done with |
| 472 |
numpy to limit memory overhead. |
| 473 |
.. note:: This function will cast the computed transport plan to the data |
| 474 |
type of the provided input :math:`\mathbf{M}`. Casting to an integer |
| 475 |
tensor might result in a loss of precision. If this behaviour is |
| 476 |
unwanted, please make sure to provide a floating point input. |
| 477 |
|
| 478 |
|
| 479 |
Parameters |
| 480 |
---------- |
| 481 |
M : array-like, shape (ns, nt) |
| 482 |
Metric cost matrix between features across domains |
| 483 |
C1 : array-like, shape (ns, ns) |
| 484 |
Metric cost matrix representative of the structure in the source space |
| 485 |
C2 : array-like, shape (nt, nt) |
| 486 |
Metric cost matrix representative of the structure in the target space |
| 487 |
p : array-like, shape (ns,), optional |
| 488 |
Distribution in the source space. |
| 489 |
If let to its default value None, uniform distribution is taken. |
| 490 |
q : array-like, shape (nt,), optional |
| 491 |
Distribution in the target space. |
| 492 |
If let to its default value None, uniform distribution is taken. |
| 493 |
loss_fun : str, optional |
| 494 |
Loss function used for the solver |
| 495 |
symmetric : bool, optional |
| 496 |
Either C1 and C2 are to be assumed symmetric or not. |
| 497 |
If let to its default None value, a symmetry test will be conducted. |
| 498 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 499 |
alpha : float, optional |
| 500 |
Trade-off parameter (0 < alpha < 1) |
| 501 |
armijo : bool, optional |
| 502 |
If True the step of the line-search is found via an armijo research. Else closed form is used. |
| 503 |
If there are convergence issues use False. |
| 504 |
G0: array-like, shape (ns,nt), optional |
| 505 |
If None the initial transport plan of the solver is pq^T. |
| 506 |
Otherwise G0 must satisfy marginal constraints and will be used as initial transport of the solver. |
| 507 |
log : bool, optional |
| 508 |
record log if True |
| 509 |
max_iter : int, optional |
| 510 |
Max number of iterations |
| 511 |
tol_rel : float, optional |
| 512 |
Stop threshold on relative error (>0) |
| 513 |
tol_abs : float, optional |
| 514 |
Stop threshold on absolute error (>0) |
| 515 |
**kwargs : dict |
| 516 |
parameters can be directly passed to the ot.optim.cg solver |
| 517 |
|
| 518 |
Returns |
| 519 |
------- |
| 520 |
T : array-like, shape (`ns`, `nt`) |
| 521 |
Optimal transportation matrix for the given parameters. |
| 522 |
log : dict |
| 523 |
Log dictionary return only if log==True in parameters. |
| 524 |
|
| 525 |
|
| 526 |
.. _references-fused-gromov-wasserstein: |
| 527 |
References |
| 528 |
---------- |
| 529 |
.. [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain |
| 530 |
and Courty Nicolas "Optimal Transport for structured data with |
| 531 |
application on graphs", International Conference on Machine Learning |
| 532 |
(ICML). 2019. |
| 533 |
|
| 534 |
.. [47] Chowdhury, S., & Mémoli, F. (2019). The gromov–wasserstein |
| 535 |
distance between networks and stable network invariants. |
| 536 |
Information and Inference: A Journal of the IMA, 8(4), 757-787. |
| 537 |
""" |
| 538 |
arr = [C1, C2, M] |
| 539 |
if p is not None: |
| 540 |
arr.append(list_to_array(p)) |
| 541 |
else: |
| 542 |
p = unif(C1.shape[0], type_as=M) |
| 543 |
if q is not None: |
| 544 |
arr.append(list_to_array(q)) |
| 545 |
else: |
| 546 |
q = unif(C2.shape[0], type_as=M) |
| 547 |
if G0 is not None: |
| 548 |
G0_ = G0 |
| 549 |
arr.append(G0) |
| 550 |
|
| 551 |
nx = get_backend(*arr) |
| 552 |
p0, q0, C10, C20, M0, alpha0 = p, q, C1, C2, M, alpha |
| 553 |
|
| 554 |
p = nx.to_numpy(p0) |
| 555 |
q = nx.to_numpy(q0) |
| 556 |
C1 = nx.to_numpy(C10) |
| 557 |
C2 = nx.to_numpy(C20) |
| 558 |
M = nx.to_numpy(M0) |
| 559 |
alpha = nx.to_numpy(alpha0) |
| 560 |
|
| 561 |
if symmetric is None: |
| 562 |
symmetric = np.allclose(C1, C1.T, atol=1e-10) and np.allclose( |
| 563 |
C2, C2.T, atol=1e-10 |
| 564 |
) |
| 565 |
|
| 566 |
if G0 is None: |
| 567 |
G0 = p[:, None] * q[None, :] |
| 568 |
else: |
| 569 |
G0 = nx.to_numpy(G0_) |
| 570 |
|
| 571 |
np.testing.assert_allclose(G0.sum(axis=1), p, atol=1e-08) |
| 572 |
np.testing.assert_allclose(G0.sum(axis=0), q, atol=1e-08) |
| 573 |
|
| 574 |
np_ = NumpyBackend() |
| 575 |
|
| 576 |
constC, hC1, hC2 = init_matrix(C1, C2, p, q, loss_fun, np_) |
| 577 |
|
| 578 |
def f(G): |
| 579 |
return gwloss(constC, hC1, hC2, G, np_) |
| 580 |
|
| 581 |
if symmetric: |
| 582 |
|
| 583 |
def df(G): |
| 584 |
return gwggrad(constC, hC1, hC2, G, np_) |
| 585 |
else: |
| 586 |
constCt, hC1t, hC2t = init_matrix(C1.T, C2.T, p, q, loss_fun, np_) |
| 587 |
|
| 588 |
def df(G): |
| 589 |
return 0.5 * ( |
| 590 |
gwggrad(constC, hC1, hC2, G, np_) + gwggrad(constCt, hC1t, hC2t, G, np_) |
| 591 |
) |
| 592 |
|
| 593 |
if armijo: |
| 594 |
|
| 595 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 596 |
return line_search_armijo(cost, G, deltaG, Mi, cost_G, nx=np_, **kwargs) |
| 597 |
else: |
| 598 |
|
| 599 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 600 |
return solve_gromov_linesearch( |
| 601 |
G, |
| 602 |
deltaG, |
| 603 |
cost_G, |
| 604 |
hC1, |
| 605 |
hC2, |
| 606 |
M=(1 - alpha) * M, |
| 607 |
reg=alpha, |
| 608 |
nx=np_, |
| 609 |
symmetric=symmetric, |
| 610 |
**kwargs, |
| 611 |
) |
| 612 |
|
| 613 |
if not nx.is_floating_point(M0): |
| 614 |
warnings.warn( |
| 615 |
"Input feature matrix consists of integer. The transport plan will be " |
| 616 |
"casted accordingly, possibly resulting in a loss of precision. " |
| 617 |
"If this behaviour is unwanted, please make sure your input " |
| 618 |
"feature matrix consists of floating point elements.", |
| 619 |
stacklevel=2, |
| 620 |
) |
| 621 |
if log: |
| 622 |
res, log = cg( |
| 623 |
p, |
| 624 |
q, |
| 625 |
(1 - alpha) * M, |
| 626 |
alpha, |
| 627 |
f, |
| 628 |
df, |
| 629 |
G0, |
| 630 |
line_search, |
| 631 |
log=True, |
| 632 |
numItermax=max_iter, |
| 633 |
stopThr=tol_rel, |
| 634 |
stopThr2=tol_abs, |
| 635 |
**kwargs, |
| 636 |
) |
| 637 |
log["fgw_dist"] = nx.from_numpy(log["loss"][-1], type_as=M0) |
| 638 |
log["u"] = nx.from_numpy(log["u"], type_as=M0) |
| 639 |
log["v"] = nx.from_numpy(log["v"], type_as=M0) |
| 640 |
return nx.from_numpy(res, type_as=M0), log |
| 641 |
else: |
| 642 |
return nx.from_numpy( |
| 643 |
cg( |
| 644 |
p, |
| 645 |
q, |
| 646 |
(1 - alpha) * M, |
| 647 |
alpha, |
| 648 |
f, |
| 649 |
df, |
| 650 |
G0, |
| 651 |
line_search, |
| 652 |
log=False, |
| 653 |
numItermax=max_iter, |
| 654 |
stopThr=tol_rel, |
| 655 |
stopThr2=tol_abs, |
| 656 |
**kwargs, |
| 657 |
), |
| 658 |
type_as=M0, |
| 659 |
) |
| 660 |
|
| 661 |
|
| 662 |
def fused_gromov_wasserstein2( |
| 663 |
M, |
| 664 |
C1, |
| 665 |
C2, |
| 666 |
p=None, |
| 667 |
q=None, |
| 668 |
loss_fun="square_loss", |
| 669 |
symmetric=None, |
| 670 |
alpha=0.5, |
| 671 |
armijo=False, |
| 672 |
G0=None, |
| 673 |
log=False, |
| 674 |
max_iter=1e4, |
| 675 |
tol_rel=1e-9, |
| 676 |
tol_abs=1e-9, |
| 677 |
**kwargs, |
| 678 |
): |
| 679 |
r""" |
| 680 |
Returns the Fused Gromov-Wasserstein distance between :math:`(\mathbf{C_1}, \mathbf{Y_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{Y_2}, \mathbf{q})` |
| 681 |
with pairwise distance matrix :math:`\mathbf{M}` between node feature matrices :math:`\mathbf{Y_1}` and :math:`\mathbf{Y_2}` (see :ref:`[24] <references-fused-gromov-wasserstein>`). |
| 682 |
|
| 683 |
The function solves the following optimization problem using Conditional Gradient: |
| 684 |
|
| 685 |
.. math:: |
| 686 |
\mathbf{FGW} = \mathop{\min}_\mathbf{T} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F + |
| 687 |
\alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 688 |
|
| 689 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 690 |
|
| 691 |
\mathbf{T}^T \mathbf{1} &= \mathbf{q} |
| 692 |
|
| 693 |
\mathbf{T} &\geq 0 |
| 694 |
Where : |
| 695 |
|
| 696 |
- :math:`\mathbf{M}`: metric cost matrix between features across domains |
| 697 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 698 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 699 |
- :math:`\mathbf{p}`: distribution in the source space |
| 700 |
- :math:`\mathbf{q}`: distribution in the target space |
| 701 |
- `L`: loss function to account for the misfit between the similarity and feature matrices |
| 702 |
- :math:`\alpha`: trade-off parameter |
| 703 |
|
| 704 |
Note that when using backends, this loss function is differentiable wrt the |
| 705 |
matrices (C1, C2, M) and weights (p, q) for quadratic loss using the gradients from [38]_. |
| 706 |
|
| 707 |
.. note:: This function is backend-compatible and will work on arrays |
| 708 |
from all compatible backends. But the algorithm uses the C++ CPU backend |
| 709 |
which can lead to copy overhead on GPU arrays. |
| 710 |
.. note:: All computations in the conjugate gradient solver are done with |
| 711 |
numpy to limit memory overhead. |
| 712 |
.. note:: This function will cast the computed transport plan to the data |
| 713 |
type of the provided input :math:`\mathbf{M}`. Casting to an integer |
| 714 |
tensor might result in a loss of precision. If this behaviour is |
| 715 |
unwanted, please make sure to provide a floating point input. |
| 716 |
|
| 717 |
Parameters |
| 718 |
---------- |
| 719 |
M : array-like, shape (ns, nt) |
| 720 |
Metric cost matrix between features across domains |
| 721 |
C1 : array-like, shape (ns, ns) |
| 722 |
Metric cost matrix representative of the structure in the source space. |
| 723 |
C2 : array-like, shape (nt, nt) |
| 724 |
Metric cost matrix representative of the structure in the target space. |
| 725 |
p : array-like, shape (ns,), optional |
| 726 |
Distribution in the source space. |
| 727 |
If let to its default value None, uniform distribution is taken. |
| 728 |
q : array-like, shape (nt,), optional |
| 729 |
Distribution in the target space. |
| 730 |
If let to its default value None, uniform distribution is taken. |
| 731 |
loss_fun : str, optional |
| 732 |
Loss function used for the solver. |
| 733 |
symmetric : bool, optional |
| 734 |
Either C1 and C2 are to be assumed symmetric or not. |
| 735 |
If let to its default None value, a symmetry test will be conducted. |
| 736 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 737 |
alpha : float, optional |
| 738 |
Trade-off parameter (0 < alpha < 1) |
| 739 |
armijo : bool, optional |
| 740 |
If True the step of the line-search is found via an armijo research. |
| 741 |
Else closed form is used. If there are convergence issues use False. |
| 742 |
G0: array-like, shape (ns,nt), optional |
| 743 |
If None the initial transport plan of the solver is pq^T. |
| 744 |
Otherwise G0 must satisfy marginal constraints and will be used as initial transport of the solver. |
| 745 |
log : bool, optional |
| 746 |
Record log if True. |
| 747 |
max_iter : int, optional |
| 748 |
Max number of iterations |
| 749 |
tol_rel : float, optional |
| 750 |
Stop threshold on relative error (>0) |
| 751 |
tol_abs : float, optional |
| 752 |
Stop threshold on absolute error (>0) |
| 753 |
**kwargs : dict |
| 754 |
Parameters can be directly passed to the ot.optim.cg solver. |
| 755 |
|
| 756 |
Returns |
| 757 |
------- |
| 758 |
fgw-distance : float |
| 759 |
Fused Gromov-Wasserstein distance for the given parameters. |
| 760 |
log : dict |
| 761 |
Log dictionary return only if log==True in parameters. |
| 762 |
|
| 763 |
|
| 764 |
.. _references-fused-gromov-wasserstein2: |
| 765 |
References |
| 766 |
---------- |
| 767 |
.. [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain |
| 768 |
and Courty Nicolas |
| 769 |
"Optimal Transport for structured data with application on graphs" |
| 770 |
International Conference on Machine Learning (ICML). 2019. |
| 771 |
|
| 772 |
.. [38] C. Vincent-Cuaz, T. Vayer, R. Flamary, M. Corneli, N. Courty, Online |
| 773 |
Graph Dictionary Learning, International Conference on Machine Learning |
| 774 |
(ICML), 2021. |
| 775 |
|
| 776 |
.. [47] Chowdhury, S., & Mémoli, F. (2019). The gromov–wasserstein |
| 777 |
distance between networks and stable network invariants. |
| 778 |
Information and Inference: A Journal of the IMA, 8(4), 757-787. |
| 779 |
""" |
| 780 |
nx = get_backend(C1, C2, M) |
| 781 |
|
| 782 |
|
| 783 |
if p is None: |
| 784 |
p = unif(C1.shape[0], type_as=M) |
| 785 |
if q is None: |
| 786 |
q = unif(C2.shape[0], type_as=M) |
| 787 |
|
| 788 |
T, log_fgw = fused_gromov_wasserstein( |
| 789 |
M, |
| 790 |
C1, |
| 791 |
C2, |
| 792 |
p, |
| 793 |
q, |
| 794 |
loss_fun, |
| 795 |
symmetric, |
| 796 |
alpha, |
| 797 |
armijo, |
| 798 |
G0, |
| 799 |
log=True, |
| 800 |
max_iter=max_iter, |
| 801 |
tol_rel=tol_rel, |
| 802 |
tol_abs=tol_abs, |
| 803 |
**kwargs, |
| 804 |
) |
| 805 |
|
| 806 |
fgw_dist = log_fgw["fgw_dist"] |
| 807 |
log_fgw["T"] = T |
| 808 |
|
| 809 |
|
| 810 |
lin_term = nx.sum(T * M) |
| 811 |
log_fgw["quad_loss"] = fgw_dist - (1 - alpha) * lin_term |
| 812 |
log_fgw["lin_loss"] = lin_term * (1 - alpha) |
| 813 |
gw_term = log_fgw["quad_loss"] / alpha |
| 814 |
|
| 815 |
if loss_fun == "square_loss": |
| 816 |
gC1 = 2 * C1 * nx.outer(p, p) - 2 * nx.dot(T, nx.dot(C2, T.T)) |
| 817 |
gC2 = 2 * C2 * nx.outer(q, q) - 2 * nx.dot(T.T, nx.dot(C1, T)) |
| 818 |
|
| 819 |
elif loss_fun == "kl_loss": |
| 820 |
gC1 = nx.log(C1 + 1e-15) * nx.outer(p, p) - nx.dot( |
| 821 |
T, nx.dot(nx.log(C2 + 1e-15), T.T) |
| 822 |
) |
| 823 |
gC2 = -nx.dot(T.T, nx.dot(C1, T)) / (C2 + 1e-15) + nx.outer(q, q) |
| 824 |
|
| 825 |
if isinstance(alpha, int) or isinstance(alpha, float): |
| 826 |
fgw_dist = nx.set_gradients( |
| 827 |
fgw_dist, |
| 828 |
(p, q, C1, C2, M), |
| 829 |
( |
| 830 |
log_fgw["u"] - nx.mean(log_fgw["u"]), |
| 831 |
log_fgw["v"] - nx.mean(log_fgw["v"]), |
| 832 |
alpha * gC1, |
| 833 |
alpha * gC2, |
| 834 |
(1 - alpha) * T, |
| 835 |
), |
| 836 |
) |
| 837 |
else: |
| 838 |
fgw_dist = nx.set_gradients( |
| 839 |
fgw_dist, |
| 840 |
(p, q, C1, C2, M, alpha), |
| 841 |
( |
| 842 |
log_fgw["u"] - nx.mean(log_fgw["u"]), |
| 843 |
log_fgw["v"] - nx.mean(log_fgw["v"]), |
| 844 |
alpha * gC1, |
| 845 |
alpha * gC2, |
| 846 |
(1 - alpha) * T, |
| 847 |
gw_term - lin_term, |
| 848 |
), |
| 849 |
) |
| 850 |
|
| 851 |
if log: |
| 852 |
return fgw_dist, log_fgw |
| 853 |
else: |
| 854 |
return fgw_dist |
| 855 |
|
| 856 |
|
| 857 |
def solve_gromov_linesearch( |
| 858 |
G, |
| 859 |
deltaG, |
| 860 |
cost_G, |
| 861 |
C1, |
| 862 |
C2, |
| 863 |
M, |
| 864 |
reg, |
| 865 |
alpha_min=None, |
| 866 |
alpha_max=None, |
| 867 |
nx=None, |
| 868 |
symmetric=False, |
| 869 |
**kwargs, |
| 870 |
): |
| 871 |
""" |
| 872 |
Solve the linesearch in the FW iterations for any inner loss that decomposes as in Proposition 1 in :ref:`[12] <references-solve-linesearch>`. |
| 873 |
|
| 874 |
Parameters |
| 875 |
---------- |
| 876 |
|
| 877 |
G : array-like, shape(ns,nt) |
| 878 |
The transport map at a given iteration of the FW |
| 879 |
deltaG : array-like (ns,nt) |
| 880 |
Difference between the optimal map found by linearization in the FW algorithm and the value at a given iteration |
| 881 |
cost_G : float |
| 882 |
Value of the cost at `G` |
| 883 |
C1 : array-like (ns,ns), optional |
| 884 |
Transformed Structure matrix in the source domain. |
| 885 |
For the 'square_loss' and 'kl_loss', we provide hC1 from ot.gromov.init_matrix |
| 886 |
C2 : array-like (nt,nt), optional |
| 887 |
Transformed Structure matrix in the source domain. |
| 888 |
For the 'square_loss' and 'kl_loss', we provide hC2 from ot.gromov.init_matrix |
| 889 |
M : array-like (ns,nt) |
| 890 |
Cost matrix between the features. |
| 891 |
reg : float |
| 892 |
Regularization parameter. |
| 893 |
alpha_min : float, optional |
| 894 |
Minimum value for alpha |
| 895 |
alpha_max : float, optional |
| 896 |
Maximum value for alpha |
| 897 |
nx : backend, optional |
| 898 |
If let to its default value None, a backend test will be conducted. |
| 899 |
symmetric : bool, optional |
| 900 |
Either structures are to be assumed symmetric or not. Default value is False. |
| 901 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 902 |
|
| 903 |
Returns |
| 904 |
------- |
| 905 |
alpha : float |
| 906 |
The optimal step size of the FW |
| 907 |
fc : int |
| 908 |
nb of function call. Useless here |
| 909 |
cost_G : float |
| 910 |
The value of the cost for the next iteration |
| 911 |
|
| 912 |
|
| 913 |
.. _references-solve-linesearch: |
| 914 |
|
| 915 |
References |
| 916 |
---------- |
| 917 |
.. [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain and Courty Nicolas |
| 918 |
"Optimal Transport for structured data with application on graphs" |
| 919 |
International Conference on Machine Learning (ICML). 2019. |
| 920 |
.. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon, |
| 921 |
"Gromov-Wasserstein averaging of kernel and distance matrices." |
| 922 |
International Conference on Machine Learning (ICML). 2016. |
| 923 |
|
| 924 |
""" |
| 925 |
if nx is None: |
| 926 |
if isinstance(M, int) or isinstance(M, float): |
| 927 |
nx = get_backend(G, deltaG, C1, C2) |
| 928 |
else: |
| 929 |
nx = get_backend(G, deltaG, C1, C2, M) |
| 930 |
|
| 931 |
dot = nx.dot(nx.dot(C1, deltaG), C2.T) |
| 932 |
a = -reg * nx.sum(dot * deltaG) |
| 933 |
if symmetric: |
| 934 |
b = nx.sum(M * deltaG) - 2 * reg * nx.sum(dot * G) |
| 935 |
else: |
| 936 |
b = nx.sum(M * deltaG) - reg * ( |
| 937 |
nx.sum(dot * G) + nx.sum(nx.dot(nx.dot(C1, G), C2.T) * deltaG) |
| 938 |
) |
| 939 |
|
| 940 |
alpha = solve_1d_linesearch_quad(a, b) |
| 941 |
if alpha_min is not None or alpha_max is not None: |
| 942 |
alpha = np.clip(alpha, alpha_min, alpha_max) |
| 943 |
|
| 944 |
|
| 945 |
cost_G = cost_G + a * (alpha**2) + b * alpha |
| 946 |
|
| 947 |
return alpha, 1, cost_G |
| 948 |
|
| 949 |
|
| 950 |
def gromov_barycenters( |
| 951 |
N, |
| 952 |
Cs, |
| 953 |
ps=None, |
| 954 |
p=None, |
| 955 |
lambdas=None, |
| 956 |
loss_fun="square_loss", |
| 957 |
symmetric=True, |
| 958 |
armijo=False, |
| 959 |
max_iter=1000, |
| 960 |
tol=1e-9, |
| 961 |
stop_criterion="barycenter", |
| 962 |
warmstartT=False, |
| 963 |
verbose=False, |
| 964 |
log=False, |
| 965 |
init_C=None, |
| 966 |
random_state=None, |
| 967 |
**kwargs, |
| 968 |
): |
| 969 |
r""" |
| 970 |
Returns the Gromov-Wasserstein barycenters of `S` measured similarity matrices :math:`(\mathbf{C}_s)_{1 \leq s \leq S}` |
| 971 |
|
| 972 |
The function solves the following optimization problem with block coordinate descent: |
| 973 |
|
| 974 |
.. math:: |
| 975 |
|
| 976 |
\mathbf{C}^* = \mathop{\arg \min}_{\mathbf{C}\in \mathbb{R}^{N \times N}} \quad \sum_s \lambda_s \mathrm{GW}(\mathbf{C}, \mathbf{C}_s, \mathbf{p}, \mathbf{p}_s) |
| 977 |
|
| 978 |
Where : |
| 979 |
|
| 980 |
- :math:`\mathbf{C}_s`: metric cost matrix |
| 981 |
- :math:`\mathbf{p}_s`: distribution |
| 982 |
|
| 983 |
Parameters |
| 984 |
---------- |
| 985 |
N : int |
| 986 |
Size of the targeted barycenter |
| 987 |
Cs : list of S array-like of shape (ns, ns) |
| 988 |
Metric cost matrices |
| 989 |
ps : list of S array-like of shape (ns,), optional |
| 990 |
Sample weights in the `S` spaces. |
| 991 |
If let to its default value None, uniform distributions are taken. |
| 992 |
p : array-like, shape (N,), optional |
| 993 |
Weights in the targeted barycenter. |
| 994 |
If let to its default value None, uniform distribution is taken. |
| 995 |
lambdas : list of float, optional |
| 996 |
List of the `S` spaces' weights. |
| 997 |
If let to its default value None, uniform weights are taken. |
| 998 |
loss_fun : callable, optional |
| 999 |
tensor-matrix multiplication function based on specific loss function |
| 1000 |
symmetric : bool, optional. |
| 1001 |
Either structures are to be assumed symmetric or not. Default value is True. |
| 1002 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 1003 |
armijo : bool, optional |
| 1004 |
If True the step of the line-search is found via an armijo research. |
| 1005 |
Else closed form is used. If there are convergence issues use False. |
| 1006 |
max_iter : int, optional |
| 1007 |
Max number of iterations |
| 1008 |
tol : float, optional |
| 1009 |
Stop threshold on relative error (>0) |
| 1010 |
stop_criterion : str, optional. Default is 'barycenter'. |
| 1011 |
Stop criterion taking values in ['barycenter', 'loss']. If set to 'barycenter' |
| 1012 |
uses absolute norm variations of estimated barycenters. Else if set to 'loss' |
| 1013 |
uses the relative variations of the loss. |
| 1014 |
warmstartT: bool, optional |
| 1015 |
Either to perform warmstart of transport plans in the successive |
| 1016 |
fused gromov-wasserstein transport problems.s |
| 1017 |
verbose : bool, optional |
| 1018 |
Print information along iterations. |
| 1019 |
log : bool, optional |
| 1020 |
Record log if True. |
| 1021 |
init_C : bool | array-like, shape(N,N) |
| 1022 |
Random initial value for the :math:`\mathbf{C}` matrix provided by user. |
| 1023 |
random_state : int or RandomState instance, optional |
| 1024 |
Fix the seed for reproducibility |
| 1025 |
|
| 1026 |
Returns |
| 1027 |
------- |
| 1028 |
C : array-like, shape (`N`, `N`) |
| 1029 |
Similarity matrix in the barycenter space (permutated arbitrarily) |
| 1030 |
log : dict |
| 1031 |
Only returned when log=True. It contains the keys: |
| 1032 |
|
| 1033 |
- :math:`\mathbf{T}`: list of (`N`, `ns`) transport matrices |
| 1034 |
- :math:`\mathbf{p}`: (`N`,) barycenter weights |
| 1035 |
- values used in convergence evaluation. |
| 1036 |
|
| 1037 |
References |
| 1038 |
---------- |
| 1039 |
.. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon, |
| 1040 |
"Gromov-Wasserstein averaging of kernel and distance matrices." |
| 1041 |
International Conference on Machine Learning (ICML). 2016. |
| 1042 |
|
| 1043 |
""" |
| 1044 |
if stop_criterion not in ["barycenter", "loss"]: |
| 1045 |
raise ValueError( |
| 1046 |
f"Unknown `stop_criterion='{stop_criterion}'`. Use one of: {'barycenter', 'loss'}." |
| 1047 |
) |
| 1048 |
|
| 1049 |
if isinstance(Cs[0], list): |
| 1050 |
raise ValueError( |
| 1051 |
"Deprecated feature in POT 0.9.4: structures Cs[i] are lists and should be arrays from a supported backend (e.g numpy)." |
| 1052 |
) |
| 1053 |
|
| 1054 |
arr = [*Cs] |
| 1055 |
if ps is not None: |
| 1056 |
if isinstance(ps[0], list): |
| 1057 |
raise ValueError( |
| 1058 |
"Deprecated feature in POT 0.9.4: weights ps[i] are lists and should be arrays from a supported backend (e.g numpy)." |
| 1059 |
) |
| 1060 |
|
| 1061 |
arr += [*ps] |
| 1062 |
else: |
| 1063 |
ps = [unif(C.shape[0], type_as=C) for C in Cs] |
| 1064 |
if p is not None: |
| 1065 |
arr.append(list_to_array(p)) |
| 1066 |
else: |
| 1067 |
p = unif(N, type_as=Cs[0]) |
| 1068 |
|
| 1069 |
nx = get_backend(*arr) |
| 1070 |
|
| 1071 |
S = len(Cs) |
| 1072 |
if lambdas is None: |
| 1073 |
lambdas = [1.0 / S] * S |
| 1074 |
|
| 1075 |
|
| 1076 |
if init_C is None: |
| 1077 |
rng = check_random_state(random_state) |
| 1078 |
xalea = rng.randn(N, 2) |
| 1079 |
C = dist(xalea, xalea) |
| 1080 |
C /= C.max() |
| 1081 |
C = nx.from_numpy(C, type_as=p) |
| 1082 |
else: |
| 1083 |
C = init_C |
| 1084 |
|
| 1085 |
if warmstartT: |
| 1086 |
T = [None] * S |
| 1087 |
|
| 1088 |
if stop_criterion == "barycenter": |
| 1089 |
inner_log = False |
| 1090 |
else: |
| 1091 |
inner_log = True |
| 1092 |
curr_loss = 1e15 |
| 1093 |
|
| 1094 |
if log: |
| 1095 |
log_ = {} |
| 1096 |
log_["err"] = [] |
| 1097 |
if stop_criterion == "loss": |
| 1098 |
log_["loss"] = [] |
| 1099 |
|
| 1100 |
for cpt in range(max_iter): |
| 1101 |
if stop_criterion == "barycenter": |
| 1102 |
Cprev = C |
| 1103 |
else: |
| 1104 |
prev_loss = curr_loss |
| 1105 |
|
| 1106 |
|
| 1107 |
if warmstartT: |
| 1108 |
res = [ |
| 1109 |
gromov_wasserstein( |
| 1110 |
C, |
| 1111 |
Cs[s], |
| 1112 |
p, |
| 1113 |
ps[s], |
| 1114 |
loss_fun, |
| 1115 |
symmetric=symmetric, |
| 1116 |
armijo=armijo, |
| 1117 |
G0=T[s], |
| 1118 |
max_iter=max_iter, |
| 1119 |
tol_rel=1e-5, |
| 1120 |
tol_abs=0.0, |
| 1121 |
log=inner_log, |
| 1122 |
verbose=verbose, |
| 1123 |
**kwargs, |
| 1124 |
) |
| 1125 |
for s in range(S) |
| 1126 |
] |
| 1127 |
else: |
| 1128 |
res = [ |
| 1129 |
gromov_wasserstein( |
| 1130 |
C, |
| 1131 |
Cs[s], |
| 1132 |
p, |
| 1133 |
ps[s], |
| 1134 |
loss_fun, |
| 1135 |
symmetric=symmetric, |
| 1136 |
armijo=armijo, |
| 1137 |
G0=None, |
| 1138 |
max_iter=max_iter, |
| 1139 |
tol_rel=1e-5, |
| 1140 |
tol_abs=0.0, |
| 1141 |
log=inner_log, |
| 1142 |
verbose=verbose, |
| 1143 |
**kwargs, |
| 1144 |
) |
| 1145 |
for s in range(S) |
| 1146 |
] |
| 1147 |
if stop_criterion == "barycenter": |
| 1148 |
T = res |
| 1149 |
else: |
| 1150 |
T = [output[0] for output in res] |
| 1151 |
curr_loss = np.sum([output[1]["gw_dist"] for output in res]) |
| 1152 |
|
| 1153 |
|
| 1154 |
C = update_barycenter_structure( |
| 1155 |
T, Cs, lambdas, p, loss_fun, target=False, check_zeros=False, nx=nx |
| 1156 |
) |
| 1157 |
|
| 1158 |
|
| 1159 |
if stop_criterion == "barycenter": |
| 1160 |
err = nx.norm(C - Cprev) |
| 1161 |
if log: |
| 1162 |
log_["err"].append(err) |
| 1163 |
|
| 1164 |
else: |
| 1165 |
err = abs(curr_loss - prev_loss) / prev_loss if prev_loss != 0.0 else np.nan |
| 1166 |
if log: |
| 1167 |
log_["loss"].append(curr_loss) |
| 1168 |
log_["err"].append(err) |
| 1169 |
|
| 1170 |
if verbose: |
| 1171 |
if cpt % 200 == 0: |
| 1172 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1173 |
print("{:5d}|{:8e}|".format(cpt, err)) |
| 1174 |
|
| 1175 |
if err <= tol: |
| 1176 |
break |
| 1177 |
|
| 1178 |
if log: |
| 1179 |
log_["T"] = T |
| 1180 |
log_["p"] = p |
| 1181 |
|
| 1182 |
return C, log_ |
| 1183 |
else: |
| 1184 |
return C |
| 1185 |
|
| 1186 |
|
| 1187 |
def fgw_barycenters( |
| 1188 |
N, |
| 1189 |
Ys, |
| 1190 |
Cs, |
| 1191 |
ps=None, |
| 1192 |
lambdas=None, |
| 1193 |
alpha=0.5, |
| 1194 |
fixed_structure=False, |
| 1195 |
fixed_features=False, |
| 1196 |
p=None, |
| 1197 |
loss_fun="square_loss", |
| 1198 |
armijo=False, |
| 1199 |
symmetric=True, |
| 1200 |
max_iter=100, |
| 1201 |
tol=1e-9, |
| 1202 |
stop_criterion="barycenter", |
| 1203 |
warmstartT=False, |
| 1204 |
verbose=False, |
| 1205 |
log=False, |
| 1206 |
init_C=None, |
| 1207 |
init_X=None, |
| 1208 |
random_state=None, |
| 1209 |
**kwargs, |
| 1210 |
): |
| 1211 |
r""" |
| 1212 |
Returns the Fused Gromov-Wasserstein barycenters of `S` measurable networks with node features :math:`(\mathbf{C}_s, \mathbf{Y}_s, \mathbf{p}_s)_{1 \leq s \leq S}` |
| 1213 |
(see eq (5) in :ref:`[24] <references-fgw-barycenters>`), estimated using Fused Gromov-Wasserstein transports from Conditional Gradient solvers. |
| 1214 |
|
| 1215 |
The function solves the following optimization problem: |
| 1216 |
|
| 1217 |
.. math:: |
| 1218 |
|
| 1219 |
\mathbf{C}^*, \mathbf{Y}^* = \mathop{\arg \min}_{\mathbf{C}\in \mathbb{R}^{N \times N}, \mathbf{Y}\in \mathbb{Y}^{N \times d}} \quad \sum_s \lambda_s \mathrm{FGW}_{\alpha}(\mathbf{C}, \mathbf{C}_s, \mathbf{Y}, \mathbf{Y}_s, \mathbf{p}, \mathbf{p}_s) |
| 1220 |
|
| 1221 |
Where : |
| 1222 |
|
| 1223 |
- :math:`\mathbf{Y}_s`: feature matrix |
| 1224 |
- :math:`\mathbf{C}_s`: metric cost matrix |
| 1225 |
- :math:`\mathbf{p}_s`: distribution |
| 1226 |
|
| 1227 |
Parameters |
| 1228 |
---------- |
| 1229 |
N : int |
| 1230 |
Desired number of samples of the target barycenter |
| 1231 |
Ys: list of array-like, each element has shape (ns,d) |
| 1232 |
Features of all samples |
| 1233 |
Cs : list of array-like, each element has shape (ns,ns) |
| 1234 |
Structure matrices of all samples |
| 1235 |
ps : list of array-like, each element has shape (ns,), optional |
| 1236 |
Masses of all samples. |
| 1237 |
If let to its default value None, uniform distributions are taken. |
| 1238 |
lambdas : list of float, optional |
| 1239 |
List of the `S` spaces' weights. |
| 1240 |
If let to its default value None, uniform weights are taken. |
| 1241 |
alpha : float, optional |
| 1242 |
Alpha parameter for the fgw distance. |
| 1243 |
fixed_structure : bool, optional |
| 1244 |
Whether to fix the structure of the barycenter during the updates. |
| 1245 |
fixed_features : bool, optional |
| 1246 |
Whether to fix the feature of the barycenter during the updates |
| 1247 |
p : array-like, shape (N,), optional |
| 1248 |
Weights in the targeted barycenter. |
| 1249 |
If let to its default value None, uniform distribution is taken. |
| 1250 |
loss_fun : str, optional |
| 1251 |
Loss function used for the solver either 'square_loss' or 'kl_loss' |
| 1252 |
armijo : bool, optional |
| 1253 |
If True the step of the line-search is found via an armijo research. |
| 1254 |
Else closed form is used. If there are convergence issues use False. |
| 1255 |
symmetric : bool, optional |
| 1256 |
Either structures are to be assumed symmetric or not. Default value is True. |
| 1257 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 1258 |
max_iter : int, optional |
| 1259 |
Max number of iterations |
| 1260 |
tol : float, optional |
| 1261 |
Stop threshold on relative error (>0) |
| 1262 |
stop_criterion : str, optional. Default is 'barycenter'. |
| 1263 |
Stop criterion taking values in ['barycenter', 'loss']. If set to 'barycenter' |
| 1264 |
uses absolute norm variations of estimated barycenters. Else if set to 'loss' |
| 1265 |
uses the relative variations of the loss. |
| 1266 |
warmstartT: bool, optional |
| 1267 |
Either to perform warmstart of transport plans in the successive |
| 1268 |
fused gromov-wasserstein transport problems. |
| 1269 |
verbose : bool, optional |
| 1270 |
Print information along iterations. |
| 1271 |
log : bool, optional |
| 1272 |
Record log if True. |
| 1273 |
init_C : array-like, shape (N,N), optional |
| 1274 |
Initialization for the barycenters' structure matrix. If not set |
| 1275 |
a random init is used. |
| 1276 |
init_X : array-like, shape (N,d), optional |
| 1277 |
Initialization for the barycenters' features. If not set a |
| 1278 |
random init is used. |
| 1279 |
random_state : int or RandomState instance, optional |
| 1280 |
Fix the seed for reproducibility |
| 1281 |
|
| 1282 |
Returns |
| 1283 |
------- |
| 1284 |
X : array-like, shape (`N`, `d`) |
| 1285 |
Barycenters' features |
| 1286 |
C : array-like, shape (`N`, `N`) |
| 1287 |
Barycenters' structure matrix |
| 1288 |
log : dict |
| 1289 |
Only returned when log=True. It contains the keys: |
| 1290 |
|
| 1291 |
- :math:`\mathbf{T}`: list of (`N`, `ns`) transport matrices |
| 1292 |
- :math:`\mathbf{p}`: (`N`,) barycenter weights |
| 1293 |
- :math:`(\mathbf{M}_s)_s`: all distance matrices between the feature of the barycenter and the other features :math:`(dist(\mathbf{X}, \mathbf{Y}_s))_s` shape (`N`, `ns`) |
| 1294 |
- values used in convergence evaluation. |
| 1295 |
|
| 1296 |
.. _references-fgw-barycenters: |
| 1297 |
References |
| 1298 |
---------- |
| 1299 |
.. [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain |
| 1300 |
and Courty Nicolas |
| 1301 |
"Optimal Transport for structured data with application on graphs" |
| 1302 |
International Conference on Machine Learning (ICML). 2019. |
| 1303 |
""" |
| 1304 |
if stop_criterion not in ["barycenter", "loss"]: |
| 1305 |
raise ValueError( |
| 1306 |
f"Unknown `stop_criterion='{stop_criterion}'`. Use one of: {'barycenter', 'loss'}." |
| 1307 |
) |
| 1308 |
|
| 1309 |
if isinstance(Cs[0], list) or isinstance(Ys[0], list): |
| 1310 |
raise ValueError( |
| 1311 |
"Deprecated feature in POT 0.9.4: structures Cs[i] and/or features Ys[i] are lists and should be arrays from a supported backend (e.g numpy)." |
| 1312 |
) |
| 1313 |
|
| 1314 |
arr = [*Cs, *Ys] |
| 1315 |
if ps is not None: |
| 1316 |
if isinstance(ps[0], list): |
| 1317 |
raise ValueError( |
| 1318 |
"Deprecated feature in POT 0.9.4: weights ps[i] are lists and should be arrays from a supported backend (e.g numpy)." |
| 1319 |
) |
| 1320 |
|
| 1321 |
arr += [*ps] |
| 1322 |
else: |
| 1323 |
ps = [unif(C.shape[0], type_as=C) for C in Cs] |
| 1324 |
if p is not None: |
| 1325 |
arr.append(list_to_array(p)) |
| 1326 |
else: |
| 1327 |
p = unif(N, type_as=Cs[0]) |
| 1328 |
|
| 1329 |
nx = get_backend(*arr) |
| 1330 |
|
| 1331 |
S = len(Cs) |
| 1332 |
if lambdas is None: |
| 1333 |
lambdas = [1.0 / S] * S |
| 1334 |
|
| 1335 |
d = Ys[0].shape[1] |
| 1336 |
|
| 1337 |
if fixed_structure: |
| 1338 |
if init_C is None: |
| 1339 |
raise UndefinedParameter("If C is fixed it must be provided in init_C") |
| 1340 |
else: |
| 1341 |
C = init_C |
| 1342 |
else: |
| 1343 |
if init_C is None: |
| 1344 |
rng = check_random_state(random_state) |
| 1345 |
xalea = rng.randn(N, 2) |
| 1346 |
C = dist(xalea, xalea) |
| 1347 |
C = nx.from_numpy(C, type_as=ps[0]) |
| 1348 |
else: |
| 1349 |
C = init_C |
| 1350 |
|
| 1351 |
if fixed_features: |
| 1352 |
if init_X is None: |
| 1353 |
raise UndefinedParameter("If X is fixed it must be provided in init_X") |
| 1354 |
else: |
| 1355 |
X = init_X |
| 1356 |
else: |
| 1357 |
if init_X is None: |
| 1358 |
X = nx.zeros((N, d), type_as=ps[0]) |
| 1359 |
|
| 1360 |
else: |
| 1361 |
X = init_X |
| 1362 |
|
| 1363 |
Ms = [dist(X, Ys[s]) for s in range(len(Ys))] |
| 1364 |
|
| 1365 |
if warmstartT: |
| 1366 |
T = [None] * S |
| 1367 |
|
| 1368 |
if stop_criterion == "barycenter": |
| 1369 |
inner_log = False |
| 1370 |
|
| 1371 |
else: |
| 1372 |
inner_log = True |
| 1373 |
curr_loss = 1e15 |
| 1374 |
|
| 1375 |
if log: |
| 1376 |
log_ = {} |
| 1377 |
if stop_criterion == "barycenter": |
| 1378 |
log_["err_feature"] = [] |
| 1379 |
log_["err_structure"] = [] |
| 1380 |
log_["Ts_iter"] = [] |
| 1381 |
else: |
| 1382 |
log_["loss"] = [] |
| 1383 |
log_["err_rel_loss"] = [] |
| 1384 |
|
| 1385 |
for cpt in range(max_iter): |
| 1386 |
if stop_criterion == "barycenter": |
| 1387 |
Cprev = C |
| 1388 |
Xprev = X |
| 1389 |
else: |
| 1390 |
prev_loss = curr_loss |
| 1391 |
|
| 1392 |
|
| 1393 |
if warmstartT: |
| 1394 |
res = [ |
| 1395 |
fused_gromov_wasserstein( |
| 1396 |
Ms[s], |
| 1397 |
C, |
| 1398 |
Cs[s], |
| 1399 |
p, |
| 1400 |
ps[s], |
| 1401 |
loss_fun=loss_fun, |
| 1402 |
alpha=alpha, |
| 1403 |
armijo=armijo, |
| 1404 |
symmetric=symmetric, |
| 1405 |
G0=T[s], |
| 1406 |
max_iter=max_iter, |
| 1407 |
tol_rel=1e-5, |
| 1408 |
tol_abs=0.0, |
| 1409 |
log=inner_log, |
| 1410 |
verbose=verbose, |
| 1411 |
**kwargs, |
| 1412 |
) |
| 1413 |
for s in range(S) |
| 1414 |
] |
| 1415 |
else: |
| 1416 |
res = [ |
| 1417 |
fused_gromov_wasserstein( |
| 1418 |
Ms[s], |
| 1419 |
C, |
| 1420 |
Cs[s], |
| 1421 |
p, |
| 1422 |
ps[s], |
| 1423 |
loss_fun=loss_fun, |
| 1424 |
alpha=alpha, |
| 1425 |
armijo=armijo, |
| 1426 |
symmetric=symmetric, |
| 1427 |
G0=None, |
| 1428 |
max_iter=max_iter, |
| 1429 |
tol_rel=1e-5, |
| 1430 |
tol_abs=0.0, |
| 1431 |
log=inner_log, |
| 1432 |
verbose=verbose, |
| 1433 |
**kwargs, |
| 1434 |
) |
| 1435 |
for s in range(S) |
| 1436 |
] |
| 1437 |
if stop_criterion == "barycenter": |
| 1438 |
T = res |
| 1439 |
else: |
| 1440 |
T = [output[0] for output in res] |
| 1441 |
curr_loss = np.sum([output[1]["fgw_dist"] for output in res]) |
| 1442 |
|
| 1443 |
|
| 1444 |
if not fixed_features: |
| 1445 |
X = update_barycenter_feature( |
| 1446 |
T, Ys, lambdas, p, target=False, check_zeros=False, nx=nx |
| 1447 |
) |
| 1448 |
|
| 1449 |
Ms = [dist(X, Ys[s]) for s in range(len(Ys))] |
| 1450 |
|
| 1451 |
if not fixed_structure: |
| 1452 |
C = update_barycenter_structure( |
| 1453 |
T, Cs, lambdas, p, loss_fun, target=False, check_zeros=False, nx=nx |
| 1454 |
) |
| 1455 |
|
| 1456 |
|
| 1457 |
if stop_criterion == "barycenter": |
| 1458 |
err_feature, err_structure = 0.0, 0.0 |
| 1459 |
if not fixed_features: |
| 1460 |
err_feature = nx.norm(X - Xprev) |
| 1461 |
if not fixed_structure: |
| 1462 |
err_structure = nx.norm(C - Cprev) |
| 1463 |
if log: |
| 1464 |
log_["err_feature"].append(err_feature) |
| 1465 |
log_["err_structure"].append(err_structure) |
| 1466 |
log_["Ts_iter"].append(T) |
| 1467 |
|
| 1468 |
if verbose: |
| 1469 |
if cpt % 200 == 0: |
| 1470 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1471 |
print("{:5d}|{:8e}|".format(cpt, err_structure)) |
| 1472 |
print("{:5d}|{:8e}|".format(cpt, err_feature)) |
| 1473 |
|
| 1474 |
if (err_feature <= tol) or (err_structure <= tol): |
| 1475 |
break |
| 1476 |
else: |
| 1477 |
err_rel_loss = ( |
| 1478 |
abs(curr_loss - prev_loss) / prev_loss if prev_loss != 0.0 else np.nan |
| 1479 |
) |
| 1480 |
if log: |
| 1481 |
log_["loss"].append(curr_loss) |
| 1482 |
log_["err_rel_loss"].append(err_rel_loss) |
| 1483 |
|
| 1484 |
if verbose: |
| 1485 |
if cpt % 200 == 0: |
| 1486 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1487 |
print("{:5d}|{:8e}|".format(cpt, err_rel_loss)) |
| 1488 |
|
| 1489 |
if err_rel_loss <= tol: |
| 1490 |
break |
| 1491 |
|
| 1492 |
if log: |
| 1493 |
log_["T"] = T |
| 1494 |
log_["p"] = p |
| 1495 |
log_["Ms"] = Ms |
| 1496 |
|
| 1497 |
return X, C, log_ |
| 1498 |
else: |
| 1499 |
return X, C |