Debian Codegraph @

test/gromov/test_gw.py

raw symbols SCIP
1 """Tests for gromov._gw.py"""
2
3 # Author: Erwan Vautier <[email protected]>
4 # Nicolas Courty <[email protected]>
5 # Titouan Vayer <[email protected]>
6 # Cédric Vincent-Cuaz <[email protected]>
7 #
8 # License: MIT License
9
10 import numpy as np
11 import pytest
12 import warnings
13
14 import ot
15 from ot.backend import torch, tf
16
17
18 def test_gromov(nx):
19 n_samples = 20 # nb samples
20 mu_s = np.array([0, 0])
21 cov_s = np.array([[1, 0], [0, 1]])
22
23 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=1)
24 xt = xs[::-1].copy()
25
26 p = ot.unif(n_samples)
27 q = ot.unif(n_samples)
28 G0 = p[:, None] * q[None, :]
29
30 C1 = ot.dist(xs, xs)
31 C2 = ot.dist(xt, xt)
32
33 C1 /= C1.max()
34 C2 /= C2.max()
35
36 C1b, C2b, pb, qb, G0b = nx.from_numpy(C1, C2, p, q, G0)
37
38 G = ot.gromov.gromov_wasserstein(
39 C1,
40 C2,
41 None,
42 q,
43 "square_loss",
44 G0=G0,
45 verbose=True,
46 alpha_min=0.0,
47 alpha_max=1.0,
48 )
49 Gb = nx.to_numpy(
50 ot.gromov.gromov_wasserstein(
51 C1b, C2b, pb, None, "square_loss", symmetric=True, G0=G0b, verbose=True
52 )
53 )
54
55 # check constraints
56 np.testing.assert_allclose(G, Gb, atol=1e-06)
57 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
58 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
59
60 Id = (1 / (1.0 * n_samples)) * np.eye(n_samples, n_samples)
61
62 np.testing.assert_allclose(Gb, np.flipud(Id), atol=1e-04)
63 for armijo in [False, True]:
64 gw, log = ot.gromov.gromov_wasserstein2(
65 C1, C2, None, q, "kl_loss", armijo=armijo, log=True
66 )
67 gwb, logb = ot.gromov.gromov_wasserstein2(
68 C1b, C2b, pb, None, "kl_loss", armijo=armijo, log=True
69 )
70 gwb = nx.to_numpy(gwb)
71
72 gw_val = ot.gromov.gromov_wasserstein2(
73 C1, C2, p, q, "kl_loss", armijo=armijo, G0=G0, log=False
74 )
75 gw_valb = nx.to_numpy(
76 ot.gromov.gromov_wasserstein2(
77 C1b, C2b, pb, qb, "kl_loss", armijo=armijo, G0=G0b, log=False
78 )
79 )
80
81 G = log["T"]
82 Gb = nx.to_numpy(logb["T"])
83
84 np.testing.assert_allclose(gw, gwb, atol=1e-06)
85 np.testing.assert_allclose(gwb, 0, atol=1e-1, rtol=1e-1)
86
87 np.testing.assert_allclose(gw_val, gw_valb, atol=1e-06)
88 np.testing.assert_allclose(gwb, gw_valb, atol=1e-1, rtol=1e-1) # cf log=False
89
90 # check constraints
91 np.testing.assert_allclose(G, Gb, atol=1e-06)
92 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
93 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
94
95
96 def test_asymmetric_gromov(nx):
97 n_samples = 20 # nb samples
98 rng = np.random.RandomState(0)
99 C1 = rng.uniform(low=0.0, high=10, size=(n_samples, n_samples))
100 idx = np.arange(n_samples)
101 rng.shuffle(idx)
102 C2 = C1[idx, :][:, idx]
103
104 p = ot.unif(n_samples)
105 q = ot.unif(n_samples)
106 G0 = p[:, None] * q[None, :]
107
108 C1b, C2b, pb, qb, G0b = nx.from_numpy(C1, C2, p, q, G0)
109
110 G, log = ot.gromov.gromov_wasserstein(
111 C1, C2, p, q, "square_loss", G0=G0, log=True, symmetric=False, verbose=True
112 )
113 Gb, logb = ot.gromov.gromov_wasserstein(
114 C1b, C2b, pb, qb, "square_loss", log=True, symmetric=False, G0=G0b, verbose=True
115 )
116 Gb = nx.to_numpy(Gb)
117 # check constraints
118 np.testing.assert_allclose(G, Gb, atol=1e-06)
119 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
120 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
121
122 np.testing.assert_allclose(log["gw_dist"], 0.0, atol=1e-04)
123 np.testing.assert_allclose(logb["gw_dist"], 0.0, atol=1e-04)
124
125 gw, log = ot.gromov.gromov_wasserstein2(
126 C1, C2, p, q, "square_loss", G0=G0, log=True, symmetric=False, verbose=True
127 )
128 gwb, logb = ot.gromov.gromov_wasserstein2(
129 C1b, C2b, pb, qb, "square_loss", log=True, symmetric=False, G0=G0b, verbose=True
130 )
131
132 G = log["T"]
133 Gb = nx.to_numpy(logb["T"])
134 # check constraints
135 np.testing.assert_allclose(G, Gb, atol=1e-06)
136 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
137 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
138
139 np.testing.assert_allclose(log["gw_dist"], 0.0, atol=1e-04)
140 np.testing.assert_allclose(logb["gw_dist"], 0.0, atol=1e-04)
141
142
143 def test_gromov_integer_warnings(nx):
144 n_samples = 10 # nb samples
145 mu_s = np.array([0, 0])
146 cov_s = np.array([[1, 0], [0, 1]])
147
148 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=1)
149 xt = xs[::-1].copy()
150
151 p = ot.unif(n_samples)
152 q = ot.unif(n_samples)
153 G0 = p[:, None] * q[None, :]
154
155 C1 = ot.dist(xs, xs)
156 C2 = ot.dist(xt, xt)
157
158 C1 /= C1.max()
159 C2 /= C2.max()
160 C1 = C1.astype(np.int32)
161 C1b, C2b, pb, qb, G0b = nx.from_numpy(C1, C2, p, q, G0)
162
163 G = ot.gromov.gromov_wasserstein(
164 C1,
165 C2,
166 None,
167 q,
168 "square_loss",
169 G0=G0,
170 verbose=True,
171 alpha_min=0.0,
172 alpha_max=1.0,
173 )
174 Gb = nx.to_numpy(
175 ot.gromov.gromov_wasserstein(
176 C1b, C2b, pb, None, "square_loss", symmetric=True, G0=G0b, verbose=True
177 )
178 )
179
180 # check constraints
181 np.testing.assert_allclose(G, Gb, atol=1e-06)
182 np.testing.assert_allclose(G, 0.0, atol=1e-09)
183
184
185 def test_gromov_dtype_device(nx):
186 # setup
187 n_samples = 20 # nb samples
188
189 mu_s = np.array([0, 0])
190 cov_s = np.array([[1, 0], [0, 1]])
191
192 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=4)
193
194 xt = xs[::-1].copy()
195
196 p = ot.unif(n_samples)
197 q = ot.unif(n_samples)
198 G0 = p[:, None] * q[None, :]
199
200 C1 = ot.dist(xs, xs)
201 C2 = ot.dist(xt, xt)
202
203 C1 /= C1.max()
204 C2 /= C2.max()
205
206 for tp in nx.__type_list__:
207 print(nx.dtype_device(tp))
208
209 C1b, C2b, pb, qb, G0b = nx.from_numpy(C1, C2, p, q, G0, type_as=tp)
210
211 with warnings.catch_warnings():
212 warnings.filterwarnings("error")
213 Gb = ot.gromov.gromov_wasserstein(
214 C1b, C2b, pb, qb, "square_loss", G0=G0b, verbose=True
215 )
216 gw_valb = ot.gromov.gromov_wasserstein2(
217 C1b, C2b, pb, qb, "kl_loss", armijo=True, G0=G0b, log=False
218 )
219
220 nx.assert_same_dtype_device(C1b, Gb)
221 nx.assert_same_dtype_device(C1b, gw_valb)
222
223
224 @pytest.mark.skipif(not tf, reason="tf not installed")
225 def test_gromov_device_tf():
226 nx = ot.backend.TensorflowBackend()
227 n_samples = 20 # nb samples
228 mu_s = np.array([0, 0])
229 cov_s = np.array([[1, 0], [0, 1]])
230 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=4)
231 xt = xs[::-1].copy()
232 p = ot.unif(n_samples)
233 q = ot.unif(n_samples)
234 G0 = p[:, None] * q[None, :]
235 C1 = ot.dist(xs, xs)
236 C2 = ot.dist(xt, xt)
237 C1 /= C1.max()
238 C2 /= C2.max()
239
240 # Check that everything stays on the CPU
241 with tf.device("/CPU:0"):
242 C1b, C2b, pb, qb, G0b = nx.from_numpy(C1, C2, p, q, G0)
243 Gb = ot.gromov.gromov_wasserstein(
244 C1b, C2b, pb, qb, "square_loss", G0=G0b, verbose=True
245 )
246 gw_valb = ot.gromov.gromov_wasserstein2(
247 C1b, C2b, pb, qb, "kl_loss", armijo=True, G0=G0b, log=False
248 )
249 nx.assert_same_dtype_device(C1b, Gb)
250 nx.assert_same_dtype_device(C1b, gw_valb)
251
252 if len(tf.config.list_physical_devices("GPU")) > 0:
253 # Check that everything happens on the GPU
254 C1b, C2b, pb, qb, G0b = nx.from_numpy(C1, C2, p, q, G0)
255 Gb = ot.gromov.gromov_wasserstein(C1b, C2b, pb, qb, "square_loss", verbose=True)
256 gw_valb = ot.gromov.gromov_wasserstein2(
257 C1b, C2b, pb, qb, "kl_loss", armijo=True, log=False
258 )
259 nx.assert_same_dtype_device(C1b, Gb)
260 nx.assert_same_dtype_device(C1b, gw_valb)
261 assert nx.dtype_device(Gb)[1].startswith("GPU")
262
263
264 def test_gromov2_gradients():
265 n_samples = 20 # nb samples
266
267 mu_s = np.array([0, 0])
268 cov_s = np.array([[1, 0], [0, 1]])
269
270 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=4)
271
272 xt = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=5)
273
274 p = ot.unif(n_samples)
275 q = ot.unif(n_samples)
276
277 C1 = ot.dist(xs, xs)
278 C2 = ot.dist(xt, xt)
279
280 C1 /= C1.max()
281 C2 /= C2.max()
282
283 if torch:
284 devices = [torch.device("cpu")]
285 if torch.cuda.is_available():
286 devices.append(torch.device("cuda"))
287 for device in devices:
288 # classical gradients
289 p1 = torch.tensor(p, requires_grad=True, device=device)
290 q1 = torch.tensor(q, requires_grad=True, device=device)
291 C11 = torch.tensor(C1, requires_grad=True, device=device)
292 C12 = torch.tensor(C2, requires_grad=True, device=device)
293
294 # Test with exact line-search
295 val = ot.gromov_wasserstein2(C11, C12, p1, q1)
296
297 val.backward()
298
299 assert val.device == p1.device
300 assert q1.shape == q1.grad.shape
301 assert p1.shape == p1.grad.shape
302 assert C11.shape == C11.grad.shape
303 assert C12.shape == C12.grad.shape
304
305 # Test with armijo line-search
306 # classical gradients
307 p1 = torch.tensor(p, requires_grad=True, device=device)
308 q1 = torch.tensor(q, requires_grad=True, device=device)
309 C11 = torch.tensor(C1, requires_grad=True, device=device)
310 C12 = torch.tensor(C2, requires_grad=True, device=device)
311
312 q1.grad = None
313 p1.grad = None
314 C11.grad = None
315 C12.grad = None
316 val = ot.gromov_wasserstein2(C11, C12, p1, q1, armijo=True)
317
318 val.backward()
319
320 assert val.device == p1.device
321 assert q1.shape == q1.grad.shape
322 assert p1.shape == p1.grad.shape
323 assert C11.shape == C11.grad.shape
324 assert C12.shape == C12.grad.shape
325
326
327 def test_gw_helper_backend(nx):
328 n_samples = 10 # nb samples
329
330 mu = np.array([0, 0])
331 cov = np.array([[1, 0], [0, 1]])
332
333 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=0)
334 xt = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=1)
335
336 p = ot.unif(n_samples)
337 q = ot.unif(n_samples)
338 G0 = p[:, None] * q[None, :]
339
340 C1 = ot.dist(xs, xs)
341 C2 = ot.dist(xt, xt)
342
343 C1 /= C1.max()
344 C2 /= C2.max()
345
346 C1b, C2b, pb, qb, G0b = nx.from_numpy(C1, C2, p, q, G0)
347 Gb, logb = ot.gromov.gromov_wasserstein(
348 C1b, C2b, pb, qb, "square_loss", armijo=False, symmetric=True, G0=G0b, log=True
349 )
350
351 # calls with nx=None
352 constCb, hC1b, hC2b = ot.gromov.init_matrix(
353 C1b, C2b, pb, qb, loss_fun="square_loss"
354 )
355
356 def f(G):
357 return ot.gromov.gwloss(constCb, hC1b, hC2b, G, None)
358
359 def df(G):
360 return ot.gromov.gwggrad(constCb, hC1b, hC2b, G, None)
361
362 def line_search(cost, G, deltaG, Mi, cost_G, df_G):
363 return ot.gromov.solve_gromov_linesearch(
364 G, deltaG, cost_G, C1b, C2b, M=0.0, reg=1.0, nx=None
365 )
366
367 # feed the precomputed local optimum Gb to cg
368 res, log = ot.optim.cg(
369 pb,
370 qb,
371 0.0,
372 1.0,
373 f,
374 df,
375 Gb,
376 line_search,
377 log=True,
378 numItermax=1e4,
379 stopThr=1e-9,
380 stopThr2=1e-9,
381 )
382 # check constraints
383 np.testing.assert_allclose(res, Gb, atol=1e-06)
384
385
386 @pytest.mark.parametrize(
387 "loss_fun",
388 [
389 "square_loss",
390 "kl_loss",
391 pytest.param("unknown_loss", marks=pytest.mark.xfail(raises=ValueError)),
392 ],
393 )
394 def test_gw_helper_validation(loss_fun):
395 n_samples = 10 # nb samples
396 mu = np.array([0, 0])
397 cov = np.array([[1, 0], [0, 1]])
398 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=0)
399 xt = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=1)
400 p = ot.unif(n_samples)
401 q = ot.unif(n_samples)
402 C1 = ot.dist(xs, xs)
403 C2 = ot.dist(xt, xt)
404 ot.gromov.init_matrix(C1, C2, p, q, loss_fun=loss_fun)
405
406
407 def test_gromov_barycenter(nx):
408 ns = 5
409 nt = 8
410
411 Xs, ys = ot.datasets.make_data_classif("3gauss", ns, random_state=42)
412 Xt, yt = ot.datasets.make_data_classif("3gauss2", nt, random_state=42)
413
414 C1 = ot.dist(Xs)
415 C2 = ot.dist(Xt)
416 p1 = ot.unif(ns)
417 p2 = ot.unif(nt)
418 n_samples = 3
419 p = ot.unif(n_samples)
420
421 C1b, C2b, p1b, p2b, pb = nx.from_numpy(C1, C2, p1, p2, p)
422 with pytest.raises(ValueError):
423 stop_criterion = "unknown stop criterion"
424 Cb = ot.gromov.gromov_barycenters(
425 n_samples,
426 [C1, C2],
427 None,
428 p,
429 [0.5, 0.5],
430 "square_loss",
431 max_iter=10,
432 tol=1e-3,
433 stop_criterion=stop_criterion,
434 verbose=False,
435 random_state=42,
436 )
437
438 for stop_criterion in ["barycenter", "loss"]:
439 Cb = ot.gromov.gromov_barycenters(
440 n_samples,
441 [C1, C2],
442 None,
443 p,
444 [0.5, 0.5],
445 "square_loss",
446 max_iter=10,
447 tol=1e-3,
448 stop_criterion=stop_criterion,
449 verbose=False,
450 random_state=42,
451 )
452 Cbb = nx.to_numpy(
453 ot.gromov.gromov_barycenters(
454 n_samples,
455 [C1b, C2b],
456 [p1b, p2b],
457 None,
458 [0.5, 0.5],
459 "square_loss",
460 max_iter=10,
461 tol=1e-3,
462 stop_criterion=stop_criterion,
463 verbose=False,
464 random_state=42,
465 )
466 )
467 np.testing.assert_allclose(Cb, Cbb, atol=1e-06)
468 np.testing.assert_allclose(Cbb.shape, (n_samples, n_samples))
469
470 # test of gromov_barycenters with `log` on
471 Cb_, err_ = ot.gromov.gromov_barycenters(
472 n_samples,
473 [C1, C2],
474 [p1, p2],
475 p,
476 None,
477 "square_loss",
478 max_iter=10,
479 tol=1e-3,
480 stop_criterion=stop_criterion,
481 verbose=False,
482 warmstartT=True,
483 random_state=42,
484 log=True,
485 )
486 Cbb_, errb_ = ot.gromov.gromov_barycenters(
487 n_samples,
488 [C1b, C2b],
489 [p1b, p2b],
490 pb,
491 [0.5, 0.5],
492 "square_loss",
493 max_iter=10,
494 tol=1e-3,
495 stop_criterion=stop_criterion,
496 verbose=False,
497 warmstartT=True,
498 random_state=42,
499 log=True,
500 )
501 Cbb_ = nx.to_numpy(Cbb_)
502 np.testing.assert_allclose(Cb_, Cbb_, atol=1e-06)
503 np.testing.assert_array_almost_equal(err_["err"], nx.to_numpy(*errb_["err"]))
504 np.testing.assert_allclose(Cbb_.shape, (n_samples, n_samples))
505
506 Cb2 = ot.gromov.gromov_barycenters(
507 n_samples,
508 [C1, C2],
509 [p1, p2],
510 p,
511 [0.5, 0.5],
512 "kl_loss",
513 max_iter=10,
514 tol=1e-3,
515 warmstartT=True,
516 random_state=42,
517 )
518 Cb2b = nx.to_numpy(
519 ot.gromov.gromov_barycenters(
520 n_samples,
521 [C1b, C2b],
522 [p1b, p2b],
523 pb,
524 [0.5, 0.5],
525 "kl_loss",
526 max_iter=10,
527 tol=1e-3,
528 warmstartT=True,
529 random_state=42,
530 )
531 )
532 np.testing.assert_allclose(Cb2, Cb2b, atol=1e-06)
533 np.testing.assert_allclose(Cb2b.shape, (n_samples, n_samples))
534
535 # test of gromov_barycenters with `log` on
536 # providing init_C
537 generator = ot.utils.check_random_state(42)
538 xalea = generator.randn(n_samples, 2)
539 init_C = ot.utils.dist(xalea, xalea)
540 init_C /= init_C.max()
541 init_Cb = nx.from_numpy(init_C)
542
543 Cb2_, err2_ = ot.gromov.gromov_barycenters(
544 n_samples,
545 [C1, C2],
546 [p1, p2],
547 p,
548 [0.5, 0.5],
549 "kl_loss",
550 max_iter=10,
551 tol=1e-3,
552 verbose=False,
553 random_state=42,
554 log=True,
555 init_C=init_C,
556 )
557 Cb2b_, err2b_ = ot.gromov.gromov_barycenters(
558 n_samples,
559 [C1b, C2b],
560 [p1b, p2b],
561 pb,
562 [0.5, 0.5],
563 "kl_loss",
564 max_iter=10,
565 tol=1e-3,
566 verbose=True,
567 random_state=42,
568 init_C=init_Cb,
569 log=True,
570 )
571 Cb2b_ = nx.to_numpy(Cb2b_)
572 np.testing.assert_allclose(Cb2_, Cb2b_, atol=1e-06)
573 np.testing.assert_array_almost_equal(err2_["err"], nx.to_numpy(*err2b_["err"]))
574 np.testing.assert_allclose(Cb2b_.shape, (n_samples, n_samples))
575
576 # test edge cases for gw barycenters:
577 # C1 as list
578 with pytest.raises(ValueError):
579 C1_list = [list(c) for c in C1]
580 _ = ot.gromov.gromov_barycenters(
581 n_samples,
582 [C1_list],
583 None,
584 p,
585 None,
586 "square_loss",
587 max_iter=10,
588 tol=1e-3,
589 stop_criterion=stop_criterion,
590 verbose=False,
591 random_state=42,
592 )
593
594 # p1, p2 as lists
595 with pytest.raises(ValueError):
596 p1_list = list(p1)
597 p2_list = list(p2)
598 _ = ot.gromov.gromov_barycenters(
599 n_samples,
600 [C1, C2],
601 [p1_list, p2_list],
602 p,
603 None,
604 "square_loss",
605 max_iter=10,
606 tol=1e-3,
607 stop_criterion=stop_criterion,
608 verbose=False,
609 random_state=42,
610 )
611
612 # unique input structure
613 Cb = ot.gromov.gromov_barycenters(
614 n_samples,
615 [C1],
616 None,
617 p,
618 None,
619 "square_loss",
620 max_iter=10,
621 tol=1e-3,
622 stop_criterion=stop_criterion,
623 verbose=False,
624 random_state=42,
625 )
626 Cbb = nx.to_numpy(
627 ot.gromov.gromov_barycenters(
628 n_samples,
629 [C1b],
630 None,
631 None,
632 [1.0],
633 "square_loss",
634 max_iter=10,
635 tol=1e-3,
636 stop_criterion=stop_criterion,
637 verbose=False,
638 random_state=42,
639 )
640 )
641 np.testing.assert_allclose(Cb, Cbb, atol=1e-06)
642 np.testing.assert_allclose(Cbb.shape, (n_samples, n_samples))
643
644
645 def test_fgw(nx):
646 n_samples = 20 # nb samples
647
648 mu_s = np.array([0, 0])
649 cov_s = np.array([[1, 0], [0, 1]])
650
651 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=42)
652
653 xt = xs[::-1].copy()
654
655 rng = np.random.RandomState(42)
656 ys = rng.randn(xs.shape[0], 2)
657 yt = ys[::-1].copy()
658
659 p = ot.unif(n_samples)
660 q = ot.unif(n_samples)
661 G0 = p[:, None] * q[None, :]
662
663 C1 = ot.dist(xs, xs)
664 C2 = ot.dist(xt, xt)
665
666 C1 /= C1.max()
667 C2 /= C2.max()
668
669 M = ot.dist(ys, yt)
670 M /= M.max()
671
672 Mb, C1b, C2b, pb, qb, G0b = nx.from_numpy(M, C1, C2, p, q, G0)
673
674 G, log = ot.gromov.fused_gromov_wasserstein(
675 M,
676 C1,
677 C2,
678 None,
679 q,
680 "square_loss",
681 alpha=0.5,
682 armijo=True,
683 symmetric=None,
684 G0=G0,
685 log=True,
686 )
687 Gb, logb = ot.gromov.fused_gromov_wasserstein(
688 Mb,
689 C1b,
690 C2b,
691 pb,
692 None,
693 "square_loss",
694 alpha=0.5,
695 armijo=True,
696 symmetric=True,
697 G0=G0b,
698 log=True,
699 )
700 Gb = nx.to_numpy(Gb)
701
702 # check constraints
703 np.testing.assert_allclose(G, Gb, atol=1e-06)
704 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence fgw
705 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence fgw
706
707 Id = (1 / (1.0 * n_samples)) * np.eye(n_samples, n_samples)
708
709 np.testing.assert_allclose(Gb, np.flipud(Id), atol=1e-04) # cf convergence gromov
710
711 fgw, log = ot.gromov.fused_gromov_wasserstein2(
712 M,
713 C1,
714 C2,
715 p,
716 None,
717 "square_loss",
718 armijo=True,
719 symmetric=True,
720 G0=None,
721 alpha=0.5,
722 log=True,
723 )
724 fgwb, logb = ot.gromov.fused_gromov_wasserstein2(
725 Mb,
726 C1b,
727 C2b,
728 None,
729 qb,
730 "square_loss",
731 armijo=True,
732 symmetric=None,
733 G0=G0b,
734 alpha=0.5,
735 log=True,
736 )
737 fgwb = nx.to_numpy(fgwb)
738
739 G = log["T"]
740 Gb = nx.to_numpy(logb["T"])
741
742 np.testing.assert_allclose(fgw, fgwb, atol=1e-08)
743 np.testing.assert_allclose(fgwb, 0, atol=1e-1, rtol=1e-1)
744
745 # check constraints
746 np.testing.assert_allclose(G, Gb, atol=1e-06)
747 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
748 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
749
750
751 def test_asymmetric_fgw(nx):
752 n_samples = 20 # nb samples
753 rng = np.random.RandomState(0)
754 C1 = rng.uniform(low=0.0, high=10, size=(n_samples, n_samples))
755 idx = np.arange(n_samples)
756 rng.shuffle(idx)
757 C2 = C1[idx, :][:, idx]
758
759 # add features
760 F1 = rng.uniform(low=0.0, high=10, size=(n_samples, 1))
761 F2 = F1[idx, :]
762 p = ot.unif(n_samples)
763 q = ot.unif(n_samples)
764 G0 = p[:, None] * q[None, :]
765
766 M = ot.dist(F1, F2)
767 Mb, C1b, C2b, pb, qb, G0b = nx.from_numpy(M, C1, C2, p, q, G0)
768
769 G, log = ot.gromov.fused_gromov_wasserstein(
770 M,
771 C1,
772 C2,
773 p,
774 q,
775 "square_loss",
776 alpha=0.5,
777 G0=G0,
778 log=True,
779 symmetric=False,
780 verbose=True,
781 )
782 Gb, logb = ot.gromov.fused_gromov_wasserstein(
783 Mb,
784 C1b,
785 C2b,
786 pb,
787 qb,
788 "square_loss",
789 alpha=0.5,
790 log=True,
791 symmetric=None,
792 G0=G0b,
793 verbose=True,
794 )
795 Gb = nx.to_numpy(Gb)
796 # check constraints
797 np.testing.assert_allclose(G, Gb, atol=1e-06)
798 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
799 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
800
801 np.testing.assert_allclose(log["fgw_dist"], 0.0, atol=1e-04)
802 np.testing.assert_allclose(logb["fgw_dist"], 0.0, atol=1e-04)
803
804 fgw, log = ot.gromov.fused_gromov_wasserstein2(
805 M,
806 C1,
807 C2,
808 p,
809 q,
810 "square_loss",
811 alpha=0.5,
812 G0=G0,
813 log=True,
814 symmetric=None,
815 verbose=True,
816 )
817 fgwb, logb = ot.gromov.fused_gromov_wasserstein2(
818 Mb,
819 C1b,
820 C2b,
821 pb,
822 qb,
823 "square_loss",
824 alpha=0.5,
825 log=True,
826 symmetric=False,
827 G0=G0b,
828 verbose=True,
829 )
830
831 G = log["T"]
832 Gb = nx.to_numpy(logb["T"])
833 # check constraints
834 np.testing.assert_allclose(G, Gb, atol=1e-06)
835 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
836 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
837
838 np.testing.assert_allclose(log["fgw_dist"], 0.0, atol=1e-04)
839 np.testing.assert_allclose(logb["fgw_dist"], 0.0, atol=1e-04)
840
841 # Tests with kl-loss:
842 for armijo in [False, True]:
843 G, log = ot.gromov.fused_gromov_wasserstein(
844 M,
845 C1,
846 C2,
847 p,
848 q,
849 "kl_loss",
850 alpha=0.5,
851 armijo=armijo,
852 G0=G0,
853 log=True,
854 symmetric=False,
855 verbose=True,
856 )
857 Gb, logb = ot.gromov.fused_gromov_wasserstein(
858 Mb,
859 C1b,
860 C2b,
861 pb,
862 qb,
863 "kl_loss",
864 alpha=0.5,
865 armijo=armijo,
866 log=True,
867 symmetric=None,
868 G0=G0b,
869 verbose=True,
870 )
871 Gb = nx.to_numpy(Gb)
872 # check constraints
873 np.testing.assert_allclose(G, Gb, atol=1e-06)
874 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
875 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
876
877 np.testing.assert_allclose(log["fgw_dist"], 0.0, atol=1e-04)
878 np.testing.assert_allclose(logb["fgw_dist"], 0.0, atol=1e-04)
879
880 fgw, log = ot.gromov.fused_gromov_wasserstein2(
881 M,
882 C1,
883 C2,
884 p,
885 q,
886 "kl_loss",
887 alpha=0.5,
888 G0=G0,
889 log=True,
890 symmetric=None,
891 verbose=True,
892 )
893 fgwb, logb = ot.gromov.fused_gromov_wasserstein2(
894 Mb,
895 C1b,
896 C2b,
897 pb,
898 qb,
899 "kl_loss",
900 alpha=0.5,
901 log=True,
902 symmetric=False,
903 G0=G0b,
904 verbose=True,
905 )
906
907 G = log["T"]
908 Gb = nx.to_numpy(logb["T"])
909 # check constraints
910 np.testing.assert_allclose(G, Gb, atol=1e-06)
911 np.testing.assert_allclose(p, Gb.sum(1), atol=1e-04) # cf convergence gromov
912 np.testing.assert_allclose(q, Gb.sum(0), atol=1e-04) # cf convergence gromov
913
914 np.testing.assert_allclose(log["fgw_dist"], 0.0, atol=1e-04)
915 np.testing.assert_allclose(logb["fgw_dist"], 0.0, atol=1e-04)
916
917
918 def test_fgw_integer_warnings(nx):
919 n_samples = 20 # nb samples
920 rng = np.random.RandomState(0)
921 C1 = rng.uniform(low=0.0, high=10, size=(n_samples, n_samples))
922 idx = np.arange(n_samples)
923 rng.shuffle(idx)
924 C2 = C1[idx, :][:, idx]
925
926 # add features
927 F1 = rng.uniform(low=0.0, high=10, size=(n_samples, 1))
928 F2 = F1[idx, :]
929 p = ot.unif(n_samples)
930 q = ot.unif(n_samples)
931 G0 = p[:, None] * q[None, :]
932
933 M = ot.dist(F1, F2).astype(np.int32)
934 Mb, C1b, C2b, pb, qb, G0b = nx.from_numpy(M, C1, C2, p, q, G0)
935
936 G, log = ot.gromov.fused_gromov_wasserstein(
937 M,
938 C1,
939 C2,
940 p,
941 q,
942 "square_loss",
943 alpha=0.5,
944 G0=G0,
945 log=True,
946 symmetric=False,
947 verbose=True,
948 )
949 Gb, logb = ot.gromov.fused_gromov_wasserstein(
950 Mb,
951 C1b,
952 C2b,
953 pb,
954 qb,
955 "square_loss",
956 alpha=0.5,
957 log=True,
958 symmetric=None,
959 G0=G0b,
960 verbose=True,
961 )
962 Gb = nx.to_numpy(Gb)
963 # check constraints
964 np.testing.assert_allclose(G, Gb, atol=1e-06)
965 np.testing.assert_allclose(G, 0.0, atol=1e-06)
966
967
968 def test_fgw2_gradients():
969 n_samples = 20 # nb samples
970
971 mu_s = np.array([0, 0])
972 cov_s = np.array([[1, 0], [0, 1]])
973
974 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=4)
975
976 xt = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=5)
977
978 p = ot.unif(n_samples)
979 q = ot.unif(n_samples)
980
981 C1 = ot.dist(xs, xs)
982 C2 = ot.dist(xt, xt)
983 M = ot.dist(xs, xt)
984
985 C1 /= C1.max()
986 C2 /= C2.max()
987
988 if torch:
989 devices = [torch.device("cpu")]
990 if torch.cuda.is_available():
991 devices.append(torch.device("cuda"))
992 for device in devices:
993 p1 = torch.tensor(p, requires_grad=True, device=device)
994 q1 = torch.tensor(q, requires_grad=True, device=device)
995 C11 = torch.tensor(C1, requires_grad=True, device=device)
996 C12 = torch.tensor(C2, requires_grad=True, device=device)
997 M1 = torch.tensor(M, requires_grad=True, device=device)
998
999 val = ot.fused_gromov_wasserstein2(M1, C11, C12, p1, q1)
1000
1001 val.backward()
1002
1003 assert val.device == p1.device
1004 assert q1.shape == q1.grad.shape
1005 assert p1.shape == p1.grad.shape
1006 assert C11.shape == C11.grad.shape
1007 assert C12.shape == C12.grad.shape
1008 assert M1.shape == M1.grad.shape
1009
1010 # full gradients with alpha
1011 p1 = torch.tensor(p, requires_grad=True, device=device)
1012 q1 = torch.tensor(q, requires_grad=True, device=device)
1013 C11 = torch.tensor(C1, requires_grad=True, device=device)
1014 C12 = torch.tensor(C2, requires_grad=True, device=device)
1015 M1 = torch.tensor(M, requires_grad=True, device=device)
1016 alpha = torch.tensor(0.5, requires_grad=True, device=device)
1017
1018 val = ot.fused_gromov_wasserstein2(M1, C11, C12, p1, q1, alpha=alpha)
1019
1020 val.backward()
1021
1022 assert val.device == p1.device
1023 assert q1.shape == q1.grad.shape
1024 assert p1.shape == p1.grad.shape
1025 assert C11.shape == C11.grad.shape
1026 assert C12.shape == C12.grad.shape
1027 assert alpha.shape == alpha.grad.shape
1028
1029
1030 def test_fgw_helper_backend(nx):
1031 n_samples = 20 # nb samples
1032
1033 mu = np.array([0, 0])
1034 cov = np.array([[1, 0], [0, 1]])
1035
1036 rng = np.random.RandomState(42)
1037 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=0)
1038 ys = rng.randn(xs.shape[0], 2)
1039 xt = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=1)
1040 yt = rng.randn(xt.shape[0], 2)
1041
1042 p = ot.unif(n_samples)
1043 q = ot.unif(n_samples)
1044 G0 = p[:, None] * q[None, :]
1045
1046 C1 = ot.dist(xs, xs)
1047 C2 = ot.dist(xt, xt)
1048
1049 C1 /= C1.max()
1050 C2 /= C2.max()
1051
1052 M = ot.dist(ys, yt)
1053 M /= M.max()
1054
1055 Mb, C1b, C2b, pb, qb, G0b = nx.from_numpy(M, C1, C2, p, q, G0)
1056 alpha = 0.5
1057 Gb, logb = ot.gromov.fused_gromov_wasserstein(
1058 Mb,
1059 C1b,
1060 C2b,
1061 pb,
1062 qb,
1063 "square_loss",
1064 alpha=0.5,
1065 armijo=False,
1066 symmetric=True,
1067 G0=G0b,
1068 log=True,
1069 )
1070
1071 # calls with nx=None
1072 constCb, hC1b, hC2b = ot.gromov.init_matrix(
1073 C1b, C2b, pb, qb, loss_fun="square_loss"
1074 )
1075
1076 def f(G):
1077 return ot.gromov.gwloss(constCb, hC1b, hC2b, G, None)
1078
1079 def df(G):
1080 return ot.gromov.gwggrad(constCb, hC1b, hC2b, G, None)
1081
1082 def line_search(cost, G, deltaG, Mi, cost_G, df_G):
1083 return ot.gromov.solve_gromov_linesearch(
1084 G, deltaG, cost_G, C1b, C2b, M=(1 - alpha) * Mb, reg=alpha, nx=None
1085 )
1086
1087 # feed the precomputed local optimum Gb to cg
1088 res, log = ot.optim.cg(
1089 pb,
1090 qb,
1091 (1 - alpha) * Mb,
1092 alpha,
1093 f,
1094 df,
1095 Gb,
1096 line_search,
1097 log=True,
1098 numItermax=1e4,
1099 stopThr=1e-9,
1100 stopThr2=1e-9,
1101 )
1102
1103 def line_search(cost, G, deltaG, Mi, cost_G, df_G):
1104 return ot.optim.line_search_armijo(cost, G, deltaG, Mi, cost_G, nx=None)
1105
1106 # feed the precomputed local optimum Gb to cg
1107 res_armijo, log_armijo = ot.optim.cg(
1108 pb,
1109 qb,
1110 (1 - alpha) * Mb,
1111 alpha,
1112 f,
1113 df,
1114 Gb,
1115 line_search,
1116 log=True,
1117 numItermax=1e4,
1118 stopThr=1e-9,
1119 stopThr2=1e-9,
1120 )
1121 # check constraints
1122 np.testing.assert_allclose(res, Gb, atol=1e-06)
1123 np.testing.assert_allclose(res_armijo, Gb, atol=1e-06)
1124
1125
1126 def test_fgw_barycenter(nx):
1127 ns = 10
1128 nt = 20
1129
1130 Xs, ys = ot.datasets.make_data_classif("3gauss", ns, random_state=42)
1131 Xt, yt = ot.datasets.make_data_classif("3gauss2", nt, random_state=42)
1132
1133 rng = np.random.RandomState(42)
1134 ys = rng.randn(Xs.shape[0], 2)
1135 yt = rng.randn(Xt.shape[0], 2)
1136
1137 C1 = ot.dist(Xs)
1138 C2 = ot.dist(Xt)
1139 C1 /= C1.max()
1140 C2 /= C2.max()
1141
1142 p1, p2 = ot.unif(ns), ot.unif(nt)
1143 n_samples = 3
1144 p = ot.unif(n_samples)
1145
1146 ysb, ytb, C1b, C2b, p1b, p2b, pb = nx.from_numpy(ys, yt, C1, C2, p1, p2, p)
1147 lambdas = [0.5, 0.5]
1148 Csb = [C1b, C2b]
1149 Ysb = [ysb, ytb]
1150 Xb, Cb, logb = ot.gromov.fgw_barycenters(
1151 n_samples,
1152 Ysb,
1153 Csb,
1154 None,
1155 lambdas,
1156 0.5,
1157 fixed_structure=False,
1158 fixed_features=False,
1159 p=pb,
1160 loss_fun="square_loss",
1161 max_iter=10,
1162 tol=1e-3,
1163 random_state=12345,
1164 log=True,
1165 )
1166 # test correspondance with utils function
1167 recovered_Cb = ot.gromov.update_barycenter_structure(
1168 logb["Ts_iter"][-1], Csb, lambdas, pb, target=False, check_zeros=True
1169 )
1170 recovered_Xb = ot.gromov.update_barycenter_feature(
1171 logb["Ts_iter"][-1], Ysb, lambdas, pb, target=False, check_zeros=True
1172 )
1173
1174 np.testing.assert_allclose(Cb, recovered_Cb)
1175 np.testing.assert_allclose(Xb, recovered_Xb)
1176
1177 xalea = rng.randn(n_samples, 2)
1178 init_C = ot.dist(xalea, xalea)
1179 init_C /= init_C.max()
1180 init_Cb = nx.from_numpy(init_C)
1181
1182 with pytest.raises(
1183 ot.utils.UndefinedParameter
1184 ): # to raise an error when `fixed_structure=True`and `init_C=None`
1185 Xb, Cb = ot.gromov.fgw_barycenters(
1186 n_samples,
1187 Ysb,
1188 Csb,
1189 ps=[p1b, p2b],
1190 lambdas=None,
1191 alpha=0.5,
1192 fixed_structure=True,
1193 init_C=None,
1194 fixed_features=False,
1195 p=None,
1196 loss_fun="square_loss",
1197 max_iter=10,
1198 tol=1e-3,
1199 )
1200
1201 Xb, Cb = ot.gromov.fgw_barycenters(
1202 n_samples,
1203 [ysb, ytb],
1204 [C1b, C2b],
1205 ps=[p1b, p2b],
1206 lambdas=None,
1207 alpha=0.5,
1208 fixed_structure=True,
1209 init_C=init_Cb,
1210 fixed_features=False,
1211 p=None,
1212 loss_fun="square_loss",
1213 max_iter=10,
1214 tol=1e-3,
1215 )
1216 Xb, Cb = nx.to_numpy(Xb), nx.to_numpy(Cb)
1217 np.testing.assert_allclose(Cb.shape, (n_samples, n_samples))
1218 np.testing.assert_allclose(Xb.shape, (n_samples, ys.shape[1]))
1219
1220 init_X = rng.randn(n_samples, ys.shape[1])
1221 init_Xb = nx.from_numpy(init_X)
1222
1223 with pytest.raises(
1224 ot.utils.UndefinedParameter
1225 ): # to raise an error when `fixed_features=True`and `init_X=None`
1226 Xb, Cb, logb = ot.gromov.fgw_barycenters(
1227 n_samples,
1228 [ysb, ytb],
1229 [C1b, C2b],
1230 [p1b, p2b],
1231 [0.5, 0.5],
1232 0.5,
1233 fixed_structure=False,
1234 fixed_features=True,
1235 init_X=None,
1236 p=pb,
1237 loss_fun="square_loss",
1238 max_iter=10,
1239 tol=1e-3,
1240 warmstartT=True,
1241 log=True,
1242 random_state=98765,
1243 verbose=True,
1244 )
1245 Xb, Cb, logb = ot.gromov.fgw_barycenters(
1246 n_samples,
1247 [ysb, ytb],
1248 [C1b, C2b],
1249 [p1b, p2b],
1250 [0.5, 0.5],
1251 0.5,
1252 fixed_structure=False,
1253 fixed_features=True,
1254 init_X=init_Xb,
1255 p=pb,
1256 loss_fun="square_loss",
1257 max_iter=10,
1258 tol=1e-3,
1259 warmstartT=True,
1260 log=True,
1261 random_state=98765,
1262 verbose=True,
1263 )
1264
1265 X, C = nx.to_numpy(Xb), nx.to_numpy(Cb)
1266 np.testing.assert_allclose(C.shape, (n_samples, n_samples))
1267 np.testing.assert_allclose(X.shape, (n_samples, ys.shape[1]))
1268
1269 # add test with 'kl_loss'
1270 with pytest.raises(ValueError):
1271 stop_criterion = "unknown stop criterion"
1272 X, C, log = ot.gromov.fgw_barycenters(
1273 n_samples,
1274 [ys, yt],
1275 [C1, C2],
1276 [p1, p2],
1277 [0.5, 0.5],
1278 0.5,
1279 fixed_structure=False,
1280 fixed_features=False,
1281 p=p,
1282 loss_fun="kl_loss",
1283 max_iter=10,
1284 tol=1e-3,
1285 stop_criterion=stop_criterion,
1286 init_C=C,
1287 init_X=X,
1288 warmstartT=True,
1289 random_state=12345,
1290 log=True,
1291 )
1292
1293 for stop_criterion in ["barycenter", "loss"]:
1294 X, C, log = ot.gromov.fgw_barycenters(
1295 n_samples,
1296 [ys, yt],
1297 [C1, C2],
1298 [p1, p2],
1299 [0.5, 0.5],
1300 0.5,
1301 fixed_structure=False,
1302 fixed_features=False,
1303 p=p,
1304 loss_fun="kl_loss",
1305 max_iter=10,
1306 tol=1e-3,
1307 stop_criterion=stop_criterion,
1308 init_C=C,
1309 init_X=X,
1310 warmstartT=True,
1311 random_state=12345,
1312 log=True,
1313 verbose=True,
1314 )
1315 np.testing.assert_allclose(C.shape, (n_samples, n_samples))
1316 np.testing.assert_allclose(X.shape, (n_samples, ys.shape[1]))
1317
1318 # test correspondance with utils function
1319 recovered_C = ot.gromov.update_barycenter_structure(
1320 log["T"],
1321 [C1, C2],
1322 lambdas,
1323 p,
1324 loss_fun="kl_loss",
1325 target=False,
1326 check_zeros=False,
1327 )
1328
1329 np.testing.assert_allclose(C, recovered_C)
1330
1331 # test edge cases for fgw barycenters:
1332 # C1 as list
1333 with pytest.raises(ValueError):
1334 C1b_list = [list(c) for c in C1b]
1335 _, _, _ = ot.gromov.fgw_barycenters(
1336 n_samples,
1337 [ysb],
1338 [C1b_list],
1339 [p1b],
1340 None,
1341 0.5,
1342 fixed_structure=False,
1343 fixed_features=False,
1344 p=pb,
1345 loss_fun="square_loss",
1346 max_iter=10,
1347 tol=1e-3,
1348 stop_criterion=stop_criterion,
1349 init_C=Cb,
1350 init_X=Xb,
1351 warmstartT=True,
1352 random_state=12345,
1353 log=True,
1354 verbose=True,
1355 )
1356
1357 # p1, p2 as lists
1358 with pytest.raises(ValueError):
1359 p1_list = list(p1)
1360 p2_list = list(p2)
1361 _, _, _ = ot.gromov.fgw_barycenters(
1362 n_samples,
1363 [ysb, ytb],
1364 [C1b, C2b],
1365 [p1_list, p2_list],
1366 None,
1367 0.5,
1368 fixed_structure=False,
1369 fixed_features=False,
1370 p=p,
1371 loss_fun="kl_loss",
1372 max_iter=10,
1373 tol=1e-3,
1374 stop_criterion=stop_criterion,
1375 init_C=Cb,
1376 init_X=Xb,
1377 warmstartT=True,
1378 random_state=12345,
1379 log=True,
1380 verbose=True,
1381 )
1382
1383 # unique input structure
1384 X, C = ot.gromov.fgw_barycenters(
1385 n_samples,
1386 [ys],
1387 [C1],
1388 [p1],
1389 None,
1390 0.5,
1391 fixed_structure=False,
1392 fixed_features=False,
1393 p=p,
1394 loss_fun="square_loss",
1395 max_iter=10,
1396 tol=1e-3,
1397 stop_criterion=stop_criterion,
1398 warmstartT=True,
1399 random_state=12345,
1400 log=False,
1401 verbose=False,
1402 )
1403 Xb, Cb = ot.gromov.fgw_barycenters(
1404 n_samples,
1405 [ysb],
1406 [C1b],
1407 [p1b],
1408 [1.0],
1409 0.5,
1410 fixed_structure=False,
1411 fixed_features=False,
1412 p=pb,
1413 loss_fun="square_loss",
1414 max_iter=10,
1415 tol=1e-3,
1416 stop_criterion=stop_criterion,
1417 warmstartT=True,
1418 random_state=12345,
1419 log=False,
1420 verbose=False,
1421 )
1422
1423 np.testing.assert_allclose(C, Cb, atol=1e-06)
1424 np.testing.assert_allclose(X, Xb, atol=1e-06)