Debian Codegraph @

ot/gromov/_utils.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Gromov-Wasserstein and Fused-Gromov-Wasserstein utils.
4 """
5
6 # Author: Erwan Vautier <[email protected]>
7 # Nicolas Courty <[email protected]>
8 # Rémi Flamary <[email protected]>
9 # Titouan Vayer <[email protected]>
10 # Cédric Vincent-Cuaz <[email protected]>
11 # Quang Huy Tran <[email protected]>
12 #
13 # License: MIT License
14
15 from ..utils import list_to_array, euclidean_distances
16 from ..backend import get_backend
17 from ..lp import emd
18
19 try:
20 from networkx.algorithms.community import asyn_fluidc
21 from networkx import from_numpy_array
22
23 networkx_import = True
24 except ImportError:
25 networkx_import = False
26
27 try:
28 from sklearn.cluster import SpectralClustering, KMeans
29
30 sklearn_import = True
31 except ImportError:
32 sklearn_import = False
33
34 import numpy as np
35 import warnings
36
37
38 def _transform_matrix(C1, C2, loss_fun="square_loss", nx=None):
39 r"""Return transformed structure matrices for Gromov-Wasserstein fast computation
40
41 Returns the matrices involved in the computation of :math:`\mathcal{L}(\mathbf{C_1}, \mathbf{C_2})`
42 with the selected loss function as the loss function of Gromov-Wasserstein discrepancy.
43
44 The matrices are computed as described in Proposition 1 in :ref:`[12] <references-init-matrix>`
45
46 Where :
47
48 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
49 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
50
51 The square-loss function :math:`L(a, b) = |a - b|^2` is read as :
52
53 .. math::
54
55 L(a, b) = f_1(a) + f_2(b) - h_1(a) h_2(b)
56
57 \mathrm{with} \ f_1(a) &= a^2
58
59 f_2(b) &= b^2
60
61 h_1(a) &= a
62
63 h_2(b) &= 2b
64
65 The kl-loss function :math:`L(a, b) = a \log\left(\frac{a}{b}\right) - a + b` is read as :
66
67 .. math::
68
69 L(a, b) = f_1(a) + f_2(b) - h_1(a) h_2(b)
70
71 \mathrm{with} \ f_1(a) &= a \log(a) - a
72
73 f_2(b) &= b
74
75 h_1(a) &= a
76
77 h_2(b) &= \log(b)
78
79 Parameters
80 ----------
81 C1 : array-like, shape (ns, ns)
82 Metric cost matrix in the source space
83 C2 : array-like, shape (nt, nt)
84 Metric cost matrix in the target space
85 loss_fun : str, optional
86 Name of loss function to use: either 'square_loss' or 'kl_loss' (default='square_loss')
87 nx : backend, optional
88 If let to its default value None, a backend test will be conducted.
89
90 Returns
91 -------
92 fC1 : array-like, shape (ns, ns)
93 :math:`\mathbf{f1}(\mathbf{C1})` matrix in Eq. (6)
94 fC2 : array-like, shape (nt, nt)
95 :math:`\mathbf{f2}(\mathbf{C2})` matrix in Eq. (6)
96 hC1 : array-like, shape (ns, ns)
97 :math:`\mathbf{h1}(\mathbf{C1})` matrix in Eq. (6)
98 hC2 : array-like, shape (nt, nt)
99 :math:`\mathbf{h2}(\mathbf{C2})` matrix in Eq. (6)
100
101
102 .. _references-transform_matrix:
103 References
104 ----------
105 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon,
106 "Gromov-Wasserstein averaging of kernel and distance matrices."
107 International Conference on Machine Learning (ICML). 2016.
108
109 """
110 if nx is None:
111 C1, C2 = list_to_array(C1, C2)
112 nx = get_backend(C1, C2)
113
114 if loss_fun == "square_loss":
115
116 def f1(a):
117 return a**2
118
119 def f2(b):
120 return b**2
121
122 def h1(a):
123 return a
124
125 def h2(b):
126 return 2 * b
127 elif loss_fun == "kl_loss":
128
129 def f1(a):
130 return a * nx.log(a + 1e-18) - a
131
132 def f2(b):
133 return b
134
135 def h1(a):
136 return a
137
138 def h2(b):
139 return nx.log(b + 1e-18)
140 else:
141 raise ValueError(
142 f"Unknown `loss_fun='{loss_fun}'`. Use one of: {'square_loss', 'kl_loss'}."
143 )
144
145 fC1 = f1(C1)
146 fC2 = f2(C2)
147 hC1 = h1(C1)
148 hC2 = h2(C2)
149
150 return fC1, fC2, hC1, hC2
151
152
153 def init_matrix(C1, C2, p, q, loss_fun="square_loss", nx=None):
154 r"""Return loss matrices and tensors for Gromov-Wasserstein fast computation
155
156 Returns the value of :math:`\mathcal{L}(\mathbf{C_1}, \mathbf{C_2}) \otimes \mathbf{T}` with the
157 selected loss function as the loss function of Gromov-Wasserstein discrepancy.
158
159 The matrices are computed as described in Proposition 1 in :ref:`[12] <references-init-matrix>`
160
161 Where :
162
163 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
164 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
165 - :math:`\mathbf{T}`: A coupling between those two spaces
166
167 The square-loss function :math:`L(a, b) = |a - b|^2` is read as :
168
169 .. math::
170
171 L(a, b) = f_1(a) + f_2(b) - h_1(a) h_2(b)
172
173 \mathrm{with} \ f_1(a) &= a^2
174
175 f_2(b) &= b^2
176
177 h_1(a) &= a
178
179 h_2(b) &= 2b
180
181 The kl-loss function :math:`L(a, b) = a \log\left(\frac{a}{b}\right) - a + b` is read as :
182
183 .. math::
184
185 L(a, b) = f_1(a) + f_2(b) - h_1(a) h_2(b)
186
187 \mathrm{with} \ f_1(a) &= a \log(a) - a
188
189 f_2(b) &= b
190
191 h_1(a) &= a
192
193 h_2(b) &= \log(b)
194
195 Parameters
196 ----------
197 C1 : array-like, shape (ns, ns)
198 Metric cost matrix in the source space
199 C2 : array-like, shape (nt, nt)
200 Metric cost matrix in the target space
201 p : array-like, shape (ns,)
202 Probability distribution in the source space
203 q : array-like, shape (nt,)
204 Probability distribution in the target space
205 loss_fun : str, optional
206 Name of loss function to use: either 'square_loss' or 'kl_loss' (default='square_loss')
207 nx : backend, optional
208 If let to its default value None, a backend test will be conducted.
209
210 Returns
211 -------
212 constC : array-like, shape (ns, nt)
213 Constant :math:`\mathbf{C}` matrix in Eq. (6)
214 hC1 : array-like, shape (ns, ns)
215 :math:`\mathbf{h1}(\mathbf{C1})` matrix in Eq. (6)
216 hC2 : array-like, shape (nt, nt)
217 :math:`\mathbf{h2}(\mathbf{C2})` matrix in Eq. (6)
218
219
220 .. _references-init-matrix:
221 References
222 ----------
223 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon,
224 "Gromov-Wasserstein averaging of kernel and distance matrices."
225 International Conference on Machine Learning (ICML). 2016.
226
227 """
228 if nx is None:
229 C1, C2, p, q = list_to_array(C1, C2, p, q)
230 nx = get_backend(C1, C2, p, q)
231
232 fC1, fC2, hC1, hC2 = _transform_matrix(C1, C2, loss_fun, nx)
233 constC1 = nx.dot(
234 nx.dot(fC1, nx.reshape(p, (-1, 1))), nx.ones((1, len(q)), type_as=q)
235 )
236 constC2 = nx.dot(
237 nx.ones((len(p), 1), type_as=p), nx.dot(nx.reshape(q, (1, -1)), fC2.T)
238 )
239 constC = constC1 + constC2
240
241 return constC, hC1, hC2
242
243
244 def tensor_product(constC, hC1, hC2, T, nx=None):
245 r"""Return the tensor for Gromov-Wasserstein fast computation
246
247 The tensor is computed as described in Proposition 1 Eq. (6) in :ref:`[12] <references-tensor-product>`
248
249 Parameters
250 ----------
251 constC : array-like, shape (ns, nt)
252 Constant :math:`\mathbf{C}` matrix in Eq. (6)
253 hC1 : array-like, shape (ns, ns)
254 :math:`\mathbf{h1}(\mathbf{C1})` matrix in Eq. (6)
255 hC2 : array-like, shape (nt, nt)
256 :math:`\mathbf{h2}(\mathbf{C2})` matrix in Eq. (6)
257 nx : backend, optional
258 If let to its default value None, a backend test will be conducted.
259 Returns
260 -------
261 tens : array-like, shape (`ns`, `nt`)
262 :math:`\mathcal{L}(\mathbf{C_1}, \mathbf{C_2}) \otimes \mathbf{T}` tensor-matrix multiplication result
263
264
265 .. _references-tensor-product:
266 References
267 ----------
268 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon,
269 "Gromov-Wasserstein averaging of kernel and distance matrices."
270 International Conference on Machine Learning (ICML). 2016.
271
272 """
273 if nx is None:
274 constC, hC1, hC2, T = list_to_array(constC, hC1, hC2, T)
275 nx = get_backend(constC, hC1, hC2, T)
276
277 A = -nx.dot(nx.dot(hC1, T), hC2.T)
278 tens = constC + A
279 # tens -= tens.min()
280 return tens
281
282
283 def gwloss(constC, hC1, hC2, T, nx=None):
284 r"""Return the Loss for Gromov-Wasserstein
285
286 The loss is computed as described in Proposition 1 Eq. (6) in :ref:`[12] <references-gwloss>`
287
288 Parameters
289 ----------
290 constC : array-like, shape (ns, nt)
291 Constant :math:`\mathbf{C}` matrix in Eq. (6)
292 hC1 : array-like, shape (ns, ns)
293 :math:`\mathbf{h1}(\mathbf{C1})` matrix in Eq. (6)
294 hC2 : array-like, shape (nt, nt)
295 :math:`\mathbf{h2}(\mathbf{C2})` matrix in Eq. (6)
296 T : array-like, shape (ns, nt)
297 Current value of transport matrix :math:`\mathbf{T}`
298 nx : backend, optional
299 If let to its default value None, a backend test will be conducted.
300 Returns
301 -------
302 loss : float
303 Gromov-Wasserstein loss
304
305
306 .. _references-gwloss:
307 References
308 ----------
309 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon,
310 "Gromov-Wasserstein averaging of kernel and distance matrices."
311 International Conference on Machine Learning (ICML). 2016.
312
313 """
314
315 tens = tensor_product(constC, hC1, hC2, T, nx)
316 if nx is None:
317 tens, T = list_to_array(tens, T)
318 nx = get_backend(tens, T)
319
320 return nx.sum(tens * T)
321
322
323 def gwggrad(constC, hC1, hC2, T, nx=None):
324 r"""Return the gradient for Gromov-Wasserstein
325
326 The gradient is computed as described in Proposition 2 in :ref:`[12] <references-gwggrad>`
327
328 Parameters
329 ----------
330 constC : array-like, shape (ns, nt)
331 Constant :math:`\mathbf{C}` matrix in Eq. (6)
332 hC1 : array-like, shape (ns, ns)
333 :math:`\mathbf{h1}(\mathbf{C1})` matrix in Eq. (6)
334 hC2 : array-like, shape (nt, nt)
335 :math:`\mathbf{h2}(\mathbf{C2})` matrix in Eq. (6)
336 T : array-like, shape (ns, nt)
337 Current value of transport matrix :math:`\mathbf{T}`
338 nx : backend, optional
339 If let to its default value None, a backend test will be conducted.
340 Returns
341 -------
342 grad : array-like, shape (`ns`, `nt`)
343 Gromov-Wasserstein gradient
344
345
346 .. _references-gwggrad:
347 References
348 ----------
349 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon,
350 "Gromov-Wasserstein averaging of kernel and distance matrices."
351 International Conference on Machine Learning (ICML). 2016.
352
353 """
354 return 2 * tensor_product(constC, hC1, hC2, T, nx) # [12] Prop. 2 misses a 2 factor
355
356
357 def init_matrix_semirelaxed(C1, C2, p, loss_fun="square_loss", nx=None):
358 r"""Return loss matrices and tensors for semi-relaxed Gromov-Wasserstein fast computation
359
360 Returns the value of :math:`\mathcal{L}(\mathbf{C_1}, \mathbf{C_2}) \otimes \mathbf{T}` with the
361 selected loss function as the loss function of semi-relaxed Gromov-Wasserstein discrepancy.
362
363 The matrices are computed as described in Proposition 1 in :ref:`[12] <references-init-matrix>`
364 and adapted to the semi-relaxed problem where the second marginal is not a constant anymore.
365
366 Where :
367
368 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
369 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
370 - :math:`\mathbf{T}`: A coupling between those two spaces
371
372 The square-loss function :math:`L(a, b) = |a - b|^2` is read as :
373
374 .. math::
375
376 L(a, b) = f_1(a) + f_2(b) - h_1(a) h_2(b)
377
378 \mathrm{with} \ f_1(a) &= a^2
379
380 f_2(b) &= b^2
381
382 h_1(a) &= a
383
384 h_2(b) &= 2b
385
386 The kl-loss function :math:`L(a, b) = a \log\left(\frac{a}{b}\right) - a + b` is read as :
387
388 .. math::
389
390 L(a, b) = f_1(a) + f_2(b) - h_1(a) h_2(b)
391
392 \mathrm{with} \ f_1(a) &= a \log(a) - a
393
394 f_2(b) &= b
395
396 h_1(a) &= a
397
398 h_2(b) &= \log(b)
399 Parameters
400 ----------
401 C1 : array-like, shape (ns, ns)
402 Metric cost matrix in the source space
403 C2 : array-like, shape (nt, nt)
404 Metric cost matrix in the target space
405 p : array-like, shape (ns,)
406 Probability distribution in the source space
407 loss_fun : str, optional
408 Name of loss function to use: either 'square_loss' or 'kl_loss' (default='square_loss')
409 nx : backend, optional
410 If let to its default value None, a backend test will be conducted.
411
412 Returns
413 -------
414 constC : array-like, shape (ns, nt)
415 Constant :math:`\mathbf{C}` matrix in Eq. (6) adapted to srGW
416 hC1 : array-like, shape (ns, ns)
417 :math:`\mathbf{h1}(\mathbf{C1})` matrix in Eq. (6)
418 hC2 : array-like, shape (nt, nt)
419 :math:`\mathbf{h2}(\mathbf{C2})` matrix in Eq. (6)
420 fC2t: array-like, shape (nt, nt)
421 :math:`\mathbf{f2}(\mathbf{C2})^\top` matrix in Eq. (6)
422
423
424 .. _references-init-matrix:
425 References
426 ----------
427 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon,
428 "Gromov-Wasserstein averaging of kernel and distance matrices."
429 International Conference on Machine Learning (ICML). 2016.
430
431 .. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty.
432 "Semi-relaxed Gromov-Wasserstein divergence and applications on graphs"
433 International Conference on Learning Representations (ICLR), 2022.
434 """
435 if nx is None:
436 C1, C2, p = list_to_array(C1, C2, p)
437 nx = get_backend(C1, C2, p)
438
439 fC1, fC2, hC1, hC2 = _transform_matrix(C1, C2, loss_fun, nx)
440
441 constC = nx.dot(
442 nx.dot(fC1, nx.reshape(p, (-1, 1))), nx.ones((1, C2.shape[0]), type_as=p)
443 )
444
445 fC2t = fC2.T
446 return constC, hC1, hC2, fC2t
447
448
449 def semirelaxed_init_plan(
450 C1,
451 C2,
452 p,
453 M=None,
454 alpha=1.0,
455 method="product",
456 use_target=True,
457 random_state=0,
458 nx=None,
459 ):
460 r"""
461 Heuristics to initialize the semi-relaxed (F)GW transport plan
462 :math:`\mathbf{T} \in \mathcal{U}_{nt}(\mathbf{p})`, between a graph
463 :math:`(\mathbf{C1}, \mathbf{p})` and a structure matrix :math:`\mathbf{C2}`,
464 where :math:`\mathcal{U}_{nt}(\mathbf{p}) = \{\mathbf{T} \in \mathbb{R}_{+}^{ns * nt}, \mathbf{T} \mathbf{1}_{nt} = \mathbf{p} \}`.
465 Available methods are:
466 - "product" or "random_product": :math:`\mathbf{T} = \mathbf{pq}^{T}`
467 with :math:`\mathbf{q}` uniform or randomly samples in the nt probability simplex.
468
469 - "random": random sampling in :math:`\mathcal{U}_{nt}(\mathbf{p})`.
470
471 - "fluid": Fluid algorithm from networkx for graph partitioning.
472
473 - "spectral", "kmeans" : Spectral or Kmeans clustering from sklearn.
474
475 - "fluid_soft", "spectral_soft", "kmeans_soft": :math:`\mathbf{T}_0` given
476 by corresponding clustering with target marginal :math:`\mathbf{q}_0`, further
477 centered as :math:`\mathbf{T} = (\mathbf{T}_0 + \mathbf{pq}_0^T) / 2` .
478
479 If a metric cost matrix between features across domains :math:`\mathbf{M}`
480 is a provided, it will be used as cost matrix in a semi-relaxed Wasserstein
481 problem providing :math:`\mathbf{T}_M \in \mathcal{U}_{nt}(\mathbf{p})`. Then
482 the outputted transport plan is :math:`\alpha \mathbf{T} + (1 - \alpha ) \mathbf{T}_{M}`.
483
484 Parameters
485 ----------
486 C1 : array-like, shape (ns, ns)
487 Metric cost matrix in the source space.
488 C2 : array-like, shape (nt, nt)
489 Metric cost matrix in the target space.
490 p : array-like, shape (ns,), optional.
491 Probability distribution in the source space. If let to None, uniform
492 weights are assumed on C1.
493 M : array-like, shape (ns, nt), optional.
494 Metric cost matrix between features across domains.
495 alpha : float, optional
496 Trade-off parameter (0 <= alpha <= 1)
497 method : str, optional
498 Method to initialize the transport plan. The default is 'product'.
499 use_target : bool, optional.
500 Whether or not to use the target structure/features to further align
501 transport plan provided by the `method`.
502 random_state: int, optional
503 Random seed used for stochastic methods.
504 nx : backend, optional
505 POT backend.
506
507 Returns
508 -------
509 T : array-like, shape (ns, ns)
510 Admissible transport plan for the sr(F)GW problems.
511
512 References
513 ----------
514 .. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty.
515 "Semi-relaxed Gromov-Wasserstein divergence and applications on graphs"
516 International Conference on Learning Representations (ICLR), 2022.
517
518 """
519 list_partitioning_methods = [
520 "fluid",
521 "spectral",
522 "kmeans",
523 "fluid_soft",
524 "spectral_soft",
525 "kmeans_soft",
526 ]
527
528 if method not in list_partitioning_methods + [
529 "product",
530 "random_product",
531 "random",
532 ]:
533 raise ValueError(f"Unsupported initialization method = {method}.")
534
535 if (method in ["kmeans", "kmeans_soft"]) and (not sklearn_import):
536 raise ValueError(f"Scikit-learn must be installed to use method = {method}")
537
538 if (method in ["fluid", "fluid_soft"]) and (not networkx_import):
539 raise ValueError(f"Networkx must be installed to use method = {method}")
540
541 if nx is None:
542 nx = get_backend(C1, C2, p, M)
543
544 n = C1.shape[0]
545 m = C2.shape[0]
546 min_size = min(n, m)
547
548 if method in list_partitioning_methods:
549 if n > m: # partition C1 to deduce map from C1 to C2
550 C_to_partition = nx.to_numpy(C1)
551 elif m > n: # partition C2 to deduce map from C1 to C2
552 C_to_partition = nx.to_numpy(C2)
553 else: # equal size -> simple Wasserstein alignment
554 C_to_partition = None
555 warnings.warn(
556 "Both structures have the same size so no partitioning is"
557 "performed to initialize the transport plan even though"
558 f"initialization method is {method}",
559 stacklevel=2,
560 )
561
562 def get_transport_from_partition(part):
563 if n > m: # partition C1 to deduce map from C1 to C2
564 T_ = nx.eye(m, type_as=C1)[part]
565 T_ = p[:, None] * T_
566 q = nx.sum(T_, 0)
567
568 factored_C1 = nx.dot(nx.dot(T_.T, C1), T_) / nx.outer(q, q)
569
570 # alignment of both structure seen as feature matrices
571 if use_target:
572 M_structure = euclidean_distances(factored_C1, C2)
573 T_emd = emd(q, q, M_structure)
574 inv_q = 1.0 / q
575
576 T = nx.dot(T_, inv_q[:, None] * T_emd)
577 else:
578 T = T_
579
580 elif m > n:
581 T_ = nx.eye(n, type_as=C1)[part] / m # assume uniform masses on C2
582 q = nx.sum(T_, 0)
583
584 factored_C2 = nx.dot(nx.dot(T_.T, C2), T_) / nx.outer(q, q)
585
586 # alignment of both structure seen as feature matrices
587 M_structure = euclidean_distances(factored_C2, C1)
588 T_emd = emd(q, p, M_structure)
589 inv_q = 1.0 / q
590
591 T = nx.dot(T_, inv_q[:, None] * T_emd).T
592 q = nx.sum(T, 0) # uniform one
593 else:
594 # alignment of both structure seen as feature matrices
595 M_structure = euclidean_distances(C1, C2)
596 q = p
597 T = emd(p, q, M_structure)
598
599 return T, q
600
601 # Handle initialization via structure information
602
603 if method == "product":
604 q = nx.ones(m, type_as=C1) / m
605 T = nx.outer(p, q)
606
607 elif method == "random_product":
608 np.random.seed(random_state)
609 q = np.random.uniform(0, m, size=(m,))
610 q = q / q.sum()
611 q = nx.from_numpy(q, type_as=p)
612 T = nx.outer(p, q)
613
614 elif method == "random":
615 np.random.seed(random_state)
616 U = np.random.uniform(0, n * m, size=(n, m))
617 U = (p / U.sum(1))[:, None] * U
618 T = nx.from_numpy(U, type_as=C1)
619
620 elif method in ["fluid", "fluid_soft"]:
621 # compute fluid partitioning on the biggest graph
622 if C_to_partition is None:
623 T, q = get_transport_from_partition(None)
624 else:
625 graph = from_numpy_array(C_to_partition)
626 part_sets = asyn_fluidc(graph, min_size, seed=random_state)
627 part = np.zeros(C_to_partition.shape[0], dtype=int)
628 for iset_, set_ in enumerate(part_sets):
629 set_ = list(set_)
630 part[set_] = iset_
631 part = nx.from_numpy(part)
632
633 T, q = get_transport_from_partition(part)
634
635 if "soft" in method:
636 T = (T + nx.outer(p, q)) / 2.0
637
638 elif method in ["spectral", "spectral_soft"]:
639 # compute spectral partitioning on the biggest graph
640 if C_to_partition is None:
641 T, q = get_transport_from_partition(None)
642 else:
643 sc = SpectralClustering(
644 n_clusters=min_size, random_state=random_state, affinity="precomputed"
645 ).fit(C_to_partition)
646 part = sc.labels_
647 T, q = get_transport_from_partition(part)
648
649 if "soft" in method:
650 T = (T + nx.outer(p, q)) / 2.0
651
652 elif method in ["kmeans", "kmeans_soft"]:
653 # compute spectral partitioning on the biggest graph
654 if C_to_partition is None:
655 T, q = get_transport_from_partition(None)
656 else:
657 km = KMeans(n_clusters=min_size, random_state=random_state, n_init=1).fit(
658 C_to_partition
659 )
660
661 part = km.labels_
662 T, q = get_transport_from_partition(part)
663
664 if "soft" in method:
665 T = (T + nx.outer(p, q)) / 2.0
666
667 if M is not None:
668 # Add feature information solving a semi-relaxed Wasserstein problem
669 # get minimum by rows as binary mask
670 TM = nx.ones(1, type_as=p) * (M == nx.reshape(nx.min(M, axis=1), (-1, 1)))
671 TM *= nx.reshape((p / nx.sum(TM, axis=1)), (-1, 1))
672
673 T = alpha * T + (1 - alpha) * TM
674
675 return T
676
677
678 def update_barycenter_structure(
679 Ts,
680 Cs,
681 lambdas,
682 p=None,
683 loss_fun="square_loss",
684 target=True,
685 check_zeros=True,
686 nx=None,
687 ):
688 r"""
689 Updates :math:`\mathbf{C}` according to the inner loss L with the `S`
690 :math:`\mathbf{T}_s` couplings calculated at each iteration of variants of
691 the GW barycenter problem (e.g GW :ref:`[12]`, srGW :ref:`[48]`).
692 If `target=True` it solves for:
693
694 .. math::
695
696 \mathbf{C}^* = \mathop{\arg \min}_{\mathbf{C}\in \mathbb{R}^{N \times N}} \quad
697 \sum_s \lambda_s \sum_{i,j,k,l}
698 L(\mathbf{C}^{(s)}_{i,k}, \mathbf{C}_{j,l}) \mathbf{T}^{(s)}_{i,j} \mathbf{T}^{(s)}_{k,l}
699
700 Else it solves the symmetric problem:
701
702 .. math::
703
704 \mathbf{C}^* = \mathop{\arg \min}_{\mathbf{C}\in \mathbb{R}^{N \times N}} \quad
705 \sum_s \lambda_s \sum_{i,j,k,l}
706 L(\mathbf{C}_{j,l}, \mathbf{C}^{(s)}_{i,k}) \mathbf{T}^{(s)}_{i,j} \mathbf{T}^{(s)}_{k,l}
707
708 Where :
709
710 - :math:`\mathbf{C}^{(s)}`: pairwise matrix in the s^{th} source space .
711 - :math:`\mathbf{C}`: pairwise matrix in the target space.
712 - :math:`L`: inner divergence for the GW loss
713
714 Parameters
715 ----------
716 Ts : list of S array-like of shape (ns, N) if `target=True` else (N, ns).
717 The `S` :math:`\mathbf{T}_s` couplings calculated at each iteration.
718 Cs : list of S array-like, shape(ns, ns)
719 Metric cost matrices.
720 lambdas : list of float,
721 List of the `S` spaces' weights.
722 p : array-like, shape (N,) or (S,N)
723 Masses or list of masses in the targeted barycenter.
724 loss_fun : str, optional. Default is 'square_loss'
725 Name of loss function to use in ['square_loss', 'kl_loss'].
726 target: bool, optional. Default is True.
727 Whether the barycenter is positioned as target (True) or source (False).
728 check_zeros: bool, optional. Default is True.
729 Whether to check if marginals on the barycenter contains zeros or not.
730 Can be set to False to gain time if marginals are known to be positive.
731 nx : backend, optional
732 If let to its default value None, a backend test will be conducted.
733
734 Returns
735 ----------
736 C : array-like, shape (`nt`, `nt`)
737 Updated :math:`\mathbf{C}` matrix.
738
739 References
740 ----------
741 .. [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon,
742 "Gromov-Wasserstein averaging of kernel and distance matrices."
743 International Conference on Machine Learning (ICML). 2016.
744
745 .. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty.
746 "Semi-relaxed Gromov-Wasserstein divergence and applications on graphs"
747 International Conference on Learning Representations (ICLR), 2022.
748
749 """
750
751 if nx is None:
752 arr = [*Ts, *Cs, p]
753 nx = get_backend(*arr)
754
755 S = len(Ts)
756
757 if p is None:
758 p = nx.concatenate(
759 [nx.sum(Ts[s], int(not target))[None, :] for s in range(S)], axis=0
760 )
761
762 # compute coefficients for the barycenter coming from marginals
763
764 if len(p.shape) == 1: # shared target masses potentially with zeros
765 if check_zeros:
766 inv_p = nx.nan_to_num(1.0 / p, nan=1.0, posinf=1.0, neginf=1.0)
767 else:
768 inv_p = 1.0 / p
769
770 prod = nx.outer(inv_p, inv_p)
771
772 else:
773 quotient = sum([lambdas[s] * nx.outer(p[s], p[s]) for s in range(S)])
774 if check_zeros:
775 prod = nx.nan_to_num(1.0 / quotient, nan=1.0, posinf=1.0, neginf=1.0)
776 else:
777 prod = 1.0 / quotient
778
779 # compute coefficients for the barycenter coming from Ts and Cs
780
781 if loss_fun == "square_loss":
782 if target:
783 list_structures = [
784 lambdas[s] * nx.dot(nx.dot(Ts[s].T, Cs[s]), Ts[s]) for s in range(S)
785 ]
786 else:
787 list_structures = [
788 lambdas[s] * nx.dot(nx.dot(Ts[s], Cs[s]), Ts[s].T) for s in range(S)
789 ]
790
791 return sum(list_structures) * prod
792
793 elif loss_fun == "kl_loss":
794 if target:
795 list_structures = [
796 lambdas[s] * nx.dot(nx.dot(Ts[s].T, Cs[s]), Ts[s]) for s in range(S)
797 ]
798
799 return sum(list_structures) * prod
800 else:
801 list_structures = [
802 lambdas[s]
803 * nx.dot(nx.dot(Ts[s], nx.log(nx.maximum(Cs[s], 1e-16))), Ts[s].T)
804 for s in range(S)
805 ]
806
807 return nx.exp(sum(list_structures) * prod)
808
809 else:
810 raise ValueError(f"not supported loss_fun = {loss_fun}")
811
812
813 def update_barycenter_feature(
814 Ts,
815 Ys,
816 lambdas,
817 p=None,
818 loss_fun="square_loss",
819 target=True,
820 check_zeros=True,
821 nx=None,
822 ):
823 r"""Updates the feature with respect to the `S` :math:`\mathbf{T}_s`
824 couplings calculated at each iteration of variants of the FGW
825 barycenter problem with inner wasserstein loss `loss_fun`
826 (e.g FGW :ref:`[24]`, srFGW :ref:`[48]`).
827 If `target=True` the barycenter is considered as the target else as the source.
828
829 Parameters
830 ----------
831 Ts : list of S array-like of shape (ns, N) if `target=True` else (N, ns).
832 The `S` :math:`\mathbf{T}_s` couplings calculated at each iteration.
833 Ys : list of S array-like, shape (ns, d)
834 Feature matrices.
835 lambdas : list of float
836 List of the `S` spaces' weights
837 p : array-like, shape (N,) or (S,N)
838 Masses or list of masses in the targeted barycenter.
839 loss_fun : str, optional. Default is 'square_loss'
840 Name of loss function to use in ['square_loss'].
841 target: bool, optional. Default is True.
842 Whether the barycenter is positioned as target (True) or source (False).
843 check_zeros: bool, optional. Default is True.
844 Whether to check if marginals on the barycenter contains zeros or not.
845 Can be set to False to gain time if marginals are known to be positive.
846 nx : backend, optional
847 If let to its default value None, a backend test will be conducted.
848
849 Returns
850 -------
851 X : array-like, shape (N, d)
852
853 References
854 ----------
855 .. [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain and Courty Nicolas
856 "Optimal Transport for structured data with application on graphs"
857 International Conference on Machine Learning (ICML). 2019.
858
859 .. [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty.
860 "Semi-relaxed Gromov-Wasserstein divergence and applications on graphs"
861 International Conference on Learning Representations (ICLR), 2022.
862 """
863 if nx is None:
864 arr = [*Ts, *Ys, p]
865 nx = get_backend(*arr)
866
867 if loss_fun != "square_loss":
868 raise ValueError(f"not supported loss_fun = {loss_fun}")
869
870 S = len(Ts)
871
872 if target:
873 list_features = [lambdas[s] * nx.dot(Ts[s].T, Ys[s]) for s in range(S)]
874 else:
875 list_features = [lambdas[s] * nx.dot(Ts[s], Ys[s]) for s in range(S)]
876
877 if p is None:
878 p = nx.concatenate(
879 [nx.sum(Ts[s], int(not target))[None, :] for s in range(S)], axis=0
880 )
881
882 if len(p.shape) == 1: # shared target masses potentially with zeros
883 if check_zeros:
884 inv_p = nx.nan_to_num(1.0 / p, nan=1.0, posinf=1.0, neginf=1.0)
885 else:
886 inv_p = 1.0 / p
887 else:
888 p_sum = sum([lambdas[s] * p[s] for s in range(S)])
889 if check_zeros:
890 inv_p = nx.nan_to_num(1.0 / p_sum, nan=1.0, posinf=1.0, neginf=1.0)
891 else:
892 inv_p = 1.0 / p_sum
893
894 return sum(list_features) * inv_p[:, None]
895
896
897 ############################################################################
898 # Methods related to fused unbalanced GW and unbalanced Co-Optimal Transport.
899 ############################################################################
900
901
902 def div_to_product(pi, a, b, pi1=None, pi2=None, divergence="kl", mass=True, nx=None):
903 r"""Fast computation of the Bregman divergence between an arbitrary measure and a product measure.
904 Only support for Kullback-Leibler and half-squared L2 divergences.
905
906 - For half-squared L2 divergence:
907
908 .. math::
909 \frac{1}{2} || \pi - a \otimes b ||^2
910 = \frac{1}{2} \Big[ \sum_{i, j} \pi_{ij}^2 + (\sum_i a_i^2) ( \sum_j b_j^2) - 2 \sum_{i, j} a_i \pi_{ij} b_j \Big]
911
912 - For Kullback-Leibler divergence:
913
914 .. math::
915 KL(\pi | a \otimes b)
916 = \langle \pi, \log \pi \rangle - \langle \pi_1, \log a \rangle
917 - \langle \pi_2, \log b \rangle - m(\pi) + m(a) m(b)
918
919 where :
920
921 - :math:`\pi` is the (`dim_a`, `dim_b`) transport plan
922 - :math:`\pi_1` and :math:`\pi_2` are the marginal distributions
923 - :math:`\mathbf{a}` and :math:`\mathbf{b}` are source and target unbalanced distributions
924 - :math:`m` denotes the mass of the measure
925
926 Parameters
927 ----------
928 pi : array-like (dim_a, dim_b)
929 Transport plan
930 a : array-like (dim_a,)
931 Unnormalized histogram of dimension `dim_a`
932 b : array-like (dim_b,)
933 Unnormalized histogram of dimension `dim_b`
934 pi1 : array-like (dim_a,), optional (default = None)
935 Marginal distribution with respect to the first dimension of the transport plan
936 Only used in case of Kullback-Leibler divergence.
937 pi2 : array-like (dim_a,), optional (default = None)
938 Marginal distribution with respect to the second dimension of the transport plan
939 Only used in case of Kullback-Leibler divergence.
940 divergence : string, default = "kl"
941 Bregman divergence, either "kl" (Kullback-Leibler divergence) or "l2" (half-squared L2 divergence)
942 mass : bool, optional. Default is False.
943 Only used in case of Kullback-Leibler divergence.
944 If False, calculate the relative entropy.
945 If True, calculate the Kullback-Leibler divergence.
946 nx : backend, optional
947 If let to its default value None, a backend test will be conducted.
948
949 Returns
950 -------
951 Bregman divergence between an arbitrary measure and a product measure.
952 """
953
954 arr = [pi, a, b, pi1, pi2]
955
956 if nx is None:
957 nx = get_backend(*arr, pi1, pi2)
958
959 if divergence == "kl":
960 if pi1 is None:
961 pi1 = nx.sum(pi, 1)
962 if pi2 is None:
963 pi2 = nx.sum(pi, 0)
964
965 res = (
966 nx.sum(pi * nx.log(pi + 1.0 * (pi == 0)))
967 - nx.sum(pi1 * nx.log(a))
968 - nx.sum(pi2 * nx.log(b))
969 )
970 if mass:
971 res = res - nx.sum(pi1) + nx.sum(a) * nx.sum(b)
972
973 elif divergence == "l2":
974 res = (
975 nx.sum(pi**2) + nx.sum(a**2) * nx.sum(b**2) - 2 * nx.dot(a, nx.dot(pi, b))
976 ) / 2
977
978 return res
979
980
981 def div_between_product(mu, nu, alpha, beta, divergence, nx=None):
982 r"""Fast computation of the Bregman divergence between two product measures.
983 Only support for Kullback-Leibler and half-squared L2 divergences.
984
985 For half-squared L2 divergence:
986
987 .. math::
988 \frac{1}{2} || \mu \otimes \nu, \alpha \otimes \beta ||^2
989 = \frac{1}{2} \Big[ ||\alpha||^2 ||\beta||^2 + ||\mu||^2 ||\nu||^2 - 2 \langle \alpha, \mu \rangle \langle \beta, \nu \rangle \Big]
990
991 For Kullback-Leibler divergence:
992
993 .. math::
994 KL(\mu \otimes \nu, \alpha \otimes \beta)
995 = m(\mu) * KL(\nu, \beta) + m(\nu) * KL(\mu, \alpha) + (m(\mu) - m(\alpha)) * (m(\nu) - m(\beta))
996
997 where:
998
999 - :math:`\mu` and :math:`\alpha` are two measures having the same shape.
1000 - :math:`\nu` and :math:`\beta` are two measures having the same shape.
1001 - :math:`m` denotes the mass of the measure
1002
1003 Parameters
1004 ----------
1005 mu : array-like
1006 vector or matrix
1007 nu : array-like
1008 vector or matrix
1009 alpha : array-like
1010 vector or matrix with the same shape as `\mu`
1011 beta : array-like
1012 vector or matrix with the same shape as `\nu`
1013 divergence : string, default = "kl"
1014 Bregman divergence, either "kl" (Kullback-Leibler divergence) or "l2" (half-squared L2 divergence)
1015 nx : backend, optional
1016 If let to its default value None, a backend test will be conducted.
1017
1018 Returns
1019 ----------
1020 Bregman divergence between two product measures.
1021 """
1022
1023 if nx is None:
1024 nx = get_backend(mu, nu, alpha, beta)
1025
1026 if divergence == "kl":
1027 m_mu, m_nu = nx.sum(mu), nx.sum(nu)
1028 m_alpha, m_beta = nx.sum(alpha), nx.sum(beta)
1029 const = (m_mu - m_alpha) * (m_nu - m_beta)
1030 res = (
1031 m_nu * nx.kl_div(mu, alpha, mass=True)
1032 + m_mu * nx.kl_div(nu, beta, mass=True)
1033 + const
1034 )
1035
1036 elif divergence == "l2":
1037 res = (
1038 nx.sum(alpha**2) * nx.sum(beta**2)
1039 - 2 * nx.sum(alpha * mu) * nx.sum(beta * nu)
1040 + nx.sum(mu**2) * nx.sum(nu**2)
1041 ) / 2
1042
1043 return res
1044
1045
1046 # Support functions for BCD schemes
1047 def uot_cost_matrix(data, pi, tuple_p, hyperparams, divergence, reg_type, nx=None):
1048 r"""The Block Coordinate Descent algorithm for FUGW and UCOOT
1049 requires solving an UOT problem in each iteration.
1050 In particular, we need to specify the following inputs:
1051
1052 - Cost matrix
1053
1054 - Hyperparameters (marginal-relaxations and regularization)
1055
1056 - Reference measures in the marginal-relaxation and regularization terms
1057
1058 This method returns the cost matrix.
1059 The method :any:`ot.gromov.uot_parameters_and_measures` returns the rest of the inputs.
1060
1061 Parameters
1062 ----------
1063 data : tuple of arrays
1064 vector or matrix
1065 pi : array-like
1066 vector or matrix
1067 tuple_p : tuple of arrays
1068 Tuple of reference measures in the marginal-relaxation terms
1069 w.r.t the (either sample or feature) coupling
1070 hyperparams : tuple of floats
1071 Hyperparameters of marginal-relaxation and regularization terms
1072 in the fused unbalanced across-domain divergence
1073 divergence : string, default = "kl"
1074 Bregman divergence, either "kl" (Kullback-Leibler divergence) or "l2" (half-squared L2 divergence)
1075 reg_type : string,
1076 Type of regularization term in the fused unbalanced across-domain divergence
1077
1078 - `reg_type = "joint"` corresponds to FUGW
1079
1080 - `reg_type = "independent"` corresponds to UCOOT
1081 nx : backend, optional
1082 If let to its default value None, a backend test will be conducted.
1083
1084 Returns
1085 ----------
1086 Cost matrix of the UOT subroutine for UCOOT and FUGW
1087 """
1088
1089 X_sqr, Y_sqr, X, Y, M = data
1090 rho_x, rho_y, eps = hyperparams
1091 a, b = tuple_p
1092
1093 if nx is None:
1094 nx = get_backend(X, Y, a, b)
1095
1096 pi1, pi2 = nx.sum(pi, 1), nx.sum(pi, 0)
1097 A, B = nx.dot(X_sqr, pi1), nx.dot(Y_sqr, pi2)
1098 uot_cost = A[:, None] + B[None, :] - 2 * nx.dot(nx.dot(X, pi), Y.T)
1099 if M is not None:
1100 uot_cost = uot_cost + M
1101
1102 if divergence == "kl":
1103 if rho_x != float("inf") and rho_x != 0:
1104 uot_cost = uot_cost + rho_x * nx.kl_div(pi1, a, mass=False)
1105 if rho_y != float("inf") and rho_y != 0:
1106 uot_cost = uot_cost + rho_y * nx.kl_div(pi2, b, mass=False)
1107 if reg_type == "joint" and eps > 0:
1108 uot_cost = uot_cost + eps * div_to_product(
1109 pi, a, b, pi1, pi2, divergence, mass=False, nx=nx
1110 )
1111
1112 return uot_cost
1113
1114
1115 def uot_parameters_and_measures(
1116 pi, tuple_weights, hyperparams, reg_type, divergence, nx
1117 ):
1118 r"""The Block Coordinate Descent algorithm for FUGW and UCOOT
1119 requires solving an UOT problem in each iteration.
1120 In particular, we need to specify the following inputs:
1121
1122 - Cost matrix
1123
1124 - Hyperparameters (marginal-relaxations and regularization)
1125
1126 - Reference measures in the marginal-relaxation and regularization terms
1127
1128 The method :any:`ot.gromov.uot_cost_matrix` returns the cost matrix.
1129 This method returns the rest of the inputs.
1130
1131 Parameters
1132 ----------
1133 pi : array-like
1134 vector or matrix
1135 tuple_weights : tuple of arrays
1136 Tuple of reference measures in the marginal-relaxation and regularization terms
1137 w.r.t the (either sample or feature) coupling
1138 hyperparams : tuple of floats
1139 Hyperparameters of marginal-relaxation and regularization terms
1140 in the fused unbalanced across-domain divergence
1141 reg_type : string,
1142 Type of regularization term in the fused unbalanced across-domain divergence
1143
1144 - `reg_type = "joint"` corresponds to FUGW
1145
1146 - `reg_type = "independent"` corresponds to UCOOT
1147 divergence : string, default = "kl"
1148 Bregman divergence, either "kl" (Kullback-Leibler divergence) or "l2" (half-squared L2 divergence)
1149 nx : backend, optional
1150 If let to its default value None, a backend test will be conducted.
1151
1152 Returns
1153 ----------
1154 Tuple of hyperparameters and distributions (weights)
1155 """
1156
1157 rho_x, rho_y, eps = hyperparams
1158 wx, wy, wxy = tuple_weights
1159
1160 if divergence == "l2":
1161 pi1, pi2 = nx.sum(pi, 1), nx.sum(pi, 0)
1162 l2_pi1, l2_pi2, l2_pi = nx.sum(pi1**2), nx.sum(pi2**2), nx.sum(pi**2)
1163
1164 weighted_wx = wx * nx.sum(pi1 * wx) / l2_pi1
1165 weighted_wy = wy * nx.sum(pi2 * wy) / l2_pi2
1166 weighted_wxy = wxy * nx.sum(pi * wxy) / l2_pi if reg_type == "joint" else wxy
1167 weighted_w = (weighted_wx, weighted_wy, weighted_wxy)
1168
1169 new_rho = (rho_x * l2_pi1, rho_y * l2_pi2)
1170 new_eps = eps * l2_pi if reg_type == "joint" else eps
1171
1172 elif divergence == "kl":
1173 mass = nx.sum(pi)
1174 new_rho = (rho_x * mass, rho_y * mass)
1175 new_eps = mass * eps if reg_type == "joint" else eps
1176 weighted_w = tuple_weights
1177
1178 return weighted_w, new_rho, new_eps
1179
1180
1181 def fused_unbalanced_across_spaces_cost(
1182 M_linear,
1183 data,
1184 tuple_pxy_samp,
1185 tuple_pxy_feat,
1186 pi_samp,
1187 pi_feat,
1188 hyperparams,
1189 divergence,
1190 reg_type,
1191 nx,
1192 ):
1193 r"""Return the fused unbalanced across-space divergence between two spaces
1194
1195 Parameters
1196 ----------
1197 M_linear : tuple of arrays
1198 Pair of cost matrices corresponding to the Wasserstein terms w.r.t sample and feature couplings
1199 data : tuple of arrays
1200 Tuple of input spaces represented as matrices
1201 tuple_pxy_samp : tuple of arrays
1202 Tuple of reference measures in the marginal-relaxation and regularization terms
1203 w.r.t the sample coupling
1204 tuple_pxy_feat : tuple of arrays
1205 Tuple of reference measures in the marginal-relaxation and regularization terms
1206 w.r.t the feature coupling
1207 pi_samp : array-like
1208 Sample coupling
1209 pi_feat : array-like
1210 Feature coupling
1211 hyperparams : tuple of floats
1212 Hyperparameters of marginal-relaxation and regularization terms
1213 in the fused unbalanced across-domain divergence
1214 divergence : string, default = "kl"
1215 Bregman divergence, either "kl" (Kullback-Leibler divergence) or "l2" (half-squared L2 divergence)
1216 reg_type : string,
1217 Type of regularization term in the fused unbalanced across-domain divergence
1218
1219 - `reg_type = "joint"` corresponds to FUGW
1220
1221 - `reg_type = "independent"` corresponds to UCOOT
1222 nx : backend, optional
1223 If let to its default value None, a backend test will be conducted.
1224
1225 Returns
1226 ----------
1227 Fused unbalanced across-space divergence between two spaces
1228 """
1229
1230 rho_x, rho_y, eps_samp, eps_feat = hyperparams
1231 M_samp, M_feat = M_linear
1232 px_samp, py_samp, pxy_samp = tuple_pxy_samp
1233 px_feat, py_feat, pxy_feat = tuple_pxy_feat
1234 X_sqr, Y_sqr, X, Y = data
1235
1236 pi1_samp, pi2_samp = nx.sum(pi_samp, 1), nx.sum(pi_samp, 0)
1237 pi1_feat, pi2_feat = nx.sum(pi_feat, 1), nx.sum(pi_feat, 0)
1238
1239 A_sqr = nx.dot(nx.dot(X_sqr, pi1_feat), pi1_samp)
1240 B_sqr = nx.dot(nx.dot(Y_sqr, pi2_feat), pi2_samp)
1241 AB = nx.dot(nx.dot(X, pi_feat), Y.T) * pi_samp
1242 linear_cost = A_sqr + B_sqr - 2 * nx.sum(AB)
1243
1244 ucoot_cost = linear_cost
1245 if M_samp is not None:
1246 ucoot_cost = ucoot_cost + nx.sum(pi_samp * M_samp)
1247 if M_feat is not None:
1248 ucoot_cost = ucoot_cost + nx.sum(pi_feat * M_feat)
1249
1250 if rho_x != float("inf") and rho_x != 0:
1251 ucoot_cost = ucoot_cost + rho_x * div_between_product(
1252 pi1_samp, pi1_feat, px_samp, px_feat, divergence, nx
1253 )
1254 if rho_y != float("inf") and rho_y != 0:
1255 ucoot_cost = ucoot_cost + rho_y * div_between_product(
1256 pi2_samp, pi2_feat, py_samp, py_feat, divergence, nx
1257 )
1258
1259 if reg_type == "joint" and eps_samp != 0:
1260 div_cost = div_between_product(
1261 pi_samp, pi_feat, pxy_samp, pxy_feat, divergence, nx
1262 )
1263 ucoot_cost = ucoot_cost + eps_samp * div_cost
1264 elif reg_type == "independent":
1265 if eps_samp != 0:
1266 div_samp = div_to_product(
1267 pi_samp,
1268 pi1_samp,
1269 pi2_samp,
1270 px_samp,
1271 py_samp,
1272 divergence,
1273 mass=True,
1274 nx=nx,
1275 )
1276 ucoot_cost = ucoot_cost + eps_samp * div_samp
1277 if eps_feat != 0:
1278 div_feat = div_to_product(
1279 pi_feat,
1280 pi1_feat,
1281 pi2_feat,
1282 px_feat,
1283 py_feat,
1284 divergence,
1285 mass=True,
1286 nx=nx,
1287 )
1288 ucoot_cost = ucoot_cost + eps_feat * div_feat
1289
1290 return linear_cost, ucoot_cost