Debian Codegraph @

ot/gromov/_estimators.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Gromov-Wasserstein and Fused-Gromov-Wasserstein stochastic estimators.
4 """
5
6 # Author: Rémi Flamary <[email protected]>
7 # Tanguy Kerdoncuff <[email protected]>
8 #
9 # License: MIT License
10
11 import numpy as np
12
13
14 from ..bregman import sinkhorn
15 from ..utils import list_to_array, check_random_state
16 from ..lp import emd_1d, emd
17 from ..backend import get_backend
18
19
20 def GW_distance_estimation(
21 C1,
22 C2,
23 p,
24 q,
25 loss_fun,
26 T,
27 nb_samples_p=None,
28 nb_samples_q=None,
29 std=True,
30 random_state=None,
31 ):
32 r"""
33 Returns an approximation of the Gromov-Wasserstein loss between :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})`
34 with a fixed transport plan :math:`\mathbf{T}`. To recover an approximation of the Gromov-Wasserstein distance as defined in [13] compute :math:`d_{GW} = \frac{1}{2} \sqrt{\mathbf{GW}}`.
35
36 The function gives an unbiased approximation of the following equation:
37
38 .. math::
39
40 \mathbf{GW} = \sum_{i,j,k,l} L(\mathbf{C_{1}}_{i,k}, \mathbf{C_{2}}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
41
42 Where :
43
44 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
45 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
46 - `L` : Loss function to account for the misfit between the similarity matrices
47 - :math:`\mathbf{T}`: Matrix with marginal :math:`\mathbf{p}` and :math:`\mathbf{q}`
48
49 Parameters
50 ----------
51 C1 : array-like, shape (ns, ns)
52 Metric cost matrix in the source space
53 C2 : array-like, shape (nt, nt)
54 Metric cost matrix in the target space
55 p : array-like, shape (ns,)
56 Distribution in the source space
57 q : array-like, shape (nt,)
58 Distribution in the target space
59 loss_fun : function: :math:`\mathbb{R} \times \mathbb{R} \mapsto \mathbb{R}`
60 Loss function used for the distance, the transport plan does not depend on the loss function
61 T : csr or array-like, shape (ns, nt)
62 Transport plan matrix, either a sparse csr or a dense matrix
63 nb_samples_p : int, optional
64 `nb_samples_p` is the number of samples (without replacement) along the first dimension of :math:`\mathbf{T}`
65 nb_samples_q : int, optional
66 `nb_samples_q` is the number of samples along the second dimension of :math:`\mathbf{T}`, for each sample along the first
67 std : bool, optional
68 Standard deviation associated with the prediction of the gromov-wasserstein cost
69 random_state : int or RandomState instance, optional
70 Fix the seed for reproducibility
71
72 Returns
73 -------
74 : float
75 Gromov-wasserstein cost
76
77 References
78 ----------
79 .. [14] Kerdoncuff, Tanguy, Emonet, Rémi, Sebban, Marc
80 "Sampled Gromov Wasserstein."
81 Machine Learning Journal (MLJ). 2021.
82
83 """
84 C1, C2, p, q = list_to_array(C1, C2, p, q)
85 nx = get_backend(C1, C2, p, q)
86
87 generator = check_random_state(random_state)
88
89 len_p = p.shape[0]
90 len_q = q.shape[0]
91
92 # It is always better to sample from the biggest distribution first.
93 if len_p < len_q:
94 p, q = q, p
95 len_p, len_q = len_q, len_p
96 C1, C2 = C2, C1
97 T = T.T
98
99 if nb_samples_p is None:
100 if nx.issparse(T):
101 # If T is sparse, it probably mean that PoGroW was used, thus the number of sample is reduced
102 nb_samples_p = min(int(5 * (len_p * np.log(len_p)) ** 0.5), len_p)
103 else:
104 nb_samples_p = len_p
105 else:
106 # The number of sample along the first dimension is without replacement.
107 nb_samples_p = min(nb_samples_p, len_p)
108 if nb_samples_q is None:
109 nb_samples_q = 1
110 if std:
111 nb_samples_q = max(2, nb_samples_q)
112
113 index_k = np.zeros((nb_samples_p, nb_samples_q), dtype=int)
114 index_l = np.zeros((nb_samples_p, nb_samples_q), dtype=int)
115
116 index_i = generator.choice(
117 len_p, size=nb_samples_p, p=nx.to_numpy(p), replace=False
118 )
119 index_j = generator.choice(
120 len_p, size=nb_samples_p, p=nx.to_numpy(p), replace=False
121 )
122
123 for i in range(nb_samples_p):
124 if nx.issparse(T):
125 T_indexi = nx.reshape(nx.todense(T[index_i[i], :]), (-1,))
126 T_indexj = nx.reshape(nx.todense(T[index_j[i], :]), (-1,))
127 else:
128 T_indexi = T[index_i[i], :]
129 T_indexj = T[index_j[i], :]
130 # For each of the row sampled, the column is sampled.
131 index_k[i] = generator.choice(
132 len_q,
133 size=nb_samples_q,
134 p=nx.to_numpy(T_indexi / nx.sum(T_indexi)),
135 replace=True,
136 )
137 index_l[i] = generator.choice(
138 len_q,
139 size=nb_samples_q,
140 p=nx.to_numpy(T_indexj / nx.sum(T_indexj)),
141 replace=True,
142 )
143
144 list_value_sample = nx.stack(
145 [
146 loss_fun(
147 C1[np.ix_(index_i, index_j)], C2[np.ix_(index_k[:, n], index_l[:, n])]
148 )
149 for n in range(nb_samples_q)
150 ],
151 axis=2,
152 )
153
154 if std:
155 std_value = nx.sum(nx.std(list_value_sample, axis=2) ** 2) ** 0.5
156 return nx.mean(list_value_sample), std_value / (nb_samples_p * nb_samples_p)
157 else:
158 return nx.mean(list_value_sample)
159
160
161 def pointwise_gromov_wasserstein(
162 C1,
163 C2,
164 p,
165 q,
166 loss_fun,
167 alpha=1,
168 max_iter=100,
169 threshold_plan=0,
170 log=False,
171 verbose=False,
172 random_state=None,
173 ):
174 r"""
175 Returns the gromov-wasserstein transport between :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})` using a stochastic Frank-Wolfe.
176 This method has a :math:`\mathcal{O}(\mathrm{max\_iter} \times PN^2)` time complexity with `P` the number of Sinkhorn iterations.
177
178 The function solves the following optimization problem:
179
180 .. math::
181 \mathbf{GW} = \mathop{\arg \min}_\mathbf{T} \quad \sum_{i,j,k,l}
182 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
183
184 s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p}
185
186 \mathbf{T}^T \mathbf{1} &= \mathbf{q}
187
188 \mathbf{T} &\geq 0
189
190 Where :
191
192 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
193 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
194 - :math:`\mathbf{p}`: distribution in the source space
195 - :math:`\mathbf{q}`: distribution in the target space
196 - `L`: loss function to account for the misfit between the similarity matrices
197
198 Parameters
199 ----------
200 C1 : array-like, shape (ns, ns)
201 Metric cost matrix in the source space
202 C2 : array-like, shape (nt, nt)
203 Metric cost matrix in the target space
204 p : array-like, shape (ns,)
205 Distribution in the source space
206 q : array-like, shape (nt,)
207 Distribution in the target space
208 loss_fun : function: :math:`\mathbb{R} \times \mathbb{R} \mapsto \mathbb{R}`
209 Loss function used for the distance, the transport plan does not depend on the loss function
210 alpha : float
211 Step of the Frank-Wolfe algorithm, should be between 0 and 1
212 max_iter : int, optional
213 Max number of iterations
214 threshold_plan : float, optional
215 Deleting very small values in the transport plan. If above zero, it violates the marginal constraints.
216 verbose : bool, optional
217 Print information along iterations
218 log : bool, optional
219 Gives the distance estimated and the standard deviation
220 random_state : int or RandomState instance, optional
221 Fix the seed for reproducibility
222
223 Returns
224 -------
225 T : array-like, shape (`ns`, `nt`)
226 Optimal coupling between the two spaces
227
228 References
229 ----------
230 .. [14] Kerdoncuff, Tanguy, Emonet, Rémi, Sebban, Marc
231 "Sampled Gromov Wasserstein."
232 Machine Learning Journal (MLJ). 2021.
233
234 """
235 C1, C2, p, q = list_to_array(C1, C2, p, q)
236 nx = get_backend(C1, C2, p, q)
237
238 len_p = p.shape[0]
239 len_q = q.shape[0]
240
241 generator = check_random_state(random_state)
242
243 index = np.zeros(2, dtype=int)
244
245 # Initialize with default marginal
246 index[0] = generator.choice(len_p, size=1, p=nx.to_numpy(p))
247 index[1] = generator.choice(len_q, size=1, p=nx.to_numpy(q))
248 T = nx.tocsr(emd_1d(C1[index[0]], C2[index[1]], a=p, b=q, dense=False))
249
250 best_gw_dist_estimated = np.inf
251 for cpt in range(max_iter):
252 index[0] = generator.choice(len_p, size=1, p=nx.to_numpy(p))
253 T_index0 = nx.reshape(nx.todense(T[index[0], :]), (-1,))
254 index[1] = generator.choice(
255 len_q, size=1, p=nx.to_numpy(T_index0 / nx.sum(T_index0))
256 )
257
258 if alpha == 1:
259 T = nx.tocsr(emd_1d(C1[index[0]], C2[index[1]], a=p, b=q, dense=False))
260 else:
261 new_T = nx.tocsr(emd_1d(C1[index[0]], C2[index[1]], a=p, b=q, dense=False))
262 T = (1 - alpha) * T + alpha * new_T
263 # To limit the number of non 0, the values below the threshold are set to 0.
264 T = nx.eliminate_zeros(T, threshold=threshold_plan)
265
266 if cpt % 10 == 0 or cpt == (max_iter - 1):
267 gw_dist_estimated = GW_distance_estimation(
268 C1=C1,
269 C2=C2,
270 loss_fun=loss_fun,
271 p=p,
272 q=q,
273 T=T,
274 std=False,
275 random_state=generator,
276 )
277
278 if gw_dist_estimated < best_gw_dist_estimated:
279 best_gw_dist_estimated = gw_dist_estimated
280 best_T = nx.copy(T)
281
282 if verbose:
283 if cpt % 200 == 0:
284 print(
285 "{:5s}|{:12s}".format("It.", "Best gw estimated")
286 + "\n"
287 + "-" * 19
288 )
289 print("{:5d}|{:8e}|".format(cpt, best_gw_dist_estimated))
290
291 if log:
292 log = {}
293 log["gw_dist_estimated"], log["gw_dist_std"] = GW_distance_estimation(
294 C1=C1, C2=C2, loss_fun=loss_fun, p=p, q=q, T=best_T, random_state=generator
295 )
296 return best_T, log
297 return best_T
298
299
300 def sampled_gromov_wasserstein(
301 C1,
302 C2,
303 p,
304 q,
305 loss_fun,
306 nb_samples_grad=100,
307 epsilon=1,
308 max_iter=500,
309 log=False,
310 verbose=False,
311 random_state=None,
312 ):
313 r"""
314 Returns the gromov-wasserstein transport between :math:`(\mathbf{C_1}, \mathbf{p})` and :math:`(\mathbf{C_2}, \mathbf{q})` using a 1-stochastic Frank-Wolfe.
315 This method has a :math:`\mathcal{O}(\mathrm{max\_iter} \times N \log(N))` time complexity by relying on the 1D Optimal Transport solver.
316
317 The function solves the following optimization problem:
318
319 .. math::
320 \mathbf{GW} = \mathop{\arg \min}_\mathbf{T} \quad \sum_{i,j,k,l}
321 L(\mathbf{C_1}_{i,k}, \mathbf{C_2}_{j,l}) \mathbf{T}_{i,j} \mathbf{T}_{k,l}
322
323 s.t. \ \mathbf{T} \mathbf{1} &= \mathbf{p}
324
325 \mathbf{T}^T \mathbf{1} &= \mathbf{q}
326
327 \mathbf{T} &\geq 0
328
329 Where :
330
331 - :math:`\mathbf{C_1}`: Metric cost matrix in the source space
332 - :math:`\mathbf{C_2}`: Metric cost matrix in the target space
333 - :math:`\mathbf{p}`: distribution in the source space
334 - :math:`\mathbf{q}`: distribution in the target space
335 - `L`: loss function to account for the misfit between the similarity matrices
336
337 Parameters
338 ----------
339 C1 : array-like, shape (ns, ns)
340 Metric cost matrix in the source space
341 C2 : array-like, shape (nt, nt)
342 Metric cost matrix in the target space
343 p : array-like, shape (ns,)
344 Distribution in the source space
345 q : array-like, shape (nt,)
346 Distribution in the target space
347 loss_fun : function: :math:`\mathbb{R} \times \mathbb{R} \mapsto \mathbb{R}`
348 Loss function used for the distance, the transport plan does not depend on the loss function
349 nb_samples_grad : int
350 Number of samples to approximate the gradient
351 epsilon : float
352 Weight of the Kullback-Leibler regularization
353 max_iter : int, optional
354 Max number of iterations
355 verbose : bool, optional
356 Print information along iterations
357 log : bool, optional
358 Gives the distance estimated and the standard deviation
359 random_state : int or RandomState instance, optional
360 Fix the seed for reproducibility
361
362 Returns
363 -------
364 T : array-like, shape (`ns`, `nt`)
365 Optimal coupling between the two spaces
366
367 References
368 ----------
369 .. [14] Kerdoncuff, Tanguy, Emonet, Rémi, Sebban, Marc
370 "Sampled Gromov Wasserstein."
371 Machine Learning Journal (MLJ). 2021.
372
373 """
374 C1, C2, p, q = list_to_array(C1, C2, p, q)
375 nx = get_backend(C1, C2, p, q)
376
377 len_p = p.shape[0]
378 len_q = q.shape[0]
379
380 generator = check_random_state(random_state)
381
382 # The most natural way to define nb_sample is with a simple integer.
383 if isinstance(nb_samples_grad, int):
384 if nb_samples_grad > len_p:
385 # As the sampling along the first dimension is done without replacement, the rest is reported to the second
386 # dimension.
387 nb_samples_grad_p, nb_samples_grad_q = len_p, nb_samples_grad // len_p
388 else:
389 nb_samples_grad_p, nb_samples_grad_q = nb_samples_grad, 1
390 else:
391 nb_samples_grad_p, nb_samples_grad_q = nb_samples_grad
392 T = nx.outer(p, q)
393 # continue_loop allows to stop the loop if there is several successive small modification of T.
394 continue_loop = 0
395
396 # The gradient of GW is more complex if the two matrices are not symmetric.
397 C_are_symmetric = nx.allclose(C1, C1.T, rtol=1e-10, atol=1e-10) and nx.allclose(
398 C2, C2.T, rtol=1e-10, atol=1e-10
399 )
400
401 for cpt in range(max_iter):
402 index0 = generator.choice(
403 len_p, size=nb_samples_grad_p, p=nx.to_numpy(p), replace=False
404 )
405 Lik = 0
406 for i, index0_i in enumerate(index0):
407 index1 = generator.choice(
408 len_q,
409 size=nb_samples_grad_q,
410 p=nx.to_numpy(T[index0_i, :] / nx.sum(T[index0_i, :])),
411 replace=False,
412 )
413 # If the matrices C are not symmetric, the gradient has 2 terms, thus the term is chosen randomly.
414 if (not C_are_symmetric) and generator.rand(1) > 0.5:
415 Lik += nx.mean(
416 loss_fun(
417 C1[:, [index0[i]] * nb_samples_grad_q][:, None, :],
418 C2[:, index1][None, :, :],
419 ),
420 axis=2,
421 )
422 else:
423 Lik += nx.mean(
424 loss_fun(
425 C1[[index0[i]] * nb_samples_grad_q, :][:, :, None],
426 C2[index1, :][:, None, :],
427 ),
428 axis=0,
429 )
430
431 max_Lik = nx.max(Lik)
432 if max_Lik == 0:
433 continue
434 # This division by the max is here to facilitate the choice of epsilon.
435 Lik /= max_Lik
436
437 if epsilon > 0:
438 # Set to infinity all the numbers below exp(-200) to avoid log of 0.
439 log_T = nx.log(nx.clip(T, np.exp(-200), 1))
440 log_T = nx.where(log_T == -200, -np.inf, log_T)
441 Lik = Lik - epsilon * log_T
442
443 try:
444 new_T = sinkhorn(a=p, b=q, M=Lik, reg=epsilon)
445 except (RuntimeWarning, UserWarning):
446 print("Warning caught in Sinkhorn: Return last stable T")
447 break
448 else:
449 new_T = emd(a=p, b=q, M=Lik)
450
451 change_T = nx.mean((T - new_T) ** 2)
452 if change_T <= 10e-20:
453 continue_loop += 1
454 if continue_loop > 100: # Number max of low modifications of T
455 T = nx.copy(new_T)
456 break
457 else:
458 continue_loop = 0
459
460 if verbose and cpt % 10 == 0:
461 if cpt % 200 == 0:
462 print(
463 "{:5s}|{:12s}".format("It.", "||T_n - T_{n+1}||") + "\n" + "-" * 19
464 )
465 print("{:5d}|{:8e}|".format(cpt, change_T))
466 T = nx.copy(new_T)
467
468 if log:
469 log = {}
470 log["gw_dist_estimated"], log["gw_dist_std"] = GW_distance_estimation(
471 C1=C1, C2=C2, loss_fun=loss_fun, p=p, q=q, T=T, random_state=generator
472 )
473 return T, log
474 return T