| 1 |
|
| 2 |
""" |
| 3 |
Semi-relaxed Gromov-Wasserstein and Fused-Gromov-Wasserstein solvers. |
| 4 |
""" |
| 5 |
|
| 6 |
> |
| 7 |
> |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
import numpy as np |
| 12 |
|
| 13 |
|
| 14 |
from ..utils import list_to_array, unif, dist, UndefinedParameter |
| 15 |
from ..optim import semirelaxed_cg, solve_1d_linesearch_quad |
| 16 |
from ..backend import get_backend |
| 17 |
|
| 18 |
from ._utils import ( |
| 19 |
init_matrix_semirelaxed, |
| 20 |
gwloss, |
| 21 |
gwggrad, |
| 22 |
update_barycenter_structure, |
| 23 |
update_barycenter_feature, |
| 24 |
semirelaxed_init_plan, |
| 25 |
) |
| 26 |
|
| 27 |
try: |
| 28 |
from sklearn.cluster import KMeans |
| 29 |
|
| 30 |
sklearn_import = True |
| 31 |
except ImportError: |
| 32 |
sklearn_import = False |
| 33 |
|
| 34 |
|
| 35 |
def semirelaxed_gromov_wasserstein( |
| 36 |
C1, |
| 37 |
C2, |
| 38 |
p=None, |
| 39 |
loss_fun="square_loss", |
| 40 |
symmetric=None, |
| 41 |
log=False, |
| 42 |
G0=None, |
| 43 |
max_iter=1e4, |
| 44 |
tol_rel=1e-9, |
| 45 |
tol_abs=1e-9, |
| 46 |
random_state=0, |
| 47 |
**kwargs, |
| 48 |
): |
| 49 |
r""" |
| 50 |
Returns the semi-relaxed Gromov-Wasserstein divergence transport from :math:`(\mathbf{C_1}, \mathbf{p})` to :math:`\mathbf{C_2}` (see [48]). |
| 51 |
|
| 52 |
The function solves the following optimization problem using Conditional Gradient: |
| 53 |
|
| 54 |
.. math:: |
| 55 |
\mathbf{T}^* \in \mathop{\arg \min}_{\mathbf{T}} \quad \sum_{i,j,k,l} |
| 56 |
L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 57 |
|
| 58 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 59 |
|
| 60 |
\mathbf{T} &\geq 0 |
| 61 |
|
| 62 |
Where : |
| 63 |
|
| 64 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 65 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 66 |
- :math:`\mathbf{p}`: distribution in the source space |
| 67 |
|
| 68 |
- `L`: loss function to account for the misfit between the similarity matrices |
| 69 |
|
| 70 |
.. note:: This function is backend-compatible and will work on arrays |
| 71 |
from all compatible backends. However all the steps in the conditional |
| 72 |
gradient are not differentiable. |
| 73 |
|
| 74 |
Parameters |
| 75 |
---------- |
| 76 |
C1 : array-like, shape (ns, ns) |
| 77 |
Metric cost matrix in the source space |
| 78 |
C2 : array-like, shape (nt, nt) |
| 79 |
Metric cost matrix in the target space |
| 80 |
p : array-like, shape (ns,), optional |
| 81 |
Distribution in the source space. |
| 82 |
If let to its default value None, uniform distribution is taken. |
| 83 |
loss_fun : str |
| 84 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 85 |
symmetric : bool, optional |
| 86 |
Either C1 and C2 are to be assumed symmetric or not. |
| 87 |
If let to its default None value, a symmetry test will be conducted. |
| 88 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 89 |
verbose : bool, optional |
| 90 |
Print information along iterations |
| 91 |
log : bool, optional |
| 92 |
record log if True |
| 93 |
G0: array-like of shape (ns,nt) or string, optional |
| 94 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 95 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 96 |
used as initial transport of the solver. |
| 97 |
if G0 is a string it will be interpreted as a method for |
| 98 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 99 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 100 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 101 |
max_iter : int, optional |
| 102 |
Max number of iterations |
| 103 |
tol_rel : float, optional |
| 104 |
Stop threshold on relative error (>0) |
| 105 |
tol_abs : float, optional |
| 106 |
Stop threshold on absolute error (>0) |
| 107 |
random_state: int, optional |
| 108 |
Random seed used in stochastic initialization methods. |
| 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 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 124 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 125 |
International Conference on Learning Representations (ICLR), 2022. |
| 126 |
.. [62] H. Van Assel, C. Vincent-Cuaz, T. Vayer, R. Flamary, N. Courty. |
| 127 |
"Interpolating between Clustering and Dimensionality Reduction with |
| 128 |
Gromov-Wasserstein". NeurIPS 2023 Workshop OTML. |
| 129 |
|
| 130 |
""" |
| 131 |
arr = [C1, C2] |
| 132 |
if p is not None: |
| 133 |
arr.append(list_to_array(p)) |
| 134 |
else: |
| 135 |
p = unif(C1.shape[0], type_as=C1) |
| 136 |
|
| 137 |
if (G0 is not None) and (not isinstance(G0, str)): |
| 138 |
arr.append(G0) |
| 139 |
|
| 140 |
nx = get_backend(*arr) |
| 141 |
|
| 142 |
if symmetric is None: |
| 143 |
symmetric = nx.allclose(C1, C1.T, atol=1e-10) and nx.allclose( |
| 144 |
C2, C2.T, atol=1e-10 |
| 145 |
) |
| 146 |
|
| 147 |
if G0 is None: |
| 148 |
q = unif(C2.shape[0], type_as=p) |
| 149 |
G0 = nx.outer(p, q) |
| 150 |
elif isinstance(G0, str): |
| 151 |
G0 = semirelaxed_init_plan( |
| 152 |
C1, C2, p, method=G0, random_state=random_state, nx=nx |
| 153 |
) |
| 154 |
q = nx.sum(G0, 0) |
| 155 |
else: |
| 156 |
q = nx.sum(G0, 0) |
| 157 |
|
| 158 |
assert nx.allclose(nx.sum(G0, 1), p, atol=1e-08) |
| 159 |
|
| 160 |
constC, hC1, hC2, fC2t = init_matrix_semirelaxed(C1, C2, p, loss_fun, nx) |
| 161 |
|
| 162 |
ones_p = nx.ones(p.shape[0], type_as=p) |
| 163 |
|
| 164 |
def f(G): |
| 165 |
qG = nx.sum(G, 0) |
| 166 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 167 |
return gwloss(constC + marginal_product, hC1, hC2, G, nx) |
| 168 |
|
| 169 |
if symmetric: |
| 170 |
|
| 171 |
def df(G): |
| 172 |
qG = nx.sum(G, 0) |
| 173 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 174 |
return gwggrad(constC + marginal_product, hC1, hC2, G, nx) |
| 175 |
else: |
| 176 |
constCt, hC1t, hC2t, fC2 = init_matrix_semirelaxed(C1.T, C2.T, p, loss_fun, nx) |
| 177 |
|
| 178 |
def df(G): |
| 179 |
qG = nx.sum(G, 0) |
| 180 |
marginal_product_1 = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 181 |
marginal_product_2 = nx.outer(ones_p, nx.dot(qG, fC2)) |
| 182 |
return 0.5 * ( |
| 183 |
gwggrad(constC + marginal_product_1, hC1, hC2, G, nx) |
| 184 |
+ gwggrad(constCt + marginal_product_2, hC1t, hC2t, G, nx) |
| 185 |
) |
| 186 |
|
| 187 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 188 |
return solve_semirelaxed_gromov_linesearch( |
| 189 |
G, |
| 190 |
deltaG, |
| 191 |
cost_G, |
| 192 |
hC1, |
| 193 |
hC2, |
| 194 |
ones_p, |
| 195 |
M=0.0, |
| 196 |
reg=1.0, |
| 197 |
fC2t=fC2t, |
| 198 |
nx=nx, |
| 199 |
**kwargs, |
| 200 |
) |
| 201 |
|
| 202 |
if log: |
| 203 |
res, log = semirelaxed_cg( |
| 204 |
p, |
| 205 |
q, |
| 206 |
0.0, |
| 207 |
1.0, |
| 208 |
f, |
| 209 |
df, |
| 210 |
G0, |
| 211 |
line_search, |
| 212 |
log=True, |
| 213 |
numItermax=max_iter, |
| 214 |
stopThr=tol_rel, |
| 215 |
stopThr2=tol_abs, |
| 216 |
**kwargs, |
| 217 |
) |
| 218 |
log["srgw_dist"] = log["loss"][-1] |
| 219 |
return res, log |
| 220 |
else: |
| 221 |
return semirelaxed_cg( |
| 222 |
p, |
| 223 |
q, |
| 224 |
0.0, |
| 225 |
1.0, |
| 226 |
f, |
| 227 |
df, |
| 228 |
G0, |
| 229 |
line_search, |
| 230 |
log=False, |
| 231 |
numItermax=max_iter, |
| 232 |
stopThr=tol_rel, |
| 233 |
stopThr2=tol_abs, |
| 234 |
**kwargs, |
| 235 |
) |
| 236 |
|
| 237 |
|
| 238 |
def semirelaxed_gromov_wasserstein2( |
| 239 |
C1, |
| 240 |
C2, |
| 241 |
p=None, |
| 242 |
loss_fun="square_loss", |
| 243 |
symmetric=None, |
| 244 |
log=False, |
| 245 |
G0=None, |
| 246 |
max_iter=1e4, |
| 247 |
tol_rel=1e-9, |
| 248 |
tol_abs=1e-9, |
| 249 |
random_state=0, |
| 250 |
**kwargs, |
| 251 |
): |
| 252 |
r""" |
| 253 |
Returns the semi-relaxed Gromov-Wasserstein divergence from :math:`(\mathbf{C_1}, \mathbf{p})` to :math:`\mathbf{C_2}` (see [48]). |
| 254 |
|
| 255 |
The function solves the following optimization problem using Conditional Gradient: |
| 256 |
|
| 257 |
.. math:: |
| 258 |
\text{srGW} = \min_{\mathbf{T}} \quad \sum_{i,j,k,l} |
| 259 |
L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 260 |
|
| 261 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 262 |
|
| 263 |
\mathbf{T} &\geq 0 |
| 264 |
|
| 265 |
Where : |
| 266 |
|
| 267 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 268 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 269 |
- :math:`\mathbf{p}`: distribution in the source space |
| 270 |
- `L`: loss function to account for the misfit between the similarity |
| 271 |
matrices |
| 272 |
|
| 273 |
Note that when using backends, this loss function is differentiable wrt the |
| 274 |
matrices (C1, C2) but not yet for the weights p. |
| 275 |
|
| 276 |
.. note:: This function is backend-compatible and will work on arrays |
| 277 |
from all compatible backends. However all the steps in the conditional |
| 278 |
gradient are not differentiable. |
| 279 |
|
| 280 |
Parameters |
| 281 |
---------- |
| 282 |
C1 : array-like, shape (ns, ns) |
| 283 |
Metric cost matrix in the source space |
| 284 |
C2 : array-like, shape (nt, nt) |
| 285 |
Metric cost matrix in the target space |
| 286 |
p : array-like, shape (ns,), optional |
| 287 |
Distribution in the source space. |
| 288 |
If let to its default value None, uniform distribution is taken. |
| 289 |
loss_fun : str |
| 290 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 291 |
symmetric : bool, optional |
| 292 |
Either C1 and C2 are to be assumed symmetric or not. |
| 293 |
If let to its default None value, a symmetry test will be conducted. |
| 294 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 295 |
verbose : bool, optional |
| 296 |
Print information along iterations |
| 297 |
log : bool, optional |
| 298 |
record log if True |
| 299 |
G0: array-like of shape (ns,nt) or string, optional |
| 300 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 301 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 302 |
used as initial transport of the solver. |
| 303 |
if G0 is a string it will be interpreted as a method for |
| 304 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 305 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 306 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 307 |
max_iter : int, optional |
| 308 |
Max number of iterations |
| 309 |
tol_rel : float, optional |
| 310 |
Stop threshold on relative error (>0) |
| 311 |
tol_abs : float, optional |
| 312 |
Stop threshold on absolute error (>0) |
| 313 |
random_state: int, optional |
| 314 |
Random seed used in stochastic initialization methods. |
| 315 |
**kwargs : dict |
| 316 |
parameters can be directly passed to the ot.optim.cg solver |
| 317 |
|
| 318 |
Returns |
| 319 |
------- |
| 320 |
srgw : float |
| 321 |
Semi-relaxed Gromov-Wasserstein divergence |
| 322 |
log : dict |
| 323 |
convergence information and Coupling matrix |
| 324 |
|
| 325 |
References |
| 326 |
---------- |
| 327 |
|
| 328 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 329 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 330 |
International Conference on Learning Representations (ICLR), 2022. |
| 331 |
|
| 332 |
.. [62] H. Van Assel, C. Vincent-Cuaz, T. Vayer, R. Flamary, N. Courty. |
| 333 |
"Interpolating between Clustering and Dimensionality Reduction with |
| 334 |
Gromov-Wasserstein". NeurIPS 2023 Workshop OTML. |
| 335 |
""" |
| 336 |
|
| 337 |
nx = get_backend(C1, C2) |
| 338 |
|
| 339 |
|
| 340 |
if p is None: |
| 341 |
p = unif(C1.shape[0], type_as=C1) |
| 342 |
|
| 343 |
T, log_srgw = semirelaxed_gromov_wasserstein( |
| 344 |
C1, |
| 345 |
C2, |
| 346 |
p, |
| 347 |
loss_fun, |
| 348 |
symmetric, |
| 349 |
log=True, |
| 350 |
G0=G0, |
| 351 |
max_iter=max_iter, |
| 352 |
tol_rel=tol_rel, |
| 353 |
tol_abs=tol_abs, |
| 354 |
random_state=random_state, |
| 355 |
**kwargs, |
| 356 |
) |
| 357 |
|
| 358 |
q = nx.sum(T, 0) |
| 359 |
log_srgw["T"] = T |
| 360 |
srgw = log_srgw["srgw_dist"] |
| 361 |
|
| 362 |
if loss_fun == "square_loss": |
| 363 |
gC1 = 2 * C1 * nx.outer(p, p) - 2 * nx.dot(T, nx.dot(C2, T.T)) |
| 364 |
gC2 = 2 * C2 * nx.outer(q, q) - 2 * nx.dot(T.T, nx.dot(C1, T)) |
| 365 |
|
| 366 |
elif loss_fun == "kl_loss": |
| 367 |
gC1 = nx.log(C1 + 1e-15) * nx.outer(p, p) - nx.dot( |
| 368 |
T, nx.dot(nx.log(C2 + 1e-15), T.T) |
| 369 |
) |
| 370 |
gC2 = -nx.dot(T.T, nx.dot(C1, T)) / (C2 + 1e-15) + nx.outer(q, q) |
| 371 |
|
| 372 |
srgw = nx.set_gradients(srgw, (C1, C2), (gC1, gC2)) |
| 373 |
|
| 374 |
if log: |
| 375 |
return srgw, log_srgw |
| 376 |
else: |
| 377 |
return srgw |
| 378 |
|
| 379 |
|
| 380 |
def semirelaxed_fused_gromov_wasserstein( |
| 381 |
M, |
| 382 |
C1, |
| 383 |
C2, |
| 384 |
p=None, |
| 385 |
loss_fun="square_loss", |
| 386 |
symmetric=None, |
| 387 |
alpha=0.5, |
| 388 |
G0=None, |
| 389 |
log=False, |
| 390 |
max_iter=1e4, |
| 391 |
tol_rel=1e-9, |
| 392 |
tol_abs=1e-9, |
| 393 |
random_state=0, |
| 394 |
**kwargs, |
| 395 |
): |
| 396 |
r""" |
| 397 |
Computes the semi-relaxed Fused Gromov-Wasserstein transport between two graphs (see [48]). |
| 398 |
|
| 399 |
.. math:: |
| 400 |
\mathbf{T}^* \in \mathop{\arg \min}_{\mathbf{T}} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F + |
| 401 |
\alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) T_{i,j} T_{k,l} |
| 402 |
|
| 403 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 404 |
|
| 405 |
\mathbf{T} &\geq 0 |
| 406 |
|
| 407 |
where : |
| 408 |
|
| 409 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix |
| 410 |
- :math:`\mathbf{p}` source weights (sum to 1) |
| 411 |
- `L` is a loss function to account for the misfit between the similarity matrices |
| 412 |
|
| 413 |
|
| 414 |
.. note:: This function is backend-compatible and will work on arrays |
| 415 |
from all compatible backends. However all the steps in the conditional |
| 416 |
gradient are not differentiable. |
| 417 |
|
| 418 |
The algorithm used for solving the problem is conditional gradient as discussed in :ref:`[48] <references-semirelaxed-fused-gromov-wasserstein>` |
| 419 |
|
| 420 |
Parameters |
| 421 |
---------- |
| 422 |
M : array-like, shape (ns, nt) |
| 423 |
Metric cost matrix between features across domains |
| 424 |
C1 : array-like, shape (ns, ns) |
| 425 |
Metric cost matrix representative of the structure in the source space |
| 426 |
C2 : array-like, shape (nt, nt) |
| 427 |
Metric cost matrix representative of the structure in the target space |
| 428 |
p : array-like, shape (ns,), optional |
| 429 |
Distribution in the source space. |
| 430 |
If let to its default value None, uniform distribution is taken. |
| 431 |
loss_fun : str |
| 432 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 433 |
symmetric : bool, optional |
| 434 |
Either C1 and C2 are to be assumed symmetric or not. |
| 435 |
If let to its default None value, a symmetry test will be conducted. |
| 436 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 437 |
alpha : float, optional |
| 438 |
Trade-off parameter (0 < alpha < 1) |
| 439 |
G0: array-like of shape (ns,nt) or string, optional |
| 440 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 441 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 442 |
used as initial transport of the solver. |
| 443 |
if G0 is a string it will be interpreted as a method for |
| 444 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 445 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 446 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 447 |
log : bool, optional |
| 448 |
record log if True |
| 449 |
max_iter : int, optional |
| 450 |
Max number of iterations |
| 451 |
tol_rel : float, optional |
| 452 |
Stop threshold on relative error (>0) |
| 453 |
tol_abs : float, optional |
| 454 |
Stop threshold on absolute error (>0) |
| 455 |
random_state: int, optional |
| 456 |
Random seed used in stochastic initialization methods. |
| 457 |
**kwargs : dict |
| 458 |
parameters can be directly passed to the ot.optim.cg solver |
| 459 |
|
| 460 |
Returns |
| 461 |
------- |
| 462 |
gamma : array-like, shape (`ns`, `nt`) |
| 463 |
Optimal transportation matrix for the given parameters. |
| 464 |
log : dict |
| 465 |
Log dictionary return only if log==True in parameters. |
| 466 |
|
| 467 |
|
| 468 |
.. _references-semirelaxed-fused-gromov-wasserstein: |
| 469 |
References |
| 470 |
---------- |
| 471 |
.. [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain |
| 472 |
and Courty Nicolas "Optimal Transport for structured data with |
| 473 |
application on graphs", International Conference on Machine Learning |
| 474 |
(ICML). 2019. |
| 475 |
|
| 476 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 477 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 478 |
International Conference on Learning Representations (ICLR), 2022. |
| 479 |
|
| 480 |
.. [62] H. Van Assel, C. Vincent-Cuaz, T. Vayer, R. Flamary, N. Courty. |
| 481 |
"Interpolating between Clustering and Dimensionality Reduction with |
| 482 |
Gromov-Wasserstein". NeurIPS 2023 Workshop OTML. |
| 483 |
""" |
| 484 |
arr = [M, C1, C2] |
| 485 |
if p is not None: |
| 486 |
arr.append(list_to_array(p)) |
| 487 |
else: |
| 488 |
p = unif(C1.shape[0], type_as=C1) |
| 489 |
|
| 490 |
if (G0 is not None) and (not isinstance(G0, str)): |
| 491 |
arr.append(G0) |
| 492 |
|
| 493 |
nx = get_backend(*arr) |
| 494 |
|
| 495 |
if symmetric is None: |
| 496 |
symmetric = nx.allclose(C1, C1.T, atol=1e-10) and nx.allclose( |
| 497 |
C2, C2.T, atol=1e-10 |
| 498 |
) |
| 499 |
|
| 500 |
if G0 is None: |
| 501 |
q = unif(C2.shape[0], type_as=p) |
| 502 |
G0 = nx.outer(p, q) |
| 503 |
elif isinstance(G0, str): |
| 504 |
G0 = semirelaxed_init_plan( |
| 505 |
C1, C2, p, M, alpha, G0, random_state=random_state, nx=nx |
| 506 |
) |
| 507 |
q = nx.sum(G0, 0) |
| 508 |
else: |
| 509 |
q = nx.sum(G0, 0) |
| 510 |
|
| 511 |
assert nx.allclose(nx.sum(G0, 1), p, atol=1e-08) |
| 512 |
|
| 513 |
constC, hC1, hC2, fC2t = init_matrix_semirelaxed(C1, C2, p, loss_fun, nx) |
| 514 |
|
| 515 |
ones_p = nx.ones(p.shape[0], type_as=p) |
| 516 |
|
| 517 |
def f(G): |
| 518 |
qG = nx.sum(G, 0) |
| 519 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 520 |
return gwloss(constC + marginal_product, hC1, hC2, G, nx) |
| 521 |
|
| 522 |
if symmetric: |
| 523 |
|
| 524 |
def df(G): |
| 525 |
qG = nx.sum(G, 0) |
| 526 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 527 |
return gwggrad(constC + marginal_product, hC1, hC2, G, nx) |
| 528 |
else: |
| 529 |
constCt, hC1t, hC2t, fC2 = init_matrix_semirelaxed(C1.T, C2.T, p, loss_fun, nx) |
| 530 |
|
| 531 |
def df(G): |
| 532 |
qG = nx.sum(G, 0) |
| 533 |
marginal_product_1 = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 534 |
marginal_product_2 = nx.outer(ones_p, nx.dot(qG, fC2)) |
| 535 |
return 0.5 * ( |
| 536 |
gwggrad(constC + marginal_product_1, hC1, hC2, G, nx) |
| 537 |
+ gwggrad(constCt + marginal_product_2, hC1t, hC2t, G, nx) |
| 538 |
) |
| 539 |
|
| 540 |
def line_search(cost, G, deltaG, Mi, cost_G, df_G, **kwargs): |
| 541 |
return solve_semirelaxed_gromov_linesearch( |
| 542 |
G, |
| 543 |
deltaG, |
| 544 |
cost_G, |
| 545 |
hC1, |
| 546 |
hC2, |
| 547 |
ones_p, |
| 548 |
M=(1 - alpha) * M, |
| 549 |
reg=alpha, |
| 550 |
fC2t=fC2t, |
| 551 |
nx=nx, |
| 552 |
**kwargs, |
| 553 |
) |
| 554 |
|
| 555 |
if log: |
| 556 |
res, log = semirelaxed_cg( |
| 557 |
p, |
| 558 |
q, |
| 559 |
(1 - alpha) * M, |
| 560 |
alpha, |
| 561 |
f, |
| 562 |
df, |
| 563 |
G0, |
| 564 |
line_search, |
| 565 |
log=True, |
| 566 |
numItermax=max_iter, |
| 567 |
stopThr=tol_rel, |
| 568 |
stopThr2=tol_abs, |
| 569 |
**kwargs, |
| 570 |
) |
| 571 |
log["srfgw_dist"] = log["loss"][-1] |
| 572 |
return res, log |
| 573 |
else: |
| 574 |
return semirelaxed_cg( |
| 575 |
p, |
| 576 |
q, |
| 577 |
(1 - alpha) * M, |
| 578 |
alpha, |
| 579 |
f, |
| 580 |
df, |
| 581 |
G0, |
| 582 |
line_search, |
| 583 |
log=False, |
| 584 |
numItermax=max_iter, |
| 585 |
stopThr=tol_rel, |
| 586 |
stopThr2=tol_abs, |
| 587 |
**kwargs, |
| 588 |
) |
| 589 |
|
| 590 |
|
| 591 |
def semirelaxed_fused_gromov_wasserstein2( |
| 592 |
M, |
| 593 |
C1, |
| 594 |
C2, |
| 595 |
p=None, |
| 596 |
loss_fun="square_loss", |
| 597 |
symmetric=None, |
| 598 |
alpha=0.5, |
| 599 |
G0=None, |
| 600 |
log=False, |
| 601 |
max_iter=1e4, |
| 602 |
tol_rel=1e-9, |
| 603 |
tol_abs=1e-9, |
| 604 |
random_state=0, |
| 605 |
**kwargs, |
| 606 |
): |
| 607 |
r""" |
| 608 |
Computes the semi-relaxed FGW divergence between two graphs (see [48]). |
| 609 |
|
| 610 |
.. math:: |
| 611 |
\mathbf{srFGW}_{\alpha} = \min_{\mathbf{T}} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F + |
| 612 |
\alpha \sum_{i,j,k,l} L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) T_{i,j} T_{k,l} |
| 613 |
|
| 614 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 615 |
|
| 616 |
\mathbf{T} &\geq 0 |
| 617 |
|
| 618 |
where : |
| 619 |
|
| 620 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix |
| 621 |
- :math:`\mathbf{p}` source weights (sum to 1) |
| 622 |
- `L` is a loss function to account for the misfit between the similarity matrices |
| 623 |
|
| 624 |
The algorithm used for solving the problem is conditional gradient as |
| 625 |
discussed in :ref:`[48] <semirelaxed-fused-gromov-wasserstein2>` |
| 626 |
|
| 627 |
Note that when using backends, this loss function is differentiable wrt the |
| 628 |
matrices (C1, C2) but not yet for the weights p. |
| 629 |
|
| 630 |
.. note:: This function is backend-compatible and will work on arrays |
| 631 |
from all compatible backends. However all the steps in the conditional |
| 632 |
gradient are not differentiable. |
| 633 |
|
| 634 |
Parameters |
| 635 |
---------- |
| 636 |
M : array-like, shape (ns, nt) |
| 637 |
Metric cost matrix between features across domains |
| 638 |
C1 : array-like, shape (ns, ns) |
| 639 |
Metric cost matrix representative of the structure in the source space. |
| 640 |
C2 : array-like, shape (nt, nt) |
| 641 |
Metric cost matrix representative of the structure in the target space. |
| 642 |
p : array-like, shape (ns,) |
| 643 |
Distribution in the source space. |
| 644 |
If let to its default value None, uniform distribution is taken. |
| 645 |
loss_fun : str, optional |
| 646 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 647 |
symmetric : bool, optional |
| 648 |
Either C1 and C2 are to be assumed symmetric or not. |
| 649 |
If let to its default None value, a symmetry test will be conducted. |
| 650 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 651 |
alpha : float, optional |
| 652 |
Trade-off parameter (0 < alpha < 1) |
| 653 |
G0: array-like of shape (ns,nt) or string, optional |
| 654 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 655 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 656 |
used as initial transport of the solver. |
| 657 |
if G0 is a string it will be interpreted as a method for |
| 658 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 659 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 660 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 661 |
log : bool, optional |
| 662 |
Record log if True. |
| 663 |
max_iter : int, optional |
| 664 |
Max number of iterations |
| 665 |
tol_rel : float, optional |
| 666 |
Stop threshold on relative error (>0) |
| 667 |
tol_abs : float, optional |
| 668 |
Stop threshold on absolute error (>0) |
| 669 |
random_state: int, optional |
| 670 |
Random seed used in stochastic initialization methods. |
| 671 |
**kwargs : dict |
| 672 |
Parameters can be directly passed to the ot.optim.cg solver. |
| 673 |
|
| 674 |
Returns |
| 675 |
------- |
| 676 |
srfgw-divergence : float |
| 677 |
Semi-relaxed Fused Gromov-Wasserstein divergence for the given parameters. |
| 678 |
log : dict |
| 679 |
Log dictionary return only if log==True in parameters. |
| 680 |
|
| 681 |
|
| 682 |
.. _references-semirelaxed-fused-gromov-wasserstein2: |
| 683 |
References |
| 684 |
---------- |
| 685 |
.. [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain |
| 686 |
and Courty Nicolas "Optimal Transport for structured data with |
| 687 |
application on graphs", International Conference on Machine Learning |
| 688 |
(ICML). 2019. |
| 689 |
|
| 690 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 691 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 692 |
International Conference on Learning Representations (ICLR), 2022. |
| 693 |
|
| 694 |
.. [62] H. Van Assel, C. Vincent-Cuaz, T. Vayer, R. Flamary, N. Courty. |
| 695 |
"Interpolating between Clustering and Dimensionality Reduction with |
| 696 |
Gromov-Wasserstein". NeurIPS 2023 Workshop OTML. |
| 697 |
""" |
| 698 |
|
| 699 |
nx = get_backend(C1, C2) |
| 700 |
|
| 701 |
|
| 702 |
if p is None: |
| 703 |
p = unif(C1.shape[0], type_as=C1) |
| 704 |
|
| 705 |
T, log_fgw = semirelaxed_fused_gromov_wasserstein( |
| 706 |
M, |
| 707 |
C1, |
| 708 |
C2, |
| 709 |
p, |
| 710 |
loss_fun, |
| 711 |
symmetric, |
| 712 |
alpha, |
| 713 |
G0, |
| 714 |
log=True, |
| 715 |
max_iter=max_iter, |
| 716 |
tol_rel=tol_rel, |
| 717 |
tol_abs=tol_abs, |
| 718 |
random_state=random_state, |
| 719 |
**kwargs, |
| 720 |
) |
| 721 |
q = nx.sum(T, 0) |
| 722 |
srfgw_dist = log_fgw["srfgw_dist"] |
| 723 |
log_fgw["T"] = T |
| 724 |
log_fgw["lin_loss"] = nx.sum(M * T) * (1 - alpha) |
| 725 |
log_fgw["quad_loss"] = srfgw_dist - log_fgw["lin_loss"] |
| 726 |
|
| 727 |
if loss_fun == "square_loss": |
| 728 |
gC1 = 2 * C1 * nx.outer(p, p) - 2 * nx.dot(T, nx.dot(C2, T.T)) |
| 729 |
gC2 = 2 * C2 * nx.outer(q, q) - 2 * nx.dot(T.T, nx.dot(C1, T)) |
| 730 |
|
| 731 |
elif loss_fun == "kl_loss": |
| 732 |
gC1 = nx.log(C1 + 1e-15) * nx.outer(p, p) - nx.dot( |
| 733 |
T, nx.dot(nx.log(C2 + 1e-15), T.T) |
| 734 |
) |
| 735 |
gC2 = -nx.dot(T.T, nx.dot(C1, T)) / (C2 + 1e-15) + nx.outer(q, q) |
| 736 |
|
| 737 |
if isinstance(alpha, int) or isinstance(alpha, float): |
| 738 |
srfgw_dist = nx.set_gradients( |
| 739 |
srfgw_dist, (C1, C2, M), (alpha * gC1, alpha * gC2, (1 - alpha) * T) |
| 740 |
) |
| 741 |
else: |
| 742 |
lin_term = nx.sum(T * M) |
| 743 |
srgw_term = (srfgw_dist - (1 - alpha) * lin_term) / alpha |
| 744 |
srfgw_dist = nx.set_gradients( |
| 745 |
srfgw_dist, |
| 746 |
(C1, C2, M, alpha), |
| 747 |
(alpha * gC1, alpha * gC2, (1 - alpha) * T, srgw_term - lin_term), |
| 748 |
) |
| 749 |
|
| 750 |
if log: |
| 751 |
return srfgw_dist, log_fgw |
| 752 |
else: |
| 753 |
return srfgw_dist |
| 754 |
|
| 755 |
|
| 756 |
def solve_semirelaxed_gromov_linesearch( |
| 757 |
G, |
| 758 |
deltaG, |
| 759 |
cost_G, |
| 760 |
C1, |
| 761 |
C2, |
| 762 |
ones_p, |
| 763 |
M, |
| 764 |
reg, |
| 765 |
fC2t=None, |
| 766 |
alpha_min=None, |
| 767 |
alpha_max=None, |
| 768 |
nx=None, |
| 769 |
**kwargs, |
| 770 |
): |
| 771 |
""" |
| 772 |
Solve the linesearch in the Conditional Gradient iterations for the semi-relaxed Gromov-Wasserstein divergence. |
| 773 |
|
| 774 |
Parameters |
| 775 |
---------- |
| 776 |
|
| 777 |
G : array-like, shape(ns,nt) |
| 778 |
The transport map at a given iteration of the FW |
| 779 |
deltaG : array-like (ns,nt) |
| 780 |
Difference between the optimal map found by linearization in the FW algorithm and the value at a given iteration |
| 781 |
cost_G : float |
| 782 |
Value of the cost at `G` |
| 783 |
C1 : array-like (ns,ns), optional |
| 784 |
Transformed Structure matrix in the source domain. |
| 785 |
Note that for the 'square_loss' and 'kl_loss', we provide hC1 from ot.gromov.init_matrix_semirelaxed |
| 786 |
C2 : array-like (nt,nt), optional |
| 787 |
Transformed Structure matrix in the source domain. |
| 788 |
Note that for the 'square_loss' and 'kl_loss', we provide hC2 from ot.gromov.init_matrix_semirelaxed |
| 789 |
ones_p: array-like (ns,1) |
| 790 |
Array of ones of size ns |
| 791 |
M : array-like (ns,nt) |
| 792 |
Cost matrix between the features. |
| 793 |
reg : float |
| 794 |
Regularization parameter. |
| 795 |
fC2t: array-like (nt,nt), optional |
| 796 |
Transformed Structure matrix in the source domain. |
| 797 |
Note that for the 'square_loss' and 'kl_loss', we provide fC2t from ot.gromov.init_matrix_semirelaxed. |
| 798 |
If fC2t is not provided, it is by default fC2t corresponding to the 'square_loss'. |
| 799 |
alpha_min : float, optional |
| 800 |
Minimum value for alpha |
| 801 |
alpha_max : float, optional |
| 802 |
Maximum value for alpha |
| 803 |
nx : backend, optional |
| 804 |
If let to its default value None, a backend test will be conducted. |
| 805 |
Returns |
| 806 |
------- |
| 807 |
alpha : float |
| 808 |
The optimal step size of the FW |
| 809 |
fc : int |
| 810 |
nb of function call. Useless here |
| 811 |
cost_G : float |
| 812 |
The value of the cost for the next iteration |
| 813 |
|
| 814 |
References |
| 815 |
---------- |
| 816 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 817 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 818 |
International Conference on Learning Representations (ICLR), 2021. |
| 819 |
|
| 820 |
.. [62] H. Van Assel, C. Vincent-Cuaz, T. Vayer, R. Flamary, N. Courty. |
| 821 |
"Interpolating between Clustering and Dimensionality Reduction with |
| 822 |
Gromov-Wasserstein". NeurIPS 2023 Workshop OTML. |
| 823 |
""" |
| 824 |
if nx is None: |
| 825 |
if isinstance(M, int) or isinstance(M, float): |
| 826 |
nx = get_backend(G, deltaG, C1, C2) |
| 827 |
else: |
| 828 |
nx = get_backend(G, deltaG, C1, C2, M) |
| 829 |
|
| 830 |
qG, qdeltaG = nx.sum(G, 0), nx.sum(deltaG, 0) |
| 831 |
dot = nx.dot(nx.dot(C1, deltaG), C2.T) |
| 832 |
if fC2t is None: |
| 833 |
fC2t = C2.T**2 |
| 834 |
dot_qG = nx.dot(nx.outer(ones_p, qG), fC2t) |
| 835 |
dot_qdeltaG = nx.dot(nx.outer(ones_p, qdeltaG), fC2t) |
| 836 |
|
| 837 |
a = reg * nx.sum((dot_qdeltaG - dot) * deltaG) |
| 838 |
b = nx.sum(M * deltaG) + reg * ( |
| 839 |
nx.sum((dot_qdeltaG - dot) * G) |
| 840 |
+ nx.sum((dot_qG - nx.dot(nx.dot(C1, G), C2.T)) * deltaG) |
| 841 |
) |
| 842 |
|
| 843 |
alpha = solve_1d_linesearch_quad(a, b) |
| 844 |
if alpha_min is not None or alpha_max is not None: |
| 845 |
alpha = np.clip(alpha, alpha_min, alpha_max) |
| 846 |
|
| 847 |
|
| 848 |
cost_G = cost_G + a * (alpha**2) + b * alpha |
| 849 |
|
| 850 |
return alpha, 1, cost_G |
| 851 |
|
| 852 |
|
| 853 |
def entropic_semirelaxed_gromov_wasserstein( |
| 854 |
C1, |
| 855 |
C2, |
| 856 |
p=None, |
| 857 |
loss_fun="square_loss", |
| 858 |
epsilon=0.1, |
| 859 |
symmetric=None, |
| 860 |
G0=None, |
| 861 |
max_iter=1e4, |
| 862 |
tol=1e-9, |
| 863 |
log=False, |
| 864 |
verbose=False, |
| 865 |
random_state=0, |
| 866 |
): |
| 867 |
r""" |
| 868 |
Returns the entropic-regularized semi-relaxed gromov-wasserstein divergence |
| 869 |
transport plan from :math:`(\mathbf{C_1}, \mathbf{p})` to :math:`\mathbf{C_2}` |
| 870 |
estimated using a Mirror Descent algorithm following the KL geometry. |
| 871 |
|
| 872 |
The function solves the following optimization problem: |
| 873 |
|
| 874 |
.. math:: |
| 875 |
\mathbf{T}^* \in \mathop{\arg \min}_\mathbf{T} \quad \sum_{i,j,k,l} |
| 876 |
L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 877 |
|
| 878 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 879 |
|
| 880 |
\mathbf{T} &\geq 0 |
| 881 |
Where : |
| 882 |
|
| 883 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 884 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 885 |
- :math:`\mathbf{p}`: distribution in the source space |
| 886 |
|
| 887 |
- `L`: loss function to account for the misfit between the similarity matrices |
| 888 |
|
| 889 |
.. note:: This function is backend-compatible and will work on arrays |
| 890 |
from all compatible backends. However all the steps in the conditional |
| 891 |
gradient are not differentiable. |
| 892 |
|
| 893 |
Parameters |
| 894 |
---------- |
| 895 |
C1 : array-like, shape (ns, ns) |
| 896 |
Metric cost matrix in the source space |
| 897 |
C2 : array-like, shape (nt, nt) |
| 898 |
Metric cost matrix in the target space |
| 899 |
p : array-like, shape (ns,), optional |
| 900 |
Distribution in the source space. |
| 901 |
If let to its default value None, uniform distribution is taken. |
| 902 |
loss_fun : str |
| 903 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 904 |
epsilon : float |
| 905 |
Regularization term >0 |
| 906 |
symmetric : bool, optional |
| 907 |
Either C1 and C2 are to be assumed symmetric or not. |
| 908 |
If let to its default None value, a symmetry test will be conducted. |
| 909 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 910 |
verbose : bool, optional |
| 911 |
Print information along iterations |
| 912 |
G0: array-like of shape (ns,nt) or string, optional |
| 913 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 914 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 915 |
used as initial transport of the solver. |
| 916 |
if G0 is a string it will be interpreted as a method for |
| 917 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 918 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 919 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 920 |
max_iter : int, optional |
| 921 |
Max number of iterations |
| 922 |
tol : float, optional |
| 923 |
Stop threshold on error computed on transport plans |
| 924 |
log : bool, optional |
| 925 |
record log if True |
| 926 |
verbose : bool, optional |
| 927 |
Print information along iterations |
| 928 |
random_state: int, optional |
| 929 |
Random seed used in stochastic initialization methods. |
| 930 |
|
| 931 |
Returns |
| 932 |
------- |
| 933 |
G : array-like, shape (`ns`, `nt`) |
| 934 |
Coupling between the two spaces that minimizes: |
| 935 |
|
| 936 |
: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}` |
| 937 |
log : dict |
| 938 |
Convergence information and loss. |
| 939 |
|
| 940 |
References |
| 941 |
---------- |
| 942 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 943 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 944 |
International Conference on Learning Representations (ICLR), 2022. |
| 945 |
""" |
| 946 |
arr = [C1, C2] |
| 947 |
if p is not None: |
| 948 |
arr.append(list_to_array(p)) |
| 949 |
else: |
| 950 |
p = unif(C1.shape[0], type_as=C1) |
| 951 |
|
| 952 |
if (G0 is not None) and (not isinstance(G0, str)): |
| 953 |
arr.append(G0) |
| 954 |
|
| 955 |
nx = get_backend(*arr) |
| 956 |
|
| 957 |
if symmetric is None: |
| 958 |
symmetric = nx.allclose(C1, C1.T, atol=1e-10) and nx.allclose( |
| 959 |
C2, C2.T, atol=1e-10 |
| 960 |
) |
| 961 |
|
| 962 |
if G0 is None: |
| 963 |
q = unif(C2.shape[0], type_as=p) |
| 964 |
G0 = nx.outer(p, q) |
| 965 |
elif isinstance(G0, str): |
| 966 |
G0 = semirelaxed_init_plan( |
| 967 |
C1, C2, p, method=G0, random_state=random_state, nx=nx |
| 968 |
) |
| 969 |
q = nx.sum(G0, 0) |
| 970 |
else: |
| 971 |
q = nx.sum(G0, 0) |
| 972 |
|
| 973 |
assert nx.allclose(nx.sum(G0, 1), p, atol=1e-08) |
| 974 |
|
| 975 |
constC, hC1, hC2, fC2t = init_matrix_semirelaxed(C1, C2, p, loss_fun, nx) |
| 976 |
|
| 977 |
ones_p = nx.ones(p.shape[0], type_as=p) |
| 978 |
|
| 979 |
if symmetric: |
| 980 |
|
| 981 |
def df(G): |
| 982 |
qG = nx.sum(G, 0) |
| 983 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 984 |
return gwggrad(constC + marginal_product, hC1, hC2, G, nx) |
| 985 |
else: |
| 986 |
constCt, hC1t, hC2t, fC2 = init_matrix_semirelaxed(C1.T, C2.T, p, loss_fun, nx) |
| 987 |
|
| 988 |
def df(G): |
| 989 |
qG = nx.sum(G, 0) |
| 990 |
marginal_product_1 = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 991 |
marginal_product_2 = nx.outer(ones_p, nx.dot(qG, fC2)) |
| 992 |
return 0.5 * ( |
| 993 |
gwggrad(constC + marginal_product_1, hC1, hC2, G, nx) |
| 994 |
+ gwggrad(constCt + marginal_product_2, hC1t, hC2t, G, nx) |
| 995 |
) |
| 996 |
|
| 997 |
cpt = 0 |
| 998 |
err = 1e15 |
| 999 |
G = G0 |
| 1000 |
|
| 1001 |
if log: |
| 1002 |
log = {"err": []} |
| 1003 |
|
| 1004 |
while err > tol and cpt < max_iter: |
| 1005 |
Gprev = G |
| 1006 |
|
| 1007 |
K = G * nx.exp(-df(G) / epsilon) |
| 1008 |
scaling = p / nx.sum(K, 1) |
| 1009 |
G = nx.reshape(scaling, (-1, 1)) * K |
| 1010 |
if cpt % 10 == 0: |
| 1011 |
|
| 1012 |
|
| 1013 |
err = nx.norm(G - Gprev) |
| 1014 |
|
| 1015 |
if log: |
| 1016 |
log["err"].append(err) |
| 1017 |
|
| 1018 |
if verbose: |
| 1019 |
if cpt % 200 == 0: |
| 1020 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1021 |
print("{:5d}|{:8e}|".format(cpt, err)) |
| 1022 |
|
| 1023 |
cpt += 1 |
| 1024 |
|
| 1025 |
if log: |
| 1026 |
qG = nx.sum(G, 0) |
| 1027 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 1028 |
log["srgw_dist"] = gwloss(constC + marginal_product, hC1, hC2, G, nx) |
| 1029 |
return G, log |
| 1030 |
else: |
| 1031 |
return G |
| 1032 |
|
| 1033 |
|
| 1034 |
def entropic_semirelaxed_gromov_wasserstein2( |
| 1035 |
C1, |
| 1036 |
C2, |
| 1037 |
p=None, |
| 1038 |
loss_fun="square_loss", |
| 1039 |
epsilon=0.1, |
| 1040 |
symmetric=None, |
| 1041 |
G0=None, |
| 1042 |
max_iter=1e4, |
| 1043 |
tol=1e-9, |
| 1044 |
log=False, |
| 1045 |
verbose=False, |
| 1046 |
random_state=0, |
| 1047 |
**kwargs, |
| 1048 |
): |
| 1049 |
r""" |
| 1050 |
Returns the entropic-regularized semi-relaxed gromov-wasserstein divergence |
| 1051 |
from :math:`(\mathbf{C_1}, \mathbf{p})` to :math:`\mathbf{C_2}` |
| 1052 |
estimated using a Mirror Descent algorithm following the KL geometry. |
| 1053 |
|
| 1054 |
The function solves the following optimization problem: |
| 1055 |
|
| 1056 |
.. math:: |
| 1057 |
\mathbf{srGW} = \min_{\mathbf{T}} \quad \sum_{i,j,k,l} |
| 1058 |
L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l} |
| 1059 |
|
| 1060 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 1061 |
|
| 1062 |
\mathbf{T} &\geq 0 |
| 1063 |
Where : |
| 1064 |
|
| 1065 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 1066 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 1067 |
- :math:`\mathbf{p}`: distribution in the source space |
| 1068 |
- `L`: loss function to account for the misfit between the similarity |
| 1069 |
matrices |
| 1070 |
|
| 1071 |
Note that when using backends, this loss function is differentiable wrt the |
| 1072 |
matrices (C1, C2) but not yet for the weights p. |
| 1073 |
.. note:: This function is backend-compatible and will work on arrays |
| 1074 |
from all compatible backends. However all the steps in the conditional |
| 1075 |
gradient are not differentiable. |
| 1076 |
|
| 1077 |
Parameters |
| 1078 |
---------- |
| 1079 |
C1 : array-like, shape (ns, ns) |
| 1080 |
Metric cost matrix in the source space |
| 1081 |
C2 : array-like, shape (nt, nt) |
| 1082 |
Metric cost matrix in the target space |
| 1083 |
p : array-like, shape (ns,), optional |
| 1084 |
Distribution in the source space. |
| 1085 |
If let to its default value None, uniform distribution is taken. |
| 1086 |
loss_fun : str |
| 1087 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 1088 |
epsilon : float |
| 1089 |
Regularization term >0 |
| 1090 |
symmetric : bool, optional |
| 1091 |
Either C1 and C2 are to be assumed symmetric or not. |
| 1092 |
If let to its default None value, a symmetry test will be conducted. |
| 1093 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 1094 |
verbose : bool, optional |
| 1095 |
Print information along iterations |
| 1096 |
G0: array-like of shape (ns,nt) or string, optional |
| 1097 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 1098 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 1099 |
used as initial transport of the solver. |
| 1100 |
if G0 is a string it will be interpreted as a method for |
| 1101 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 1102 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 1103 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 1104 |
max_iter : int, optional |
| 1105 |
Max number of iterations |
| 1106 |
tol : float, optional |
| 1107 |
Stop threshold on error computed on transport plans |
| 1108 |
log : bool, optional |
| 1109 |
record log if True |
| 1110 |
verbose : bool, optional |
| 1111 |
Print information along iterations |
| 1112 |
random_state: int, optional |
| 1113 |
Random seed used in stochastic initialization methods. |
| 1114 |
|
| 1115 |
Returns |
| 1116 |
------- |
| 1117 |
srgw : float |
| 1118 |
Semi-relaxed Gromov-Wasserstein divergence |
| 1119 |
log : dict |
| 1120 |
convergence information and Coupling matrix |
| 1121 |
|
| 1122 |
References |
| 1123 |
---------- |
| 1124 |
|
| 1125 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 1126 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 1127 |
International Conference on Learning Representations (ICLR), 2022. |
| 1128 |
""" |
| 1129 |
T, log_srgw = entropic_semirelaxed_gromov_wasserstein( |
| 1130 |
C1, |
| 1131 |
C2, |
| 1132 |
p, |
| 1133 |
loss_fun, |
| 1134 |
epsilon, |
| 1135 |
symmetric, |
| 1136 |
G0, |
| 1137 |
max_iter, |
| 1138 |
tol, |
| 1139 |
log=True, |
| 1140 |
verbose=verbose, |
| 1141 |
random_state=random_state, |
| 1142 |
) |
| 1143 |
|
| 1144 |
log_srgw["T"] = T |
| 1145 |
|
| 1146 |
if log: |
| 1147 |
return log_srgw["srgw_dist"], log_srgw |
| 1148 |
else: |
| 1149 |
return log_srgw["srgw_dist"] |
| 1150 |
|
| 1151 |
|
| 1152 |
def entropic_semirelaxed_fused_gromov_wasserstein( |
| 1153 |
M, |
| 1154 |
C1, |
| 1155 |
C2, |
| 1156 |
p=None, |
| 1157 |
loss_fun="square_loss", |
| 1158 |
symmetric=None, |
| 1159 |
epsilon=0.1, |
| 1160 |
alpha=0.5, |
| 1161 |
G0=None, |
| 1162 |
max_iter=1e4, |
| 1163 |
tol=1e-9, |
| 1164 |
log=False, |
| 1165 |
verbose=False, |
| 1166 |
random_state=0, |
| 1167 |
): |
| 1168 |
r""" |
| 1169 |
Computes the entropic-regularized semi-relaxed FGW transport between two graphs (see :ref:`[48] <references-semirelaxed-fused-gromov-wasserstein>`) |
| 1170 |
estimated using a Mirror Descent algorithm following the KL geometry. |
| 1171 |
|
| 1172 |
.. math:: |
| 1173 |
\mathbf{T}^* \in \mathop{\arg \min}_{\mathbf{T}} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F + |
| 1174 |
\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} |
| 1175 |
|
| 1176 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 1177 |
|
| 1178 |
\mathbf{T} &\geq 0 |
| 1179 |
|
| 1180 |
where : |
| 1181 |
|
| 1182 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix between features |
| 1183 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 1184 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 1185 |
- :math:`\mathbf{p}` source weights (sum to 1) |
| 1186 |
- `L` is a loss function to account for the misfit between the similarity matrices |
| 1187 |
|
| 1188 |
|
| 1189 |
.. note:: This function is backend-compatible and will work on arrays |
| 1190 |
from all compatible backends. However all the steps in the conditional |
| 1191 |
gradient are not differentiable. |
| 1192 |
|
| 1193 |
The algorithm used for solving the problem is conditional gradient as discussed in :ref:`[48] <references-semirelaxed-fused-gromov-wasserstein>` |
| 1194 |
|
| 1195 |
Parameters |
| 1196 |
---------- |
| 1197 |
M : array-like, shape (ns, nt) |
| 1198 |
Metric cost matrix between features across domains |
| 1199 |
C1 : array-like, shape (ns, ns) |
| 1200 |
Metric cost matrix representative of the structure in the source space |
| 1201 |
C2 : array-like, shape (nt, nt) |
| 1202 |
Metric cost matrix representative of the structure in the target space |
| 1203 |
p : array-like, shape (ns,), optional |
| 1204 |
Distribution in the source space. |
| 1205 |
If let to its default value None, uniform distribution is taken. |
| 1206 |
loss_fun : str |
| 1207 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 1208 |
epsilon : float |
| 1209 |
Regularization term >0 |
| 1210 |
symmetric : bool, optional |
| 1211 |
Either C1 and C2 are to be assumed symmetric or not. |
| 1212 |
If let to its default None value, a symmetry test will be conducted. |
| 1213 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 1214 |
alpha : float, optional |
| 1215 |
Trade-off parameter (0 < alpha < 1) |
| 1216 |
G0: array-like of shape (ns,nt) or string, optional |
| 1217 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 1218 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 1219 |
used as initial transport of the solver. |
| 1220 |
if G0 is a string it will be interpreted as a method for |
| 1221 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 1222 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 1223 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 1224 |
max_iter : int, optional |
| 1225 |
Max number of iterations |
| 1226 |
tol : float, optional |
| 1227 |
Stop threshold on error computed on transport plans |
| 1228 |
log : bool, optional |
| 1229 |
record log if True |
| 1230 |
verbose : bool, optional |
| 1231 |
Print information along iterations |
| 1232 |
random_state: int, optional |
| 1233 |
Random seed used in stochastic initialization methods. |
| 1234 |
|
| 1235 |
Returns |
| 1236 |
------- |
| 1237 |
G : array-like, shape (`ns`, `nt`) |
| 1238 |
Optimal transportation matrix for the given parameters. |
| 1239 |
log : dict |
| 1240 |
Log dictionary return only if log==True in parameters. |
| 1241 |
|
| 1242 |
|
| 1243 |
.. _references-semirelaxed-fused-gromov-wasserstein: |
| 1244 |
References |
| 1245 |
---------- |
| 1246 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 1247 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 1248 |
International Conference on Learning Representations (ICLR), 2022. |
| 1249 |
""" |
| 1250 |
arr = [M, C1, C2] |
| 1251 |
if p is not None: |
| 1252 |
arr.append(list_to_array(p)) |
| 1253 |
else: |
| 1254 |
p = unif(C1.shape[0], type_as=C1) |
| 1255 |
|
| 1256 |
if (G0 is not None) and (not isinstance(G0, str)): |
| 1257 |
arr.append(G0) |
| 1258 |
|
| 1259 |
nx = get_backend(*arr) |
| 1260 |
|
| 1261 |
if symmetric is None: |
| 1262 |
symmetric = nx.allclose(C1, C1.T, atol=1e-10) and nx.allclose( |
| 1263 |
C2, C2.T, atol=1e-10 |
| 1264 |
) |
| 1265 |
|
| 1266 |
if G0 is None: |
| 1267 |
q = unif(C2.shape[0], type_as=p) |
| 1268 |
G0 = nx.outer(p, q) |
| 1269 |
elif isinstance(G0, str): |
| 1270 |
G0 = semirelaxed_init_plan( |
| 1271 |
C1, C2, p, M, alpha, G0, random_state=random_state, nx=nx |
| 1272 |
) |
| 1273 |
q = nx.sum(G0, 0) |
| 1274 |
else: |
| 1275 |
q = nx.sum(G0, 0) |
| 1276 |
|
| 1277 |
assert nx.allclose(nx.sum(G0, 1), p, atol=1e-08) |
| 1278 |
|
| 1279 |
constC, hC1, hC2, fC2t = init_matrix_semirelaxed(C1, C2, p, loss_fun, nx) |
| 1280 |
|
| 1281 |
ones_p = nx.ones(p.shape[0], type_as=p) |
| 1282 |
dM = (1 - alpha) * M |
| 1283 |
if symmetric: |
| 1284 |
|
| 1285 |
def df(G): |
| 1286 |
qG = nx.sum(G, 0) |
| 1287 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 1288 |
return alpha * gwggrad(constC + marginal_product, hC1, hC2, G, nx) + dM |
| 1289 |
else: |
| 1290 |
constCt, hC1t, hC2t, fC2 = init_matrix_semirelaxed(C1.T, C2.T, p, loss_fun, nx) |
| 1291 |
|
| 1292 |
def df(G): |
| 1293 |
qG = nx.sum(G, 0) |
| 1294 |
marginal_product_1 = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 1295 |
marginal_product_2 = nx.outer(ones_p, nx.dot(qG, fC2)) |
| 1296 |
return ( |
| 1297 |
0.5 |
| 1298 |
* alpha |
| 1299 |
* ( |
| 1300 |
gwggrad(constC + marginal_product_1, hC1, hC2, G, nx) |
| 1301 |
+ gwggrad(constCt + marginal_product_2, hC1t, hC2t, G, nx) |
| 1302 |
) |
| 1303 |
+ dM |
| 1304 |
) |
| 1305 |
|
| 1306 |
cpt = 0 |
| 1307 |
err = 1e15 |
| 1308 |
G = G0 |
| 1309 |
|
| 1310 |
if log: |
| 1311 |
log = {"err": []} |
| 1312 |
|
| 1313 |
while err > tol and cpt < max_iter: |
| 1314 |
Gprev = G |
| 1315 |
|
| 1316 |
K = G * nx.exp(-df(G) / epsilon) |
| 1317 |
scaling = p / nx.sum(K, 1) |
| 1318 |
G = nx.reshape(scaling, (-1, 1)) * K |
| 1319 |
if cpt % 10 == 0: |
| 1320 |
|
| 1321 |
|
| 1322 |
err = nx.norm(G - Gprev) |
| 1323 |
|
| 1324 |
if log: |
| 1325 |
log["err"].append(err) |
| 1326 |
|
| 1327 |
if verbose: |
| 1328 |
if cpt % 200 == 0: |
| 1329 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1330 |
print("{:5d}|{:8e}|".format(cpt, err)) |
| 1331 |
|
| 1332 |
cpt += 1 |
| 1333 |
|
| 1334 |
if log: |
| 1335 |
qG = nx.sum(G, 0) |
| 1336 |
marginal_product = nx.outer(ones_p, nx.dot(qG, fC2t)) |
| 1337 |
log["lin_loss"] = nx.sum(M * G) * (1 - alpha) |
| 1338 |
log["quad_loss"] = alpha * gwloss(constC + marginal_product, hC1, hC2, G, nx) |
| 1339 |
log["srfgw_dist"] = log["lin_loss"] + log["quad_loss"] |
| 1340 |
return G, log |
| 1341 |
else: |
| 1342 |
return G |
| 1343 |
|
| 1344 |
|
| 1345 |
def entropic_semirelaxed_fused_gromov_wasserstein2( |
| 1346 |
M, |
| 1347 |
C1, |
| 1348 |
C2, |
| 1349 |
p=None, |
| 1350 |
loss_fun="square_loss", |
| 1351 |
symmetric=None, |
| 1352 |
epsilon=0.1, |
| 1353 |
alpha=0.5, |
| 1354 |
G0=None, |
| 1355 |
max_iter=1e4, |
| 1356 |
tol=1e-9, |
| 1357 |
log=False, |
| 1358 |
verbose=False, |
| 1359 |
random_state=0, |
| 1360 |
): |
| 1361 |
r""" |
| 1362 |
Computes the entropic-regularized semi-relaxed FGW divergence between two graphs (see :ref:`[48] <references-semirelaxed-fused-gromov-wasserstein>`) |
| 1363 |
estimated using a Mirror Descent algorithm following the KL geometry. |
| 1364 |
|
| 1365 |
.. math:: |
| 1366 |
\mathbf{srFGW}_{\alpha} = \min_{\mathbf{T}} \quad (1 - \alpha) \langle \mathbf{T}, \mathbf{M} \rangle_F + |
| 1367 |
\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} |
| 1368 |
|
| 1369 |
s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p} |
| 1370 |
|
| 1371 |
\mathbf{T} &\geq 0 |
| 1372 |
|
| 1373 |
where : |
| 1374 |
|
| 1375 |
- :math:`\mathbf{M}` is the (`ns`, `nt`) metric cost matrix between features |
| 1376 |
- :math:`\mathbf{C_1}`: Metric cost matrix in the source space |
| 1377 |
- :math:`\mathbf{C_2}`: Metric cost matrix in the target space |
| 1378 |
- :math:`\mathbf{p}` source weights (sum to 1) |
| 1379 |
- `L` is a loss function to account for the misfit between the similarity matrices |
| 1380 |
|
| 1381 |
|
| 1382 |
.. note:: This function is backend-compatible and will work on arrays |
| 1383 |
from all compatible backends. However all the steps in the conditional |
| 1384 |
gradient are not differentiable. |
| 1385 |
|
| 1386 |
The algorithm used for solving the problem is conditional gradient as discussed in :ref:`[48] <references-semirelaxed-fused-gromov-wasserstein>` |
| 1387 |
|
| 1388 |
Parameters |
| 1389 |
---------- |
| 1390 |
M : array-like, shape (ns, nt) |
| 1391 |
Metric cost matrix between features across domains |
| 1392 |
C1 : array-like, shape (ns, ns) |
| 1393 |
Metric cost matrix representative of the structure in the source space. |
| 1394 |
C2 : array-like, shape (nt, nt) |
| 1395 |
Metric cost matrix representative of the structure in the target space. |
| 1396 |
p : array-like, shape (ns,), optional |
| 1397 |
Distribution in the source space. |
| 1398 |
If let to its default value None, uniform distribution is taken. |
| 1399 |
loss_fun : str, optional |
| 1400 |
loss function used for the solver either 'square_loss' or 'kl_loss'. |
| 1401 |
epsilon : float |
| 1402 |
Regularization term >0 |
| 1403 |
symmetric : bool, optional |
| 1404 |
Either C1 and C2 are to be assumed symmetric or not. |
| 1405 |
If let to its default None value, a symmetry test will be conducted. |
| 1406 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 1407 |
alpha : float, optional |
| 1408 |
Trade-off parameter (0 < alpha < 1) |
| 1409 |
G0: array-like of shape (ns,nt) or string, optional |
| 1410 |
If `G0=None` the initial transport plan of the solver is :math:`\mathbf{p} \frac{\mathbf{1}_{nt}}{nt}^\top`. |
| 1411 |
If G0 is a tensor it must satisfy marginal constraints and will be |
| 1412 |
used as initial transport of the solver. |
| 1413 |
if G0 is a string it will be interpreted as a method for |
| 1414 |
:func:`ot.gromov.semirelaxed_init_plan` taking values in "product", |
| 1415 |
"random_product", "random", "fluid", "fluid_soft", "spectral", |
| 1416 |
"spectral_soft", "kmeans", "kmeans_soft". |
| 1417 |
max_iter : int, optional |
| 1418 |
Max number of iterations |
| 1419 |
tol : float, optional |
| 1420 |
Stop threshold on error computed on transport plans |
| 1421 |
log : bool, optional |
| 1422 |
record log if True |
| 1423 |
verbose : bool, optional |
| 1424 |
Print information along iterations |
| 1425 |
random_state: int, optional |
| 1426 |
Random seed used in stochastic initialization methods. |
| 1427 |
|
| 1428 |
Returns |
| 1429 |
------- |
| 1430 |
srfgw-divergence : float |
| 1431 |
Semi-relaxed Fused gromov wasserstein divergence for the given parameters. |
| 1432 |
log : dict |
| 1433 |
Log dictionary return only if log==True in parameters. |
| 1434 |
|
| 1435 |
|
| 1436 |
.. _references-semirelaxed-fused-gromov-wasserstein2: |
| 1437 |
References |
| 1438 |
---------- |
| 1439 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 1440 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 1441 |
International Conference on Learning Representations (ICLR), 2022. |
| 1442 |
""" |
| 1443 |
T, log_srfgw = entropic_semirelaxed_fused_gromov_wasserstein( |
| 1444 |
M, |
| 1445 |
C1, |
| 1446 |
C2, |
| 1447 |
p, |
| 1448 |
loss_fun, |
| 1449 |
symmetric, |
| 1450 |
epsilon, |
| 1451 |
alpha, |
| 1452 |
G0, |
| 1453 |
max_iter, |
| 1454 |
tol, |
| 1455 |
log=True, |
| 1456 |
verbose=verbose, |
| 1457 |
random_state=random_state, |
| 1458 |
) |
| 1459 |
|
| 1460 |
log_srfgw["T"] = T |
| 1461 |
|
| 1462 |
if log: |
| 1463 |
return log_srfgw["srfgw_dist"], log_srfgw |
| 1464 |
else: |
| 1465 |
return log_srfgw["srfgw_dist"] |
| 1466 |
|
| 1467 |
|
| 1468 |
def semirelaxed_gromov_barycenters( |
| 1469 |
N, |
| 1470 |
Cs, |
| 1471 |
ps=None, |
| 1472 |
lambdas=None, |
| 1473 |
loss_fun="square_loss", |
| 1474 |
symmetric=True, |
| 1475 |
max_iter=1000, |
| 1476 |
tol=1e-9, |
| 1477 |
stop_criterion="barycenter", |
| 1478 |
warmstartT=False, |
| 1479 |
verbose=False, |
| 1480 |
log=False, |
| 1481 |
init_C=None, |
| 1482 |
G0="product", |
| 1483 |
random_state=None, |
| 1484 |
**kwargs, |
| 1485 |
): |
| 1486 |
r""" |
| 1487 |
Returns the Semi-relaxed Gromov-Wasserstein barycenters of `S` measured similarity matrices |
| 1488 |
:math:`(\mathbf{C}_s)_{1 \leq s \leq S}` |
| 1489 |
|
| 1490 |
The function solves the following optimization problem with block coordinate descent: |
| 1491 |
|
| 1492 |
.. math:: |
| 1493 |
|
| 1494 |
\mathbf{C}^* = \mathop{\arg \min}_{\mathbf{C}\in \mathbb{R}^{N \times N}} \quad \sum_s \lambda_s \mathrm{srGW}(\mathbf{C}_s, \mathbf{p}_s, \mathbf{C}) |
| 1495 |
|
| 1496 |
Where : |
| 1497 |
|
| 1498 |
- :math:`\mathbf{C}_s`: input metric cost matrix |
| 1499 |
- :math:`\mathbf{p}_s`: distribution |
| 1500 |
|
| 1501 |
Parameters |
| 1502 |
---------- |
| 1503 |
N : int |
| 1504 |
Size of the targeted barycenter |
| 1505 |
Cs : list of S array-like of shape (ns, ns) |
| 1506 |
Metric cost matrices |
| 1507 |
ps : list of S array-like of shape (ns,), optional |
| 1508 |
Sample weights in the `S` spaces. |
| 1509 |
If let to its default value None, uniform distributions are taken. |
| 1510 |
lambdas : array-like of shape (S,) , optional |
| 1511 |
List of the `S` spaces' weights. |
| 1512 |
If let to its default value None, uniform weights are taken. |
| 1513 |
loss_fun : callable, optional |
| 1514 |
tensor-matrix multiplication function based on specific loss function |
| 1515 |
symmetric : bool, optional. |
| 1516 |
Either structures are to be assumed symmetric or not. Default value is True. |
| 1517 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 1518 |
max_iter : int, optional |
| 1519 |
Max number of iterations |
| 1520 |
tol : float, optional |
| 1521 |
Stop threshold on relative error (>0) |
| 1522 |
stop_criterion : str, optional. Default is 'barycenter'. |
| 1523 |
Stop criterion taking values in ['barycenter', 'loss']. If set to 'barycenter' |
| 1524 |
uses absolute norm variations of estimated barycenters. Else if set to 'loss' |
| 1525 |
uses the relative variations of the loss. |
| 1526 |
warmstartT: bool, optional |
| 1527 |
Either to perform warmstart of transport plans in the successive |
| 1528 |
fused gromov-wasserstein transport problems.s |
| 1529 |
verbose : bool, optional |
| 1530 |
Print information along iterations. |
| 1531 |
log : bool, optional |
| 1532 |
Record log if True. |
| 1533 |
init_C : array-like of shape (N,N), optional. |
| 1534 |
Random initial value for the :math:`\mathbf{C}` matrix provided by user. |
| 1535 |
Default is None and relies `G0` to produce an initial structure. |
| 1536 |
G0: str, optional. Default is 'product'. |
| 1537 |
Initialization method for transport plans calling :func:`ot.gromov.semirelaxed_init_plan`, |
| 1538 |
and taking values in "product", "random_product", "random", "fluid", |
| 1539 |
"fluid_soft", "spectral", "spectral_soft", "kmeans", "kmeans_soft". |
| 1540 |
Transport plans are used to deduce an initial barycenter structure |
| 1541 |
if `init_C=None`. |
| 1542 |
random_state : int or RandomState instance, optional |
| 1543 |
Fix the seed for reproducibility |
| 1544 |
|
| 1545 |
Returns |
| 1546 |
------- |
| 1547 |
C : array-like, shape (`N`, `N`) |
| 1548 |
Barycenters' structure matrix |
| 1549 |
log : dict |
| 1550 |
Only returned when log=True. It contains the keys: |
| 1551 |
|
| 1552 |
- :math:`\mathbf{T}`: list of (`N`, `ns`) transport matrices |
| 1553 |
- :math:`\mathbf{p}`: (`N`,) barycenter weights |
| 1554 |
- values used in convergence evaluation. |
| 1555 |
|
| 1556 |
References |
| 1557 |
---------- |
| 1558 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 1559 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 1560 |
International Conference on Learning Representations (ICLR), 2022. |
| 1561 |
|
| 1562 |
""" |
| 1563 |
if stop_criterion not in ["barycenter", "loss"]: |
| 1564 |
raise ValueError( |
| 1565 |
f"Unknown `stop_criterion='{stop_criterion}'`. Use one of: {'barycenter', 'loss'}." |
| 1566 |
) |
| 1567 |
|
| 1568 |
arr = [*Cs] |
| 1569 |
if ps is not None: |
| 1570 |
arr += [*ps] |
| 1571 |
else: |
| 1572 |
ps = [unif(C.shape[0], type_as=C) for C in Cs] |
| 1573 |
|
| 1574 |
nx = get_backend(*arr) |
| 1575 |
|
| 1576 |
S = len(Cs) |
| 1577 |
if lambdas is None: |
| 1578 |
lambdas = nx.ones(S) / S |
| 1579 |
else: |
| 1580 |
lambdas = list_to_array(lambdas) |
| 1581 |
lambdas = nx.from_numpy(lambdas) |
| 1582 |
|
| 1583 |
|
| 1584 |
if init_C is None: |
| 1585 |
init_C = nx.zeros((N, N), type_as=Cs[0]) |
| 1586 |
if G0 in ["product", "random_product", "random"]: |
| 1587 |
T = [ |
| 1588 |
semirelaxed_init_plan( |
| 1589 |
Cs[i], |
| 1590 |
init_C, |
| 1591 |
ps[i], |
| 1592 |
method=G0, |
| 1593 |
use_target=False, |
| 1594 |
random_state=random_state, |
| 1595 |
nx=nx, |
| 1596 |
) |
| 1597 |
for i in range(S) |
| 1598 |
] |
| 1599 |
C = update_barycenter_structure(T, Cs, lambdas, loss_fun=loss_fun, nx=nx) |
| 1600 |
|
| 1601 |
if G0 in ["product", "random_product"]: |
| 1602 |
|
| 1603 |
|
| 1604 |
np.random.seed(random_state) |
| 1605 |
noise = np.random.uniform(-0.01, 0.01, size=(N, N)) |
| 1606 |
if symmetric: |
| 1607 |
noise = (noise + noise.T) / 2.0 |
| 1608 |
noise = nx.from_numpy(noise) |
| 1609 |
C = C + noise |
| 1610 |
|
| 1611 |
else: |
| 1612 |
shapes = np.array([C.shape[0] for C in Cs]) |
| 1613 |
large_graphs_idx = np.where(shapes > N)[0] |
| 1614 |
small_graphs_idx = np.where(shapes <= N)[0] |
| 1615 |
T = [None] * S |
| 1616 |
list_init_C = [] |
| 1617 |
|
| 1618 |
|
| 1619 |
|
| 1620 |
|
| 1621 |
for indices in [large_graphs_idx, small_graphs_idx]: |
| 1622 |
if len(indices) > 0: |
| 1623 |
sub_T = [ |
| 1624 |
semirelaxed_init_plan( |
| 1625 |
Cs[i], |
| 1626 |
init_C, |
| 1627 |
ps[i], |
| 1628 |
method=G0, |
| 1629 |
use_target=False, |
| 1630 |
random_state=random_state, |
| 1631 |
nx=nx, |
| 1632 |
) |
| 1633 |
for i in indices |
| 1634 |
] |
| 1635 |
sub_Cs = [Cs[i] for i in indices] |
| 1636 |
sub_lambdas = lambdas[indices] / nx.sum(lambdas[indices]) |
| 1637 |
init_C = update_barycenter_structure( |
| 1638 |
sub_T, sub_Cs, sub_lambdas, loss_fun=loss_fun, nx=nx |
| 1639 |
) |
| 1640 |
for i, idx in enumerate(indices): |
| 1641 |
T[idx] = sub_T[i] |
| 1642 |
list_init_C.append(init_C) |
| 1643 |
|
| 1644 |
if len(list_init_C) == 2: |
| 1645 |
init_C = update_barycenter_structure( |
| 1646 |
T, Cs, lambdas, loss_fun=loss_fun, nx=nx |
| 1647 |
) |
| 1648 |
C = init_C |
| 1649 |
|
| 1650 |
else: |
| 1651 |
C = init_C |
| 1652 |
T = [ |
| 1653 |
semirelaxed_init_plan( |
| 1654 |
Cs[i], |
| 1655 |
C, |
| 1656 |
ps[i], |
| 1657 |
method=G0, |
| 1658 |
use_target=True, |
| 1659 |
random_state=random_state, |
| 1660 |
nx=nx, |
| 1661 |
) |
| 1662 |
for i in range(S) |
| 1663 |
] |
| 1664 |
|
| 1665 |
if stop_criterion == "barycenter": |
| 1666 |
inner_log = False |
| 1667 |
else: |
| 1668 |
inner_log = True |
| 1669 |
curr_loss = 1e15 |
| 1670 |
|
| 1671 |
if log: |
| 1672 |
log_ = {} |
| 1673 |
log_["err"] = [] |
| 1674 |
if stop_criterion == "loss": |
| 1675 |
log_["loss"] = [] |
| 1676 |
|
| 1677 |
for cpt in range(max_iter): |
| 1678 |
if stop_criterion == "barycenter": |
| 1679 |
Cprev = C |
| 1680 |
else: |
| 1681 |
prev_loss = curr_loss |
| 1682 |
|
| 1683 |
|
| 1684 |
if warmstartT: |
| 1685 |
res = [ |
| 1686 |
semirelaxed_gromov_wasserstein( |
| 1687 |
Cs[s], |
| 1688 |
C, |
| 1689 |
ps[s], |
| 1690 |
loss_fun, |
| 1691 |
symmetric, |
| 1692 |
G0=T[s], |
| 1693 |
max_iter=max_iter, |
| 1694 |
tol_rel=tol, |
| 1695 |
tol_abs=0.0, |
| 1696 |
log=inner_log, |
| 1697 |
verbose=verbose, |
| 1698 |
**kwargs, |
| 1699 |
) |
| 1700 |
for s in range(S) |
| 1701 |
] |
| 1702 |
else: |
| 1703 |
res = [ |
| 1704 |
semirelaxed_gromov_wasserstein( |
| 1705 |
Cs[s], |
| 1706 |
C, |
| 1707 |
ps[s], |
| 1708 |
loss_fun, |
| 1709 |
symmetric, |
| 1710 |
G0=G0, |
| 1711 |
max_iter=max_iter, |
| 1712 |
tol_rel=tol, |
| 1713 |
tol_abs=0.0, |
| 1714 |
log=inner_log, |
| 1715 |
verbose=verbose, |
| 1716 |
**kwargs, |
| 1717 |
) |
| 1718 |
for s in range(S) |
| 1719 |
] |
| 1720 |
|
| 1721 |
if stop_criterion == "barycenter": |
| 1722 |
T = res |
| 1723 |
else: |
| 1724 |
T = [output[0] for output in res] |
| 1725 |
curr_loss = np.sum([output[1]["srgw_dist"] for output in res]) |
| 1726 |
|
| 1727 |
|
| 1728 |
p = nx.concatenate([nx.sum(T[s], 0)[None, :] for s in range(S)], axis=0) |
| 1729 |
|
| 1730 |
C = update_barycenter_structure(T, Cs, lambdas, p, loss_fun, nx=nx) |
| 1731 |
|
| 1732 |
|
| 1733 |
if stop_criterion == "barycenter": |
| 1734 |
err = nx.norm(C - Cprev) |
| 1735 |
if log: |
| 1736 |
log_["err"].append(err) |
| 1737 |
|
| 1738 |
else: |
| 1739 |
err = abs(curr_loss - prev_loss) / prev_loss if prev_loss != 0.0 else np.nan |
| 1740 |
if log: |
| 1741 |
log_["loss"].append(curr_loss) |
| 1742 |
log_["err"].append(err) |
| 1743 |
|
| 1744 |
if verbose: |
| 1745 |
if cpt % 200 == 0: |
| 1746 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 1747 |
print("{:5d}|{:8e}|".format(cpt, err)) |
| 1748 |
|
| 1749 |
if err <= tol: |
| 1750 |
break |
| 1751 |
|
| 1752 |
if log: |
| 1753 |
log_["T"] = T |
| 1754 |
log_["p"] = p |
| 1755 |
|
| 1756 |
return C, log_ |
| 1757 |
else: |
| 1758 |
return C |
| 1759 |
|
| 1760 |
|
| 1761 |
def semirelaxed_fgw_barycenters( |
| 1762 |
N, |
| 1763 |
Ys, |
| 1764 |
Cs, |
| 1765 |
ps=None, |
| 1766 |
lambdas=None, |
| 1767 |
alpha=0.5, |
| 1768 |
fixed_structure=False, |
| 1769 |
fixed_features=False, |
| 1770 |
p=None, |
| 1771 |
loss_fun="square_loss", |
| 1772 |
symmetric=True, |
| 1773 |
max_iter=100, |
| 1774 |
tol=1e-9, |
| 1775 |
stop_criterion="barycenter", |
| 1776 |
warmstartT=False, |
| 1777 |
verbose=False, |
| 1778 |
log=False, |
| 1779 |
init_C=None, |
| 1780 |
init_X=None, |
| 1781 |
G0="product", |
| 1782 |
random_state=None, |
| 1783 |
**kwargs, |
| 1784 |
): |
| 1785 |
r""" |
| 1786 |
Returns the Semi-relaxed Fused Gromov-Wasserstein barycenters of `S` measurable networks |
| 1787 |
with node features :math:`(\mathbf{C}_s, \mathbf{Y}_s, \mathbf{p}_s)_{1 \leq s \leq S}` |
| 1788 |
(see eq (44) in :ref:`[48]`, estimated using the semi-relaxed FGW transports from Conditional Gradient solvers. |
| 1789 |
|
| 1790 |
The function solves the following optimization problem: |
| 1791 |
|
| 1792 |
.. math:: |
| 1793 |
|
| 1794 |
\mathbf{C}^*, \mathbf{Y}^* = \mathop{\arg \min}_{\mathbf{C}\in \mathbb{R}^{N \times N}, \mathbf{Y}\in \mathbb{Y}^{N \times d}} |
| 1795 |
\quad \sum_s \lambda_s \mathrm{srFGW}_{\alpha}(\mathbf{C}_s, \mathbf{Y}_s, \mathbf{p}_s, \mathbf{C}, \mathbf{Y}) |
| 1796 |
|
| 1797 |
Where : |
| 1798 |
|
| 1799 |
- :math:`\mathbf{Y}_s`: input feature matrix |
| 1800 |
- :math:`\mathbf{C}_s`: input metric cost matrix |
| 1801 |
- :math:`\mathbf{p}_s`: input distribution |
| 1802 |
|
| 1803 |
Parameters |
| 1804 |
---------- |
| 1805 |
N : int |
| 1806 |
Desired number of samples of the target barycenter |
| 1807 |
Ys: list of array-like, each element has shape (ns,d) |
| 1808 |
Features of all samples |
| 1809 |
Cs : list of array-like, each element has shape (ns,ns) |
| 1810 |
Structure matrices of all samples |
| 1811 |
ps : list of array-like, each element has shape (ns,), optional |
| 1812 |
Masses of all samples. |
| 1813 |
If let to its default value None, uniform distributions are taken. |
| 1814 |
lambdas : array-like of shape (S,) , optional |
| 1815 |
List of the `S` spaces' weights. |
| 1816 |
If let to its default value None, uniform weights are taken. |
| 1817 |
alpha : float, optional |
| 1818 |
Alpha parameter for the srFGW divergence in :math:`]0, 1[`. |
| 1819 |
fixed_structure : bool, optional |
| 1820 |
Whether to fix the structure of the barycenter during the updates. |
| 1821 |
fixed_features : bool, optional |
| 1822 |
Whether to fix the feature of the barycenter during the updates |
| 1823 |
loss_fun : str, optional |
| 1824 |
Loss function used for the solver either 'square_loss' or 'kl_loss' |
| 1825 |
symmetric : bool, optional |
| 1826 |
Either structures are to be assumed symmetric or not. Default value is True. |
| 1827 |
Else if set to True (resp. False), C1 and C2 will be assumed symmetric (resp. asymmetric). |
| 1828 |
max_iter : int, optional |
| 1829 |
Max number of iterations |
| 1830 |
tol : float, optional |
| 1831 |
Stop threshold on relative error (>0) |
| 1832 |
stop_criterion : str, optional. Default is 'barycenter'. |
| 1833 |
Stop criterion taking values in ['barycenter', 'loss']. If set to 'barycenter' |
| 1834 |
uses absolute norm variations of estimated barycenters. Else if set to 'loss' |
| 1835 |
uses the relative variations of the loss. |
| 1836 |
warmstartT: bool, optional |
| 1837 |
Either to perform warmstart of transport plans in the successive |
| 1838 |
fused gromov-wasserstein transport problems. |
| 1839 |
verbose : bool, optional |
| 1840 |
Print information along iterations. |
| 1841 |
log : bool, optional |
| 1842 |
Record log if True. |
| 1843 |
init_C : array-like, shape (N,N), optional |
| 1844 |
Initialization for the barycenters' structure matrix. If not set |
| 1845 |
a random init is used. |
| 1846 |
init_X : array-like, shape (N,d), optional |
| 1847 |
Initialization for the barycenters' features. If not set a |
| 1848 |
random init is used. |
| 1849 |
G0: str, optional. Default is "product". |
| 1850 |
Initialization method for transport plans calling :func:`ot.gromov.semirelaxed_init_plan`, |
| 1851 |
and taking values in "product", "random_product", "random", "fluid", |
| 1852 |
"fluid_soft", "spectral", "spectral_soft", "kmeans", "kmeans_soft". |
| 1853 |
Transport plans are used to deduce an initial barycenter structure |
| 1854 |
if `init_C=None`. |
| 1855 |
random_state : int or RandomState instance, optional |
| 1856 |
Fix the seed for reproducibility |
| 1857 |
|
| 1858 |
Returns |
| 1859 |
------- |
| 1860 |
X : array-like, shape (`N`, `d`) |
| 1861 |
Barycenters' features |
| 1862 |
C : array-like, shape (`N`, `N`) |
| 1863 |
Barycenters' structure matrix |
| 1864 |
log : dict |
| 1865 |
Only returned when log=True. It contains the keys: |
| 1866 |
|
| 1867 |
- :math:`\mathbf{T}_s`: list of (`N`, `ns`) transport matrices from which target masses can be deduced. |
| 1868 |
- :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`) |
| 1869 |
- values used in convergence evaluation. |
| 1870 |
|
| 1871 |
References |
| 1872 |
---------- |
| 1873 |
.. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty. |
| 1874 |
"Semi-relaxed Gromov-Wasserstein divergence and applications on graphs" |
| 1875 |
International Conference on Learning Representations (ICLR), 2022. |
| 1876 |
""" |
| 1877 |
if stop_criterion not in ["barycenter", "loss"]: |
| 1878 |
raise ValueError( |
| 1879 |
f"Unknown `stop_criterion='{stop_criterion}'`. Use one of: {'barycenter', 'loss'}." |
| 1880 |
) |
| 1881 |
|
| 1882 |
arr = [*Cs, *Ys] |
| 1883 |
if ps is not None: |
| 1884 |
arr += [*ps] |
| 1885 |
else: |
| 1886 |
ps = [unif(C.shape[0], type_as=C) for C in Cs] |
| 1887 |
|
| 1888 |
nx = get_backend(*arr) |
| 1889 |
|
| 1890 |
S = len(Cs) |
| 1891 |
if lambdas is None: |
| 1892 |
lambdas = nx.ones(S) / S |
| 1893 |
else: |
| 1894 |
lambdas = list_to_array(lambdas) |
| 1895 |
lambdas = nx.from_numpy(lambdas) |
| 1896 |
|
| 1897 |
if fixed_structure: |
| 1898 |
if init_C is None: |
| 1899 |
raise UndefinedParameter("If C is fixed it must be provided in init_C") |
| 1900 |
else: |
| 1901 |
C = init_C |
| 1902 |
|
| 1903 |
if fixed_features: |
| 1904 |
if init_X is None: |
| 1905 |
raise UndefinedParameter("If X is fixed it must be provided in init_X") |
| 1906 |
else: |
| 1907 |
X = init_X |
| 1908 |
|
| 1909 |
|
| 1910 |
if G0 in ["product", "random_product", "random"]: |
| 1911 |
|
| 1912 |
|
| 1913 |
if init_C is None: |
| 1914 |
init_C = nx.zeros((N, N), type_as=Cs[0]) |
| 1915 |
|
| 1916 |
T = [ |
| 1917 |
semirelaxed_init_plan( |
| 1918 |
Cs[i], |
| 1919 |
init_C, |
| 1920 |
ps[i], |
| 1921 |
method=G0, |
| 1922 |
use_target=False, |
| 1923 |
random_state=random_state, |
| 1924 |
nx=nx, |
| 1925 |
) |
| 1926 |
for i in range(S) |
| 1927 |
] |
| 1928 |
|
| 1929 |
C = update_barycenter_structure(T, Cs, lambdas, loss_fun=loss_fun, nx=nx) |
| 1930 |
if G0 in ["product", "random_product"]: |
| 1931 |
|
| 1932 |
|
| 1933 |
np.random.seed(random_state) |
| 1934 |
noise = np.random.uniform(-0.01, 0.01, size=(N, N)) |
| 1935 |
if symmetric: |
| 1936 |
noise = (noise + noise.T) / 2.0 |
| 1937 |
noise = nx.from_numpy(noise) |
| 1938 |
C = C + noise |
| 1939 |
|
| 1940 |
else: |
| 1941 |
T = [ |
| 1942 |
semirelaxed_init_plan( |
| 1943 |
Cs[i], |
| 1944 |
init_C, |
| 1945 |
ps[i], |
| 1946 |
method=G0, |
| 1947 |
use_target=False, |
| 1948 |
random_state=random_state, |
| 1949 |
nx=nx, |
| 1950 |
) |
| 1951 |
for i in range(S) |
| 1952 |
] |
| 1953 |
|
| 1954 |
C = init_C |
| 1955 |
|
| 1956 |
if init_X is None: |
| 1957 |
X = update_barycenter_feature(T, Ys, lambdas, loss_fun=loss_fun, nx=nx) |
| 1958 |
else: |
| 1959 |
X = init_X |
| 1960 |
|
| 1961 |
Ms = [dist(Ys[s], X) for s in range(len(Ys))] |
| 1962 |
|
| 1963 |
else: |
| 1964 |
|
| 1965 |
|
| 1966 |
|
| 1967 |
|
| 1968 |
if init_X is None: |
| 1969 |
stacked_features = nx.concatenate(Ys, axis=0) |
| 1970 |
if sklearn_import: |
| 1971 |
stacked_features = nx.to_numpy(stacked_features) |
| 1972 |
km = KMeans(n_clusters=N, random_state=random_state, n_init=1).fit( |
| 1973 |
stacked_features |
| 1974 |
) |
| 1975 |
X = nx.from_numpy(km.cluster_centers_) |
| 1976 |
else: |
| 1977 |
raise ValueError( |
| 1978 |
f"Scikit-learn must be installed to use G0={G0} while init_X=None." |
| 1979 |
) |
| 1980 |
else: |
| 1981 |
X = init_X |
| 1982 |
|
| 1983 |
Ms = [dist(Ys[s], X) for s in range(len(Ys))] |
| 1984 |
|
| 1985 |
if init_C is None: |
| 1986 |
init_C = nx.zeros((N, N), type_as=Cs[0]) |
| 1987 |
|
| 1988 |
|
| 1989 |
shapes = np.array([C.shape[0] for C in Cs]) |
| 1990 |
large_graphs_idx = np.where(shapes > N)[0] |
| 1991 |
small_graphs_idx = np.where(shapes <= N)[0] |
| 1992 |
T = [None] * S |
| 1993 |
list_init_C = [] |
| 1994 |
|
| 1995 |
|
| 1996 |
|
| 1997 |
|
| 1998 |
for indices in [large_graphs_idx, small_graphs_idx]: |
| 1999 |
if len(indices) > 0: |
| 2000 |
sub_T = [ |
| 2001 |
semirelaxed_init_plan( |
| 2002 |
Cs[i], |
| 2003 |
init_C, |
| 2004 |
ps[i], |
| 2005 |
Ms[i], |
| 2006 |
alpha, |
| 2007 |
method=G0, |
| 2008 |
use_target=False, |
| 2009 |
random_state=random_state, |
| 2010 |
nx=nx, |
| 2011 |
) |
| 2012 |
for i in indices |
| 2013 |
] |
| 2014 |
sub_Cs = [Cs[i] for i in indices] |
| 2015 |
sub_lambdas = lambdas[indices] / nx.sum(lambdas[indices]) |
| 2016 |
|
| 2017 |
init_C = update_barycenter_structure( |
| 2018 |
sub_T, sub_Cs, sub_lambdas, loss_fun=loss_fun, nx=nx |
| 2019 |
) |
| 2020 |
|
| 2021 |
for i, idx in enumerate(indices): |
| 2022 |
T[idx] = sub_T[i] |
| 2023 |
|
| 2024 |
list_init_C.append(init_C) |
| 2025 |
|
| 2026 |
if len(list_init_C) == 2: |
| 2027 |
init_C = update_barycenter_structure( |
| 2028 |
T, Cs, lambdas, loss_fun=loss_fun, nx=nx |
| 2029 |
) |
| 2030 |
C = init_C |
| 2031 |
else: |
| 2032 |
C = init_C |
| 2033 |
T = [ |
| 2034 |
semirelaxed_init_plan( |
| 2035 |
Cs[i], |
| 2036 |
C, |
| 2037 |
ps[i], |
| 2038 |
Ms[i], |
| 2039 |
alpha, |
| 2040 |
method=G0, |
| 2041 |
use_target=True, |
| 2042 |
random_state=random_state, |
| 2043 |
nx=nx, |
| 2044 |
) |
| 2045 |
for i in range(S) |
| 2046 |
] |
| 2047 |
|
| 2048 |
if stop_criterion == "barycenter": |
| 2049 |
inner_log = False |
| 2050 |
|
| 2051 |
else: |
| 2052 |
inner_log = True |
| 2053 |
curr_loss = 1e15 |
| 2054 |
|
| 2055 |
if log: |
| 2056 |
log_ = {} |
| 2057 |
if stop_criterion == "barycenter": |
| 2058 |
log_["err_feature"] = [] |
| 2059 |
log_["err_structure"] = [] |
| 2060 |
else: |
| 2061 |
log_["loss"] = [] |
| 2062 |
log_["err_rel_loss"] = [] |
| 2063 |
|
| 2064 |
for cpt in range(max_iter): |
| 2065 |
if stop_criterion == "barycenter": |
| 2066 |
Cprev = C |
| 2067 |
Xprev = X |
| 2068 |
else: |
| 2069 |
prev_loss = curr_loss |
| 2070 |
|
| 2071 |
|
| 2072 |
if warmstartT: |
| 2073 |
res = [ |
| 2074 |
semirelaxed_fused_gromov_wasserstein( |
| 2075 |
Ms[s], |
| 2076 |
Cs[s], |
| 2077 |
C, |
| 2078 |
ps[s], |
| 2079 |
loss_fun, |
| 2080 |
symmetric, |
| 2081 |
alpha, |
| 2082 |
T[s], |
| 2083 |
inner_log, |
| 2084 |
max_iter, |
| 2085 |
tol_rel=tol, |
| 2086 |
tol_abs=0.0, |
| 2087 |
**kwargs, |
| 2088 |
) |
| 2089 |
for s in range(S) |
| 2090 |
] |
| 2091 |
else: |
| 2092 |
res = [ |
| 2093 |
semirelaxed_fused_gromov_wasserstein( |
| 2094 |
Ms[s], |
| 2095 |
Cs[s], |
| 2096 |
C, |
| 2097 |
ps[s], |
| 2098 |
loss_fun, |
| 2099 |
symmetric, |
| 2100 |
alpha, |
| 2101 |
G0, |
| 2102 |
inner_log, |
| 2103 |
max_iter, |
| 2104 |
tol_rel=tol, |
| 2105 |
tol_abs=0.0, |
| 2106 |
**kwargs, |
| 2107 |
) |
| 2108 |
for s in range(S) |
| 2109 |
] |
| 2110 |
|
| 2111 |
if stop_criterion == "barycenter": |
| 2112 |
T = res |
| 2113 |
else: |
| 2114 |
T = [output[0] for output in res] |
| 2115 |
curr_loss = np.sum([output[1]["srfgw_dist"] for output in res]) |
| 2116 |
|
| 2117 |
|
| 2118 |
p = nx.concatenate([nx.sum(T[s], 0)[None, :] for s in range(S)], axis=0) |
| 2119 |
|
| 2120 |
if not fixed_features: |
| 2121 |
X = update_barycenter_feature(T, Ys, lambdas, p, nx=nx) |
| 2122 |
Ms = [dist(Ys[s], X) for s in range(len(Ys))] |
| 2123 |
|
| 2124 |
if not fixed_structure: |
| 2125 |
C = update_barycenter_structure(T, Cs, lambdas, p, loss_fun, nx=nx) |
| 2126 |
|
| 2127 |
|
| 2128 |
if stop_criterion == "barycenter": |
| 2129 |
err_feature, err_structure = 0.0, 0.0 |
| 2130 |
if not fixed_features: |
| 2131 |
err_feature = nx.norm(X - Xprev) |
| 2132 |
if not fixed_structure: |
| 2133 |
err_structure = nx.norm(C - Cprev) |
| 2134 |
if log: |
| 2135 |
log_["err_feature"].append(err_feature) |
| 2136 |
log_["err_structure"].append(err_structure) |
| 2137 |
|
| 2138 |
if verbose: |
| 2139 |
if cpt % 200 == 0: |
| 2140 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 2141 |
print("{:5d}|{:8e}|".format(cpt, err_structure)) |
| 2142 |
print("{:5d}|{:8e}|".format(cpt, err_feature)) |
| 2143 |
|
| 2144 |
if (err_feature <= tol) or (err_structure <= tol): |
| 2145 |
break |
| 2146 |
else: |
| 2147 |
err_rel_loss = ( |
| 2148 |
abs(curr_loss - prev_loss) / prev_loss if prev_loss != 0.0 else np.nan |
| 2149 |
) |
| 2150 |
if log: |
| 2151 |
log_["loss"].append(curr_loss) |
| 2152 |
log_["err_rel_loss"].append(err_rel_loss) |
| 2153 |
|
| 2154 |
if verbose: |
| 2155 |
if cpt % 200 == 0: |
| 2156 |
print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19) |
| 2157 |
print("{:5d}|{:8e}|".format(cpt, err_rel_loss)) |
| 2158 |
|
| 2159 |
if err_rel_loss <= tol: |
| 2160 |
break |
| 2161 |
|
| 2162 |
if log: |
| 2163 |
log_["T"] = T |
| 2164 |
log_["p"] = p |
| 2165 |
log_["Ms"] = Ms |
| 2166 |
|
| 2167 |
return X, C, log_ |
| 2168 |
else: |
| 2169 |
return X, C |