Debian Codegraph @

ot/gromov/_unbalanced.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Unbalanced Co-Optimal Transport and Fused Unbalanced Gromov-Wasserstein solvers
4 """
5
6 # Author: Quang Huy Tran <[email protected]>
7 # Alexis Thual <[email protected]>
8 #
9 # License: MIT License
10
11 import warnings
12 from functools import partial
13 import ot
14 from ot.backend import get_backend
15 from ot.utils import list_to_array, get_parameter_pair
16 from ._utils import (
17 fused_unbalanced_across_spaces_cost,
18 uot_cost_matrix,
19 uot_parameters_and_measures,
20 )
21
22
23 def fused_unbalanced_across_spaces_divergence(
24 X,
25 Y,
26 wx_samp=None,
27 wx_feat=None,
28 wy_samp=None,
29 wy_feat=None,
30 reg_marginals=10,
31 epsilon=0,
32 reg_type="joint",
33 divergence="kl",
34 unbalanced_solver="sinkhorn",
35 alpha=0,
36 M_samp=None,
37 M_feat=None,
38 rescale_plan=True,
39 init_pi=None,
40 init_duals=None,
41 max_iter=100,
42 tol=1e-7,
43 max_iter_ot=500,
44 tol_ot=1e-7,
45 log=False,
46 verbose=False,
47 **kwargs_solver,
48 ):
49 r"""Compute the fused unbalanced cross-spaces divergence between two matrices equipped
50 with the distributions on rows and columns. We consider two cases of matrix:
51
52 - (Squared) similarity matrix in Gromov-Wasserstein setting,
53 whose rows and columns represent the samples.
54
55 - Arbitrary-size matrix in Co-Optimal Transport setting,
56 whose rows represent samples, and columns represent corresponding features/dimensions.
57
58 More precisely, this function returns the sample and feature transport plans between
59 :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
60 :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`,
61 by solving the following problem using Block Coordinate Descent algorithm:
62
63 .. math::
64
65 \mathop{\arg \min}_{\mathbf{P}, \mathbf{Q}}
66 &\quad \sum_{i,j,k,l}
67 (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l} \\
68 &+ \rho_s \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
69 + \rho_f \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w}_{xf} \mathbf{w}_{yf}^T) \\
70 &+ \alpha_s \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j}
71 + \alpha_f \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l}
72 + \mathbf{Reg}(\mathbf{P}, \mathbf{Q})
73
74 Where:
75
76 - :math:`\mathbf{X}`: Source input (arbitrary-size) matrix
77 - :math:`\mathbf{Y}`: Target input (arbitrary-size) matrix
78 - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
79 - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
80 - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
81 - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
82 - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
83 - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
84 - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.
85 - :math:`\mathbf{Reg}`: Regularizer for sample and feature couplings.
86
87 We consider two types of regularizer:
88 + Independent regularization used in unbalanced Co-Optimal Transport
89
90 .. math::
91 \mathbf{Reg}(\mathbf{P}, \mathbf{Q}) =
92 \varepsilon_s \mathbf{Div}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
93 + \varepsilon_f \mathbf{Div}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)
94
95 + Joint regularization used in fused unbalanced Gromov-Wasserstein
96
97 .. math::
98 \mathbf{Reg}(\mathbf{P}, \mathbf{Q}) =
99 \varepsilon \mathbf{Div}(\mathbf{P} \otimes \mathbf{Q} | (\mathbf{w}_{xs} \mathbf{w}_{ys}^T) \otimes (\mathbf{w}_{xf} \mathbf{w}_{yf}^T) )
100
101 .. note:: This function allows epsilon to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".
102
103 Parameters
104 ----------
105 X : (n_sample_x, n_feature_x) array-like, float
106 Source input matrix.
107 Y : (n_sample_y, n_feature_y) array-like, float
108 Target input matrix.
109 wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
110 Histogram assigned on rows (samples) of matrix X.
111 Uniform distribution by default.
112 wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
113 Histogram assigned on columns (features) of matrix X.
114 Uniform distribution by default.
115 wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
116 Histogram assigned on rows (samples) of matrix Y.
117 Uniform distribution by default.
118 wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
119 Histogram assigned on columns (features) of matrix Y.
120 Uniform distribution by default.
121 reg_marginals: float or indexable object of length 1 or 2
122 Marginal relaxation terms for sample and feature couplings.
123 If `reg_marginals` is a scalar or an indexable object of length 1,
124 then the same value is applied to both marginal relaxations.
125 epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
126 Regularization parameters for entropic approximation of sample and feature couplings.
127 Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
128 instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
129 both regularization of sample and feature couplings.
130 reg_type: string, optional
131
132 - If `reg_type` = "joint": then use joint regularization for couplings.
133
134 - If `reg_type` = "independent": then use independent regularization for couplings.
135 divergence : string, optional (default = "kl")
136
137 - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.
138
139 - If `divergence` = "l2", then Div is the half squared Euclidean norm.
140 unbalanced_solver : string, optional (default = "sinkhorn")
141 Solver for the unbalanced OT subroutine.
142
143 - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"
144
145 - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
146 alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
147 Coeffficient parameter of linear terms with respect to the sample and feature couplings.
148 If alpha is scalar, then the same alpha is applied to both linear terms.
149 M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
150 Sample matrix associated to the Wasserstein linear term on sample coupling.
151 M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
152 Feature matrix associated to the Wasserstein linear term on feature coupling.
153 rescale_plan : boolean, optional (default = True)
154 If True, then rescale the sample and feature transport plans within each BCD iteration,
155 so that they always have equal mass.
156 init_pi : tuple of two matrices of size (n_sample_x, n_sample_y) and
157 (n_feature_x, n_feature_y), optional (default = None).
158 Initialization of sample and feature couplings.
159 Uniform distributions by default.
160 init_duals : tuple of two tuples ((n_sample_x, ), (n_sample_y, )) and ((n_feature_x, ), (n_feature_y, )), optional (default = None).
161 Initialization of sample and feature dual vectors
162 if using Sinkhorn algorithm. Zero vectors by default.
163 max_iter : int, optional (default = 100)
164 Number of Block Coordinate Descent (BCD) iterations.
165 tol : float, optional (default = 1e-7)
166 Tolerance of BCD scheme. If the L1-norm between the current and previous
167 sample couplings is under this threshold, then stop BCD scheme.
168 max_iter_ot : int, optional (default = 100)
169 Number of iterations to solve each of the
170 two unbalanced optimal transport problems in each BCD iteration.
171 tol_ot : float, optional (default = 1e-7)
172 Tolerance of unbalanced solver for each of the
173 two unbalanced optimal transport problems in each BCD iteration.
174 log : bool, optional (default = False)
175 If True then the cost and four dual vectors, including
176 two from sample and two from feature couplings, are recorded.
177 verbose : bool, optional (default = False)
178 If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.
179
180 Returns
181 -------
182 pi_samp : (n_sample_x, n_sample_y) array-like, float
183 Sample coupling matrix.
184 pi_feat : (n_feature_x, n_feature_y) array-like, float
185 Feature coupling matrix.
186 log : dictionary, optional
187 Returned if `log` is True. The keys are:
188
189 error : array-like, float
190 list of L1 norms between the current and previous sample coupling.
191 duals_sample : (n_sample_x, n_sample_y) tuple, float
192 Pair of dual vectors when solving OT problem w.r.t the sample coupling.
193 duals_feature : (n_feature_x, n_feature_y) tuple, float
194 Pair of dual vectors when solving OT problem w.r.t the feature coupling.
195 linear : float
196 Linear part of the cost.
197 ucoot : float
198 Total cost.
199 backend
200 The proper backend for all input arrays
201 """
202
203 # MAIN FUNCTION
204
205 if reg_type not in ["joint", "independent"]:
206 raise (NotImplementedError('Unknown reg_type="{}"'.format(reg_type)))
207 if divergence not in ["kl", "l2"]:
208 raise (NotImplementedError('Unknown divergence="{}"'.format(divergence)))
209 if unbalanced_solver not in ["sinkhorn", "sinkhorn_log", "mm", "lbfgsb"]:
210 raise (NotImplementedError('Unknown method="{}"'.format(unbalanced_solver)))
211
212 # hyperparameters
213 alpha_samp, alpha_feat = get_parameter_pair(alpha)
214 rho_x, rho_y = get_parameter_pair(reg_marginals)
215 eps_samp, eps_feat = get_parameter_pair(epsilon)
216
217 if reg_type == "joint": # same regularization
218 eps_feat = eps_samp
219 if unbalanced_solver in ["sinkhorn", "sinkhorn_log"] and divergence == "l2":
220 warnings.warn(
221 "Sinkhorn algorithm does not support L2 norm. \
222 Divergence is set to 'kl'."
223 )
224 divergence = "kl"
225 if unbalanced_solver in ["sinkhorn", "sinkhorn_log"] and (
226 eps_samp == 0 or eps_feat == 0
227 ):
228 warnings.warn(
229 "Sinkhorn algorithm does not support unregularized problem. \
230 Solver is set to 'mm'."
231 )
232 unbalanced_solver = "mm"
233
234 if init_pi is None:
235 pi_samp, pi_feat = None, None
236 else:
237 pi_samp, pi_feat = init_pi
238
239 if init_duals is None:
240 init_duals = (None, None)
241 duals_samp, duals_feat = init_duals
242
243 arr = [X, Y]
244
245 for tuple in [duals_samp, duals_feat]:
246 if tuple is not None:
247 d1, d2 = duals_feat
248 if d1 is not None:
249 arr.append(list_to_array(d1))
250 if d2 is not None:
251 arr.append(list_to_array(d2))
252
253 nx = get_backend(
254 *arr, wx_samp, wx_feat, wy_samp, wy_feat, M_samp, M_feat, pi_samp, pi_feat
255 )
256
257 # constant input variables
258 if M_samp is None:
259 if alpha_samp > 0:
260 warnings.warn(
261 "M_samp is None but alpha_samp = {} > 0. \
262 The algo will treat as if alpha_samp = 0.".format(alpha_samp)
263 )
264 else:
265 M_samp = alpha_samp * M_samp
266
267 if M_feat is None:
268 if alpha_feat > 0:
269 warnings.warn(
270 "M_feat is None but alpha_feat = {} > 0. \
271 The algo will treat as if alpha_feat = 0.".format(alpha_feat)
272 )
273 else:
274 M_feat = alpha_feat * M_feat
275
276 nx_samp, nx_feat = X.shape
277 ny_samp, ny_feat = Y.shape
278
279 # measures on rows and columns
280 if wx_samp is None:
281 wx_samp = nx.ones(nx_samp, type_as=X) / nx_samp
282 if wx_feat is None:
283 wx_feat = nx.ones(nx_feat, type_as=X) / nx_feat
284 if wy_samp is None:
285 wy_samp = nx.ones(ny_samp, type_as=Y) / ny_samp
286 if wy_feat is None:
287 wy_feat = nx.ones(ny_feat, type_as=Y) / ny_feat
288 wxy_samp = wx_samp[:, None] * wy_samp[None, :]
289 wxy_feat = wx_feat[:, None] * wy_feat[None, :]
290
291 # initialize coupling and dual vectors
292 pi_samp = wxy_samp if pi_samp is None else pi_samp
293 pi_feat = wxy_feat if pi_feat is None else pi_feat
294
295 if unbalanced_solver in ["sinkhorn", "sinkhorn_log"]:
296 if duals_samp is None:
297 duals_samp = (nx.zeros(nx_samp, type_as=X), nx.zeros(ny_samp, type_as=Y))
298 if duals_feat is None:
299 duals_feat = (nx.zeros(nx_feat, type_as=X), nx.zeros(ny_feat, type_as=Y))
300
301 # shortcut functions
302 X_sqr, Y_sqr = X**2, Y**2
303 local_cost_samp = partial(
304 uot_cost_matrix,
305 data=(X_sqr, Y_sqr, X, Y, M_samp),
306 tuple_p=(wx_feat, wy_feat),
307 hyperparams=(rho_x, rho_y, eps_feat),
308 divergence=divergence,
309 reg_type=reg_type,
310 nx=nx,
311 )
312
313 local_cost_feat = partial(
314 uot_cost_matrix,
315 data=(X_sqr.T, Y_sqr.T, X.T, Y.T, M_feat),
316 tuple_p=(wx_samp, wy_samp),
317 hyperparams=(rho_x, rho_y, eps_samp),
318 divergence=divergence,
319 reg_type=reg_type,
320 nx=nx,
321 )
322
323 parameters_uot_l2_samp = partial(
324 uot_parameters_and_measures,
325 tuple_weights=(wx_samp, wy_samp, wxy_samp),
326 hyperparams=(rho_x, rho_y, eps_samp),
327 reg_type=reg_type,
328 divergence=divergence,
329 nx=nx,
330 )
331
332 parameters_uot_l2_feat = partial(
333 uot_parameters_and_measures,
334 tuple_weights=(wx_feat, wy_feat, wxy_feat),
335 hyperparams=(rho_x, rho_y, eps_feat),
336 reg_type=reg_type,
337 divergence=divergence,
338 nx=nx,
339 )
340
341 solver = partial(
342 ot.solve,
343 reg_type=divergence,
344 unbalanced_type=divergence,
345 method=unbalanced_solver,
346 max_iter=max_iter_ot,
347 tol=tol_ot,
348 verbose=False,
349 )
350
351 # initialize log
352 if log:
353 dict_log = {"backend": nx, "error": []}
354
355 for idx in range(max_iter):
356 pi_samp_prev = nx.copy(pi_samp)
357
358 # Update feature coupling
359 mass = nx.sum(pi_samp)
360 uot_cost = local_cost_feat(pi=pi_samp)
361
362 if divergence == "kl":
363 new_rho = (rho_x * mass, rho_y * mass)
364 new_eps = mass * eps_feat if reg_type == "joint" else eps_feat
365 new_wx, new_wy, new_wxy = wx_feat, wy_feat, wxy_feat
366 else: # divergence == "l2"
367 new_w, new_rho, new_eps = parameters_uot_l2_feat(pi_feat)
368 new_wx, new_wy, new_wxy = new_w
369
370 res = solver(
371 M=uot_cost,
372 a=new_wx,
373 b=new_wy,
374 reg=new_eps,
375 c=new_wxy,
376 unbalanced=new_rho,
377 plan_init=pi_feat,
378 potentials_init=duals_feat,
379 )
380 pi_feat, duals_feat = res.plan, res.potentials
381
382 if rescale_plan:
383 pi_feat = nx.sqrt(mass / nx.sum(pi_feat)) * pi_feat
384
385 # Update sample coupling
386 mass = nx.sum(pi_feat)
387 uot_cost = local_cost_samp(pi=pi_feat)
388
389 if divergence == "kl":
390 new_rho = (rho_x * mass, rho_y * mass)
391 new_eps = mass * eps_feat if reg_type == "joint" else eps_feat
392 new_wx, new_wy, new_wxy = wx_samp, wy_samp, wxy_samp
393 else: # divergence == "l2"
394 new_w, new_rho, new_eps = parameters_uot_l2_samp(pi_samp)
395 new_wx, new_wy, new_wxy = new_w
396
397 res = solver(
398 M=uot_cost,
399 a=new_wx,
400 b=new_wy,
401 reg=new_eps,
402 c=new_wxy,
403 unbalanced=new_rho,
404 plan_init=pi_samp,
405 potentials_init=duals_samp,
406 )
407 pi_samp, duals_samp = res.plan, res.potentials
408
409 if rescale_plan:
410 pi_samp = nx.sqrt(mass / nx.sum(pi_samp)) * pi_samp # shape nx x ny
411
412 # get L1 error
413 err = nx.sum(nx.abs(pi_samp - pi_samp_prev))
414 if log:
415 dict_log["error"].append(err)
416 if verbose:
417 print("{:5d}|{:8e}|".format(idx + 1, err))
418 if err < tol:
419 break
420
421 # sanity check
422 if nx.sum(nx.isnan(pi_samp)) > 0 or nx.sum(nx.isnan(pi_feat)) > 0:
423 raise (
424 ValueError(
425 "There is NaN in coupling. \
426 Adjust the relaxation or regularization parameters."
427 )
428 )
429
430 if log:
431 linear_cost, ucoot_cost = fused_unbalanced_across_spaces_cost(
432 M_linear=(M_samp, M_feat),
433 data=(X_sqr, Y_sqr, X, Y),
434 tuple_pxy_samp=(wx_samp, wy_samp, wxy_samp),
435 tuple_pxy_feat=(wx_feat, wy_feat, wxy_feat),
436 pi_samp=pi_samp,
437 pi_feat=pi_feat,
438 hyperparams=(rho_x, rho_y, eps_samp, eps_feat),
439 divergence=divergence,
440 reg_type=reg_type,
441 nx=nx,
442 )
443
444 dict_log["duals_sample"] = duals_samp
445 dict_log["duals_feature"] = duals_feat
446 dict_log["linear_cost"] = linear_cost
447 dict_log["ucoot_cost"] = ucoot_cost
448
449 return pi_samp, pi_feat, dict_log
450
451 else:
452 return pi_samp, pi_feat
453
454
455 def unbalanced_co_optimal_transport(
456 X,
457 Y,
458 wx_samp=None,
459 wx_feat=None,
460 wy_samp=None,
461 wy_feat=None,
462 reg_marginals=10,
463 epsilon=0,
464 divergence="kl",
465 unbalanced_solver="mm",
466 alpha=0,
467 M_samp=None,
468 M_feat=None,
469 rescale_plan=True,
470 init_pi=None,
471 init_duals=None,
472 max_iter=100,
473 tol=1e-7,
474 max_iter_ot=500,
475 tol_ot=1e-7,
476 log=False,
477 verbose=False,
478 **kwargs_solve,
479 ):
480 r"""Compute the unbalanced Co-Optimal Transport between two Euclidean point clouds
481 (represented as matrices whose rows are samples and columns are the features/dimensions).
482
483 More precisely, this function returns the sample and feature transport plans between
484 :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
485 :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`,
486 by solving the following problem using Block Coordinate Descent algorithm:
487
488 .. math::
489 \mathop{\arg \min}_{\mathbf{P}, \mathbf{Q}} &\quad \sum_{i,j,k,l}
490 (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l} \\
491 &+ \rho_s \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
492 + \rho_f \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w}_{xf} \mathbf{w}_{yf}^T) \\
493 &+ \alpha_s \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j}
494 + \alpha_f \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l} \\
495 &+ \varepsilon_s \mathbf{Div}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
496 + \varepsilon_f \mathbf{Div}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)
497
498 Where:
499
500 - :math:`\mathbf{X}`: Source input (arbitrary-size) matrix
501 - :math:`\mathbf{Y}`: Target input (arbitrary-size) matrix
502 - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
503 - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
504 - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
505 - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
506 - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
507 - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
508 - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.
509
510 .. note:: This function allows `epsilon` to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".
511
512 Parameters
513 ----------
514 X : (n_sample_x, n_feature_x) array-like, float
515 Source input matrix.
516 Y : (n_sample_y, n_feature_y) array-like, float
517 Target input matrix.
518 wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
519 Histogram assigned on rows (samples) of matrix X.
520 Uniform distribution by default.
521 wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
522 Histogram assigned on columns (features) of matrix X.
523 Uniform distribution by default.
524 wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
525 Histogram assigned on rows (samples) of matrix Y.
526 Uniform distribution by default.
527 wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
528 Histogram assigned on columns (features) of matrix Y.
529 Uniform distribution by default.
530 reg_marginals: float or indexable object of length 1 or 2
531 Marginal relaxation terms for sample and feature couplings.
532 If `reg_marginals is a scalar` or an indexable object of length 1,
533 then the same value is applied to both marginal relaxations.
534 epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
535 Regularization parameters for entropic approximation of sample and feature couplings.
536 Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
537 instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
538 both regularization of sample and feature couplings.
539 divergence : string, optional (default = "kl")
540
541 - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.
542
543 - If `divergence` = "l2", then Div is the half squared Euclidean norm.
544 unbalanced_solver : string, optional (default = "sinkhorn")
545 Solver for the unbalanced OT subroutine.
546
547 - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"
548
549 - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
550 alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
551 Coeffficient parameter of linear terms with respect to the sample and feature couplings.
552 If alpha is scalar, then the same alpha is applied to both linear terms.
553 M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
554 Sample matrix associated to the Wasserstein linear term on sample coupling.
555 M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
556 Feature matrix associated to the Wasserstein linear term on feature coupling.
557 rescale_plan : boolean, optional (default = True)
558 If True, then rescale the sample and feature transport plans within each BCD iteration,
559 so that they always have equal mass.
560 init_pi : tuple of two matrices of size (n_sample_x, n_sample_y) and
561 (n_feature_x, n_feature_y), optional (default = None).
562 Initialization of sample and feature couplings.
563 Uniform distributions by default.
564 init_duals : tuple of two tuples ((n_sample_x, ), (n_sample_y, )) and ((n_feature_x, ), (n_feature_y, )), optional (default = None).
565 Initialization of sample and feature dual vectors
566 if using Sinkhorn algorithm. Zero vectors by default.
567 max_iter : int, optional (default = 100)
568 Number of Block Coordinate Descent (BCD) iterations.
569 tol : float, optional (default = 1e-7)
570 Tolerance of BCD scheme. If the L1-norm between the current and previous
571 sample couplings is under this threshold, then stop BCD scheme.
572 max_iter_ot : int, optional (default = 100)
573 Number of iterations to solve each of the
574 two unbalanced optimal transport problems in each BCD iteration.
575 tol_ot : float, optional (default = 1e-7)
576 Tolerance of unbalanced solver for each of the
577 two unbalanced optimal transport problems in each BCD iteration.
578 log : bool, optional (default = False)
579 If True then the cost and four dual vectors, including
580 two from sample and two from feature couplings, are recorded.
581 verbose : bool, optional (default = False)
582 If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.
583
584 Returns
585 -------
586 pi_samp : (n_sample_x, n_sample_y) array-like, float
587 Sample coupling matrix.
588 pi_feat : (n_feature_x, n_feature_y) array-like, float
589 Feature coupling matrix.
590 log : dictionary, optional
591 Returned if `log` is True. The keys are:
592
593 error : array-like, float
594 list of L1 norms between the current and previous sample coupling.
595 duals_sample : (n_sample_x, n_sample_y)-tuple, float
596 Pair of dual vectors when solving OT problem w.r.t the sample coupling.
597 duals_feature : (n_feature_x, n_feature_y)-tuple, float
598 Pair of dual vectors when solving OT problem w.r.t the feature coupling.
599 linear : float
600 Linear part of the cost.
601 ucoot : float
602 Total cost.
603
604 References
605 ----------
606 .. [71] Tran, H., Janati, H., Courty, N., Flamary, R., Redko, I., Demetci, P., & Singh, R.
607 Unbalanced Co-Optimal Transport. AAAI Conference on Artificial Intelligence, 2023.
608 """
609
610 return fused_unbalanced_across_spaces_divergence(
611 X=X,
612 Y=Y,
613 wx_samp=wx_samp,
614 wx_feat=wx_feat,
615 wy_samp=wy_samp,
616 wy_feat=wy_feat,
617 reg_marginals=reg_marginals,
618 epsilon=epsilon,
619 reg_type="independent",
620 divergence=divergence,
621 unbalanced_solver=unbalanced_solver,
622 alpha=alpha,
623 M_samp=M_samp,
624 M_feat=M_feat,
625 rescale_plan=rescale_plan,
626 init_pi=init_pi,
627 init_duals=init_duals,
628 max_iter=max_iter,
629 tol=tol,
630 max_iter_ot=max_iter_ot,
631 tol_ot=tol_ot,
632 log=log,
633 verbose=verbose,
634 **kwargs_solve,
635 )
636
637
638 def unbalanced_co_optimal_transport2(
639 X,
640 Y,
641 wx_samp=None,
642 wx_feat=None,
643 wy_samp=None,
644 wy_feat=None,
645 reg_marginals=10,
646 epsilon=0,
647 divergence="kl",
648 unbalanced_solver="sinkhorn",
649 alpha=0,
650 M_samp=None,
651 M_feat=None,
652 rescale_plan=True,
653 init_pi=None,
654 init_duals=None,
655 max_iter=100,
656 tol=1e-7,
657 max_iter_ot=500,
658 tol_ot=1e-7,
659 log=False,
660 verbose=False,
661 **kwargs_solve,
662 ):
663 r"""Compute the unbalanced Co-Optimal Transport between two Euclidean point clouds
664 (represented as matrices whose rows are samples and columns are the features/dimensions).
665
666 More precisely, this function returns the unbalanced Co-Optimal Transport cost between
667 :math:`(\mathbf{X}, \mathbf{w}_{xs}, \mathbf{w}_{xf})` and
668 :math:`(\mathbf{Y}, \mathbf{w}_{ys}, \mathbf{w}_{yf})`,
669 by solving the following problem using Block Coordinate Descent algorithm:
670
671 .. math::
672 \mathop{\min}_{\mathbf{P}, \mathbf{Q}} &\quad \sum_{i,j,k,l}
673 (\mathbf{X}_{i,k} - \mathbf{Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l} \\
674 &+ \rho_s \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
675 + \rho_f \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w}_{xf} \mathbf{w}_{yf}^T) \\
676 &+ \alpha_s \sum_{i,j} \mathbf{P}_{i,j} \mathbf{M^{(s)}}_{i, j}
677 + \alpha_f \sum_{k, l} \mathbf{Q}_{k,l} \mathbf{M^{(f)}}_{k, l} \\
678 &+ \varepsilon_s \mathbf{Div}(\mathbf{P} | \mathbf{w}_{xs} \mathbf{w}_{ys}^T)
679 + \varepsilon_f \mathbf{Div}(\mathbf{Q} | \mathbf{w}_{xf} \mathbf{w}_{yf}^T)
680
681 Where:
682
683 - :math:`\mathbf{X}`: Source input (arbitrary-size) matrix
684 - :math:`\mathbf{Y}`: Target input (arbitrary-size) matrix
685 - :math:`\mathbf{M^{(s)}}`: Additional sample matrix
686 - :math:`\mathbf{M^{(f)}}`: Additional feature matrix
687 - :math:`\mathbf{w}_{xs}`: Distribution of the samples in the source space
688 - :math:`\mathbf{w}_{xf}`: Distribution of the features in the source space
689 - :math:`\mathbf{w}_{ys}`: Distribution of the samples in the target space
690 - :math:`\mathbf{w}_{yf}`: Distribution of the features in the target space
691 - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.
692
693 .. note:: This function allows `epsilon` to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".
694 Also the computation of gradients is only supported for KL divergence. The case of half squared-L2 norm uses those of KL divergence.
695
696 Parameters
697 ----------
698 X : (n_sample_x, n_feature_x) array-like, float
699 Source input matrix.
700 Y : (n_sample_y, n_feature_y) array-like, float
701 Target input matrix.
702 wx_samp : (n_sample_x, ) array-like, float, optional (default = None)
703 Histogram assigned on rows (samples) of matrix X.
704 Uniform distribution by default.
705 wx_feat : (n_feature_x, ) array-like, float, optional (default = None)
706 Histogram assigned on columns (features) of matrix X.
707 Uniform distribution by default.
708 wy_samp : (n_sample_y, ) array-like, float, optional (default = None)
709 Histogram assigned on rows (samples) of matrix Y.
710 Uniform distribution by default.
711 wy_feat : (n_feature_y, ) array-like, float, optional (default = None)
712 Histogram assigned on columns (features) of matrix Y.
713 Uniform distribution by default.
714 reg_marginals: float or indexable object of length 1 or 2
715 Marginal relaxation terms for sample and feature couplings.
716 If `reg_marginals` is a scalar or an indexable object of length 1,
717 then the same value is applied to both marginal relaxations.
718 epsilon : scalar or indexable object of length 2, float or int, optional (default = 0)
719 Regularization parameters for entropic approximation of sample and feature couplings.
720 Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
721 instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
722 both regularization of sample and feature couplings.
723 divergence : string, optional (default = "kl")
724
725 - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.
726
727 - If `divergence` = "l2", then Div is the half squared Euclidean norm.
728 unbalanced_solver : string, optional (default = "sinkhorn")
729 Solver for the unbalanced OT subroutine.
730
731 - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"
732
733 - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
734 alpha : scalar or indexable object of length 2, float or int, optional (default = 0)
735 Coeffficient parameter of linear terms with respect to the sample and feature couplings.
736 If alpha is scalar, then the same alpha is applied to both linear terms.
737 M_samp : (n_sample_x, n_sample_y), float, optional (default = None)
738 Sample matrix associated to the Wasserstein linear term on sample coupling.
739 M_feat : (n_feature_x, n_feature_y), float, optional (default = None)
740 Feature matrix associated to the Wasserstein linear term on feature coupling.
741 rescale_plan : boolean, optional (default = True)
742 If True, then rescale the transport plans in each BCD iteration,
743 so that they always have equal mass.
744 init_pi : tuple of two matrices of size (n_sample_x, n_sample_y) and
745 (n_feature_x, n_feature_y), optional (default = None).
746 Initialization of sample and feature couplings.
747 Uniform distributions by default.
748 init_duals : tuple of two tuples ((n_sample_x, ), (n_sample_y, )) and ((n_feature_x, ), (n_feature_y, )), optional (default = None).
749 Initialization of sample and feature dual vectors
750 if using Sinkhorn algorithm. Zero vectors by default.
751 max_iter : int, optional (default = 100)
752 Number of Block Coordinate Descent (BCD) iterations.
753 tol : float, optional (default = 1e-7)
754 Tolerance of BCD scheme. If the L1-norm between the current and previous
755 sample couplings is under this threshold, then stop BCD scheme.
756 max_iter_ot : int, optional (default = 100)
757 Number of iterations to solve each of the
758 two unbalanced optimal transport problems in each BCD iteration.
759 tol_ot : float, optional (default = 1e-7)
760 Tolerance of unbalanced solver for each of the
761 two unbalanced optimal transport problems in each BCD iteration.
762 log : bool, optional (default = False)
763 If True then the cost and four dual vectors, including
764 two from sample and two from feature couplings, are recorded.
765 verbose : bool, optional (default = False)
766 If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.
767
768 Returns
769 -------
770 ucoot : float
771 UCOOT cost.
772 log : dictionary, optional
773 Returned if `log` is True. The keys are:
774
775 error : array-like, float
776 list of L1 norms between the current and previous sample coupling.
777 duals_sample : (n_sample_x, n_sample_y)-tuple, float
778 Pair of dual vectors when solving OT problem w.r.t the sample coupling.
779 duals_feature : (n_feature_x, n_feature_y)-tuple, float
780 Pair of dual vectors when solving OT problem w.r.t the feature coupling.
781 linear : float
782 Linear part of UCOOT cost.
783 ucoot : float
784 UCOOT cost.
785 backend
786 The proper backend for all input arrays
787
788 References
789 ----------
790 .. [71] Tran, H., Janati, H., Courty, N., Flamary, R., Redko, I., Demetci, P., & Singh, R.
791 Unbalanced Co-Optimal Transport. AAAI Conference on Artificial Intelligence, 2023.
792 """
793
794 if divergence != "kl":
795 warnings.warn(
796 "The computation of gradients is only supported for KL divergence, not \
797 for {} divergence".format(divergence)
798 )
799
800 pi_samp, pi_feat, log_ucoot = unbalanced_co_optimal_transport(
801 X=X,
802 Y=Y,
803 wx_samp=wx_samp,
804 wx_feat=wx_feat,
805 wy_samp=wy_samp,
806 wy_feat=wy_feat,
807 reg_marginals=reg_marginals,
808 epsilon=epsilon,
809 divergence=divergence,
810 unbalanced_solver=unbalanced_solver,
811 alpha=alpha,
812 M_samp=M_samp,
813 M_feat=M_feat,
814 rescale_plan=rescale_plan,
815 init_pi=init_pi,
816 init_duals=init_duals,
817 max_iter=max_iter,
818 tol=tol,
819 max_iter_ot=max_iter_ot,
820 tol_ot=tol_ot,
821 log=True,
822 verbose=verbose,
823 **kwargs_solve,
824 )
825
826 nx = log_ucoot["backend"]
827
828 nx_samp, nx_feat = X.shape
829 ny_samp, ny_feat = Y.shape
830
831 # measures on rows and columns
832 if wx_samp is None:
833 wx_samp = nx.ones(nx_samp, type_as=X) / nx_samp
834 if wx_feat is None:
835 wx_feat = nx.ones(nx_feat, type_as=X) / nx_feat
836 if wy_samp is None:
837 wy_samp = nx.ones(ny_samp, type_as=Y) / ny_samp
838 if wy_feat is None:
839 wy_feat = nx.ones(ny_feat, type_as=Y) / ny_feat
840
841 # extract parameters
842 rho_x, rho_y = get_parameter_pair(reg_marginals)
843 eps_samp, eps_feat = get_parameter_pair(epsilon)
844
845 # calculate marginals
846 pi1_samp, pi2_samp = nx.sum(pi_samp, 1), nx.sum(pi_samp, 0)
847 pi1_feat, pi2_feat = nx.sum(pi_feat, 1), nx.sum(pi_feat, 0)
848 m_samp, m_feat = nx.sum(pi1_samp), nx.sum(pi1_feat)
849 m_wx_feat, m_wx_samp = nx.sum(wx_feat), nx.sum(wx_samp)
850 m_wy_feat, m_wy_samp = nx.sum(wy_feat), nx.sum(wy_samp)
851
852 # calculate subgradients
853 gradX = 2 * X * (pi1_samp[:, None] * pi1_feat[None, :]) - 2 * nx.dot(
854 nx.dot(pi_samp, Y), pi_feat.T
855 ) # shape (nx_samp, nx_feat)
856 gradY = 2 * Y * (pi2_samp[:, None] * pi2_feat[None, :]) - 2 * nx.dot(
857 nx.dot(pi_samp.T, X), pi_feat
858 ) # shape (ny_samp, ny_feat)
859
860 grad_wx_samp = rho_x * (m_wx_feat - m_feat * pi1_samp / wx_samp) + eps_samp * (
861 m_wy_samp - pi1_samp / wx_samp
862 )
863 grad_wx_feat = rho_x * (m_wx_samp - m_samp * pi1_feat / wx_feat) + eps_feat * (
864 m_wy_feat - pi1_feat / wx_feat
865 )
866 grad_wy_samp = rho_y * (m_wy_feat - m_feat * pi2_samp / wy_samp) + eps_samp * (
867 m_wx_samp - pi2_samp / wy_samp
868 )
869 grad_wy_feat = rho_y * (m_wy_samp - m_samp * pi2_feat / wy_feat) + eps_feat * (
870 m_wx_feat - pi2_feat / wy_feat
871 )
872
873 # set gradients
874 ucoot = log_ucoot["ucoot_cost"]
875 ucoot = nx.set_gradients(
876 ucoot,
877 (X, Y, wx_samp, wx_feat, wy_samp, wy_feat),
878 (gradX, gradY, grad_wx_samp, grad_wx_feat, grad_wy_samp, grad_wy_feat),
879 )
880
881 if log:
882 return ucoot, log_ucoot
883
884 else:
885 return ucoot
886
887
888 def fused_unbalanced_gromov_wasserstein(
889 Cx,
890 Cy,
891 wx=None,
892 wy=None,
893 reg_marginals=10,
894 epsilon=0,
895 divergence="kl",
896 unbalanced_solver="mm",
897 alpha=0,
898 M=None,
899 init_duals=None,
900 init_pi=None,
901 max_iter=100,
902 tol=1e-7,
903 max_iter_ot=500,
904 tol_ot=1e-7,
905 log=False,
906 verbose=False,
907 **kwargs_solve,
908 ):
909 r"""Compute the lower bound of the fused unbalanced Gromov-Wasserstein (FUGW) between two similarity matrices.
910 In practice, this lower bound is used interchangeably with the true FUGW.
911
912 More precisely, this function returns the transport plan between
913 :math:`(\mathbf{C^X}, \mathbf{w_X})` and :math:`(\mathbf{C^Y}, \mathbf{w_Y})`,
914 by solving the following problem using Block Coordinate Descent algorithm:
915
916 .. math::
917 \mathop{\arg \min}_{\substack{\mathbf{P}, \mathbf{Q}: \\ mass(P) = mass(Q)}}
918 &\quad \sum_{i,j,k,l} (\mathbf{C^X}_{i,k} - \mathbf{C^Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l}
919 + \frac{\alpha}{2} \sum_{i,j} (\mathbf{P}_{i,j} + \mathbf{Q}_{i,j}) \mathbf{M}_{i, j} \\
920 &+ \rho_1 \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w_X} \mathbf{w_X}^T)
921 + \rho_2 \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w_Y} \mathbf{w_Y}^T) \\
922 &+ \varepsilon \mathbf{Div}(\mathbf{P} \otimes \mathbf{Q} | (\mathbf{w_X} \mathbf{w_Y}^T) \otimes (\mathbf{w_X} \mathbf{w_Y}^T))
923
924 Where:
925
926 - :math:`\mathbf{C^X}`: Source similarity matrix
927 - :math:`\mathbf{C^Y}`: Target similarity matrix
928 - :math:`\mathbf{M}`: Sample matrix corresponding to the Wasserstein term
929 - :math:`\mathbf{w_X}`: Distribution of the samples in the source space
930 - :math:`\mathbf{w_Y}`: Distribution of the samples in the target space
931 - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.
932
933 .. note:: This function allows epsilon to be zero. In that case, `unbalanced_method` must be either "mm" or "lbfgsb".
934
935 Parameters
936 ----------
937 Cx : (n_sample_x, n_feature_x) array-like, float
938 Source similarity matrix.
939 Cy : (n_sample_y, n_feature_y) array-like, float
940 Target similarity matrix.
941 wx : (n_sample_x, ) array-like, float, optional (default = None)
942 Histogram assigned on rows (samples) of matrix Cx.
943 Uniform distribution by default.
944 wy : (n_sample_y, ) array-like, float, optional (default = None)
945 Histogram assigned on rows (samples) of matrix Cy.
946 Uniform distribution by default.
947 reg_marginals: float or indexable object of length 1 or 2
948 Marginal relaxation terms for sample and feature couplings.
949 If `reg_marginals` is a scalar or an indexable object of length 1,
950 then the same value is applied to both marginal relaxations.
951 epsilon : scalar, float or int, optional (default = 0)
952 Regularization parameters for entropic approximation of sample and feature couplings.
953 Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
954 instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
955 both regularization of sample and feature couplings.
956 divergence : string, optional (default = "kl")
957
958 - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.
959
960 - If `divergence` = "l2", then Div is the half squared Euclidean norm.
961 unbalanced_solver : string, optional (default = "sinkhorn")
962 Solver for the unbalanced OT subroutine.
963
964 - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"
965
966 - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
967 alpha : scalar, float or int, optional (default = 0)
968 Coeffficient parameter of linear terms with respect to the sample and feature couplings.
969 If alpha is scalar, then the same alpha is applied to both linear terms.
970 M : (n_sample_x, n_sample_y), float, optional (default = None)
971 Sample matrix associated to the Wasserstein linear term on sample coupling.
972 init_pi :(n_sample_x, n_sample_y) array-like, optional (default = None)
973 Initialization of sample coupling. By default = :math:`w_X w_Y^T`.
974 init_duals : tuple of vectors ((n_sample_x, ), (n_sample_y, )), optional (default = None).
975 Initialization of sample and feature dual vectors
976 if using Sinkhorn algorithm. Zero vectors by default.
977 max_iter : int, optional (default = 100)
978 Number of Block Coordinate Descent (BCD) iterations.
979 tol : float, optional (default = 1e-7)
980 Tolerance of BCD scheme. If the L1-norm between the current and previous
981 sample couplings is under this threshold, then stop BCD scheme.
982 max_iter_ot : int, optional (default = 100)
983 Number of iterations to solve each of the
984 two unbalanced optimal transport problems in each BCD iteration.
985 tol_ot : float, optional (default = 1e-7)
986 Tolerance of unbalanced solver for each of the
987 two unbalanced optimal transport problems in each BCD iteration.
988 log : bool, optional (default = False)
989 If True then the cost and four dual vectors, including
990 two from sample and two from feature couplings, are recorded.
991 verbose : bool, optional (default = False)
992 If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.
993
994 Returns
995 -------
996 pi_samp : (n_sample_x, n_sample_y) array-like, float
997 Sample coupling matrix.
998 In practice, we use this matrix as solution of FUGW.
999 pi_samp2 : (n_sample_x, n_sample_y) array-like, float
1000 Second sample coupling matrix.
1001 In practice, we usually ignore this output.
1002 log : dictionary, optional
1003 Returned if `log` is True. The keys are:
1004
1005 error : array-like, float
1006 list of L1 norms between the current and previous sample couplings.
1007 duals : (n_sample_x, n_sample_y)-tuple, float
1008 Pair of dual vectors when solving OT problem w.r.t the sample coupling.
1009 linear : float
1010 Linear part of FUGW cost.
1011 fugw_cost : float
1012 Total FUGW cost.
1013 backend
1014 The proper backend for all input arrays
1015
1016 References
1017 ----------
1018 .. [70] Thual, A., Tran, H., Zemskova, T., Courty, N., Flamary, R., Dehaene, S., & Thirion, B.
1019 Aligning individual brains with Fused Unbalanced Gromov-Wasserstein.
1020 Advances in Neural Information Systems, 35 (2022).
1021
1022 .. [72] Thibault Séjourné, François-Xavier Vialard, & Gabriel Peyré.
1023 The Unbalanced Gromov Wasserstein Distance: Conic Formulation and Relaxation.
1024 Neural Information Processing Systems, 34 (2021).
1025 """
1026
1027 alpha = (alpha / 2, alpha / 2)
1028
1029 pi_samp, pi_feat, dict_log = fused_unbalanced_across_spaces_divergence(
1030 X=Cx,
1031 Y=Cy,
1032 wx_samp=wx,
1033 wx_feat=wx,
1034 wy_samp=wy,
1035 wy_feat=wy,
1036 reg_marginals=reg_marginals,
1037 epsilon=epsilon,
1038 reg_type="joint",
1039 divergence=divergence,
1040 unbalanced_solver=unbalanced_solver,
1041 alpha=alpha,
1042 M_samp=M,
1043 M_feat=M,
1044 rescale_plan=True,
1045 init_pi=(init_pi, init_pi),
1046 init_duals=(init_duals, init_duals),
1047 max_iter=max_iter,
1048 tol=tol,
1049 max_iter_ot=max_iter_ot,
1050 tol_ot=tol_ot,
1051 log=True,
1052 verbose=verbose,
1053 **kwargs_solve,
1054 )
1055
1056 if log:
1057 log_fugw = {
1058 "error": dict_log["error"],
1059 "duals": dict_log["duals_sample"],
1060 "linear_cost": dict_log["linear_cost"],
1061 "fugw_cost": dict_log["ucoot_cost"],
1062 "backend": dict_log["backend"],
1063 }
1064
1065 return pi_samp, pi_feat, log_fugw
1066
1067 else:
1068 return pi_samp, pi_feat
1069
1070
1071 def fused_unbalanced_gromov_wasserstein2(
1072 Cx,
1073 Cy,
1074 wx=None,
1075 wy=None,
1076 reg_marginals=10,
1077 epsilon=0,
1078 divergence="kl",
1079 unbalanced_solver="mm",
1080 alpha=0,
1081 M=None,
1082 init_duals=None,
1083 init_pi=None,
1084 max_iter=100,
1085 tol=1e-7,
1086 max_iter_ot=500,
1087 tol_ot=1e-7,
1088 log=False,
1089 verbose=False,
1090 **kwargs_solve,
1091 ):
1092 r"""Compute the lower bound of the fused unbalanced Gromov-Wasserstein (FUGW) between two similarity matrices.
1093 In practice, this lower bound is used interchangeably with the true FUGW.
1094
1095 More precisely, this function returns the lower bound of the fused unbalanced Gromov-Wasserstein cost between
1096 :math:`(\mathbf{C^X}, \mathbf{w_X})` and :math:`(\mathbf{C^Y}, \mathbf{w_Y})`,
1097 by solving the following problem using Block Coordinate Descent algorithm:
1098
1099 .. math::
1100 \mathop{\min}_{\substack{\mathbf{P}, \mathbf{Q}: \\ mass(P) = mass(Q)}}
1101 &\quad \sum_{i,j,k,l} (\mathbf{C^X}_{i,k} - \mathbf{C^Y}_{j,l})^2 \mathbf{P}_{i,j} \mathbf{Q}_{k,l}
1102 + \frac{\alpha}{2} \sum_{i,j} (\mathbf{P}_{i,j} + \mathbf{Q}_{i,j}) \mathbf{M}_{i, j} \\
1103 &+ \rho_1 \mathbf{Div}(\mathbf{P}_{\# 1} \mathbf{Q}_{\# 1}^T | \mathbf{w_X} \mathbf{w_X}^T)
1104 + \rho_2 \mathbf{Div}(\mathbf{P}_{\# 2} \mathbf{Q}_{\# 2}^T | \mathbf{w_Y} \mathbf{w_Y}^T) \\
1105 &+ \varepsilon \mathbf{Div}(\mathbf{P} \otimes \mathbf{Q} | (\mathbf{w_X} \mathbf{w_Y}^T) \otimes (\mathbf{w_X} \mathbf{w_Y}^T))
1106
1107 Where:
1108
1109 - :math:`\mathbf{C^X}`: Source similarity matrix
1110 - :math:`\mathbf{C^Y}`: Target similarity matrix
1111 - :math:`\mathbf{M}`: Sample matrix corresponding to the Wasserstein term
1112 - :math:`\mathbf{w_X}`: Distribution of the samples in the source space
1113 - :math:`\mathbf{w_Y}`: Distribution of the samples in the target space
1114 - :math:`\mathbf{Div}`: Either Kullback-Leibler divergence or half-squared L2 norm.
1115
1116 .. note:: This function allows `epsilon` to be zero. In that case, unbalanced_method must be either "mm" or "lbfgsb".
1117 Also the computation of gradients is only supported for KL divergence, but not for half squared-L2 norm. In case of half squared-L2 norm, the calculation of KL divergence will be used.
1118
1119 Parameters
1120 ----------
1121 Cx : (n_sample_x, n_feature_x) array-like, float
1122 Source similarity matrix.
1123 Cy : (n_sample_y, n_feature_y) array-like, float
1124 Target similarity matrix.
1125 wx : (n_sample_x, ) array-like, float, optional (default = None)
1126 Histogram assigned on rows (samples) of matrix Cx.
1127 Uniform distribution by default.
1128 wy : (n_sample_y, ) array-like, float, optional (default = None)
1129 Histogram assigned on rows (samples) of matrix Cy.
1130 Uniform distribution by default.
1131 reg_marginals: float or indexable object of length 1 or 2
1132 Marginal relaxation terms for sample and feature couplings.
1133 If `reg_marginals` is a scalar or an indexable object of length 1,
1134 then the same value is applied to both marginal relaxations.
1135 epsilon : scalar, float or int, optional (default = 0)
1136 Regularization parameters for entropic approximation of sample and feature couplings.
1137 Allow the case where `epsilon` contains 0. In that case, the MM solver is used by default
1138 instead of Sinkhorn solver. If `epsilon` is scalar, then the same value is applied to
1139 both regularization of sample and feature couplings.
1140 divergence : string, optional (default = "kl")
1141
1142 - If `divergence` = "kl", then Div is the Kullback-Leibler divergence.
1143
1144 - If `divergence` = "l2", then Div is the half squared Euclidean norm.
1145 unbalanced_solver : string, optional (default = "sinkhorn")
1146 Solver for the unbalanced OT subroutine.
1147
1148 - If `divergence` = "kl", then `unbalanced_solver` can be: "sinkhorn", "sinkhorn_log", "mm", "lbfgsb"
1149
1150 - If `divergence` = "l2", then `unbalanced_solver` can be "mm", "lbfgsb"
1151 alpha : scalar, float or int, optional (default = 0)
1152 Coeffficient parameter of linear terms with respect to the sample and feature couplings.
1153 If alpha is scalar, then the same alpha is applied to both linear terms.
1154 M : (n_sample_x, n_sample_y), float, optional (default = None)
1155 Sample matrix associated to the Wasserstein linear term on sample coupling.
1156 init_pi :(n_sample_x, n_sample_y) array-like, optional (default = None)
1157 Initialization of sample coupling. By default = :math:`w_X w_Y^T`.
1158 init_duals : tuple of vectors ((n_sample_x, ), (n_sample_y, )), optional (default = None).
1159 Initialization of sample and feature dual vectors
1160 if using Sinkhorn algorithm. Zero vectors by default.
1161 max_iter : int, optional (default = 100)
1162 Number of Block Coordinate Descent (BCD) iterations.
1163 tol : float, optional (default = 1e-7)
1164 Tolerance of BCD scheme. If the L1-norm between the current and previous
1165 sample couplings is under this threshold, then stop BCD scheme.
1166 max_iter_ot : int, optional (default = 100)
1167 Number of iterations to solve each of the
1168 two unbalanced optimal transport problems in each BCD iteration.
1169 tol_ot : float, optional (default = 1e-7)
1170 Tolerance of unbalanced solver for each of the
1171 two unbalanced optimal transport problems in each BCD iteration.
1172 log : bool, optional (default = False)
1173 If True then the cost and four dual vectors, including
1174 two from sample and two from feature couplings, are recorded.
1175 verbose : bool, optional (default = False)
1176 If True then print the COOT cost at every multiplier of `eval_bcd`-th iteration.
1177
1178 Returns
1179 -------
1180 fugw : float
1181 Total FUGW cost
1182 log : dictionary, optional
1183 Returned if `log` is True. The keys are:
1184
1185 error : array-like, float
1186 list of L1 norms between the current and previous sample couplings.
1187 duals : (n_sample_x, n_sample_y)-tuple, float
1188 Pair of dual vectors when solving OT problem w.r.t the sample coupling.
1189 linear : float
1190 Linear part of FUGW cost.
1191 fugw_cost : float
1192 Total FUGW cost.
1193 backend
1194 The proper backend for all input arrays
1195
1196 References
1197 ----------
1198 .. [70] Thual, A., Tran, H., Zemskova, T., Courty, N., Flamary, R., Dehaene, S., & Thirion, B.
1199 Aligning individual brains with Fused Unbalanced Gromov-Wasserstein.
1200 Advances in Neural Information Systems, 35 (2022).
1201
1202 .. [72] Thibault Séjourné, François-Xavier Vialard, & Gabriel Peyré.
1203 The Unbalanced Gromov Wasserstein Distance: Conic Formulation and Relaxation.
1204 Neural Information Processing Systems, 34 (2021).
1205 """
1206
1207 if divergence != "kl":
1208 warnings.warn(
1209 "The computation of gradients is only supported for KL divergence, \
1210 but not for {} divergence. The gradient of the KL case will be used.".format(
1211 divergence
1212 )
1213 )
1214
1215 pi_samp, pi_feat, log_fugw = fused_unbalanced_gromov_wasserstein(
1216 Cx=Cx,
1217 Cy=Cy,
1218 wx=wx,
1219 wy=wy,
1220 reg_marginals=reg_marginals,
1221 epsilon=epsilon,
1222 divergence=divergence,
1223 unbalanced_solver=unbalanced_solver,
1224 alpha=alpha,
1225 M=M,
1226 init_duals=init_duals,
1227 init_pi=init_pi,
1228 max_iter=max_iter,
1229 tol=tol,
1230 max_iter_ot=max_iter_ot,
1231 tol_ot=tol_ot,
1232 log=True,
1233 verbose=verbose,
1234 **kwargs_solve,
1235 )
1236
1237 nx = log_fugw["backend"]
1238 sx, sy = Cx.shape[0], Cy.shape[0]
1239
1240 # measures on rows and columns
1241 if wx is None:
1242 wx = nx.ones(sx, type_as=Cx) / sx
1243 if wy is None:
1244 wy = nx.ones(sy, type_as=Cy) / sy
1245
1246 # calculate marginals
1247 pi1_samp, pi2_samp = nx.sum(pi_samp, 1), nx.sum(pi_samp, 0)
1248 pi1_feat, pi2_feat = nx.sum(pi_feat, 1), nx.sum(pi_feat, 0)
1249 m_samp, m_feat = nx.sum(pi1_samp), nx.sum(pi1_feat)
1250 m_wx, m_wy = nx.sum(wx), nx.sum(wy)
1251
1252 # calculate subgradients
1253 gradX = 2 * Cx * (pi1_samp[:, None] * pi1_feat[None, :]) - 2 * nx.dot(
1254 nx.dot(pi_samp, Cy), pi_feat.T
1255 ) # shape (nx_samp, nx_feat)
1256 gradY = 2 * Cy * (pi2_samp[:, None] * pi2_feat[None, :]) - 2 * nx.dot(
1257 nx.dot(pi_samp.T, Cx), pi_feat
1258 ) # shape (ny_samp, ny_feat)
1259
1260 gradM = alpha / 2 * (pi_samp + pi_feat)
1261
1262 rho_x, rho_y = get_parameter_pair(reg_marginals)
1263 grad_wx = (
1264 2 * m_wx * (rho_x + epsilon * m_wy**2)
1265 - (rho_x + epsilon) * (m_feat * pi1_samp + m_samp * pi1_feat) / wx
1266 )
1267 grad_wy = (
1268 2 * m_wy * (rho_y + epsilon * m_wx**2)
1269 - (rho_y + epsilon) * (m_feat * pi2_samp + m_samp * pi2_feat) / wy
1270 )
1271
1272 # set gradients
1273 fugw = log_fugw["fugw_cost"]
1274 fugw = nx.set_gradients(
1275 fugw, (Cx, Cy, M, wx, wy), (gradX, gradY, gradM, grad_wx, grad_wy)
1276 )
1277
1278 if log:
1279 return fugw, log_fugw
1280
1281 else:
1282 return fugw