Debian Codegraph @

test/test_sliced.py

raw symbols SCIP
1 """Tests for module sliced"""
2
3 # Author: Adrien Corenflos <[email protected]>
4 # Nicolas Courty <[email protected]>
5 #
6 # License: MIT License
7
8 import numpy as np
9 import pytest
10
11 import ot
12 from ot.sliced import get_random_projections
13 from ot.backend import tf, torch
14
15
16 def test_get_random_projections():
17 rng = np.random.RandomState(0)
18 projections = get_random_projections(1000, 50, rng)
19 np.testing.assert_almost_equal(np.sum(projections**2, 0), 1.0)
20
21
22 def test_sliced_same_dist():
23 n = 100
24 rng = np.random.RandomState(0)
25
26 x = rng.randn(n, 2)
27 u = ot.utils.unif(n)
28
29 res = ot.sliced_wasserstein_distance(x, x, u, u, 10, seed=rng)
30 np.testing.assert_almost_equal(res, 0.0)
31
32
33 def test_sliced_bad_shapes():
34 n = 100
35 rng = np.random.RandomState(0)
36
37 x = rng.randn(n, 2)
38 y = rng.randn(n, 4)
39 u = ot.utils.unif(n)
40
41 with pytest.raises(ValueError):
42 _ = ot.sliced_wasserstein_distance(x, y, u, u, 10, seed=rng)
43
44
45 def test_sliced_log():
46 n = 100
47 rng = np.random.RandomState(0)
48
49 x = rng.randn(n, 4)
50 y = rng.randn(n, 4)
51 u = ot.utils.unif(n)
52
53 res, log = ot.sliced_wasserstein_distance(x, y, u, u, 10, p=1, seed=rng, log=True)
54 assert len(log) == 2
55 projections = log["projections"]
56 projected_emds = log["projected_emds"]
57
58 assert projections.shape[1] == len(projected_emds) == 10
59 for emd in projected_emds:
60 assert emd > 0
61
62
63 def test_sliced_different_dists():
64 n = 100
65 rng = np.random.RandomState(0)
66
67 x = rng.randn(n, 2)
68 u = ot.utils.unif(n)
69 y = rng.randn(n, 2)
70
71 res = ot.sliced_wasserstein_distance(x, y, u, u, 10, seed=rng)
72 assert res > 0.0
73
74
75 def test_1d_sliced_equals_emd():
76 n = 100
77 m = 120
78 rng = np.random.RandomState(0)
79
80 x = rng.randn(n, 1)
81 a = rng.uniform(0, 1, n)
82 a /= a.sum()
83 y = rng.randn(m, 1)
84 u = ot.utils.unif(m)
85 res = ot.sliced_wasserstein_distance(x, y, a, u, 10, seed=42)
86 expected = ot.emd2_1d(x.squeeze(), y.squeeze(), a, u)
87 np.testing.assert_almost_equal(res**2, expected)
88
89
90 def test_max_sliced_same_dist():
91 n = 100
92 rng = np.random.RandomState(0)
93
94 x = rng.randn(n, 2)
95 u = ot.utils.unif(n)
96
97 res = ot.max_sliced_wasserstein_distance(x, x, u, u, 10, seed=rng)
98 np.testing.assert_almost_equal(res, 0.0)
99
100
101 def test_max_sliced_different_dists():
102 n = 100
103 rng = np.random.RandomState(0)
104
105 x = rng.randn(n, 2)
106 u = ot.utils.unif(n)
107 y = rng.randn(n, 2)
108
109 res, log = ot.max_sliced_wasserstein_distance(x, y, u, u, 10, seed=rng, log=True)
110 assert res > 0.0
111
112
113 def test_sliced_same_proj():
114 n_projections = 10
115 seed = 12
116 rng = np.random.RandomState(0)
117 X = rng.randn(8, 2)
118 Y = rng.randn(8, 2)
119 cost1, log1 = ot.sliced_wasserstein_distance(
120 X, Y, seed=seed, n_projections=n_projections, log=True
121 )
122 P = get_random_projections(X.shape[1], n_projections=10, seed=seed)
123 cost2, log2 = ot.sliced_wasserstein_distance(X, Y, projections=P, log=True)
124
125 assert np.allclose(log1["projections"], log2["projections"])
126 assert np.isclose(cost1, cost2)
127
128
129 def test_sliced_backend(nx):
130 n = 100
131 rng = np.random.RandomState(0)
132
133 x = rng.randn(n, 2)
134 y = rng.randn(2 * n, 2)
135
136 P = rng.randn(2, 20)
137 P = P / np.sqrt((P**2).sum(0, keepdims=True))
138
139 n_projections = 20
140
141 xb, yb, Pb = nx.from_numpy(x, y, P)
142
143 val0 = ot.sliced_wasserstein_distance(x, y, projections=P)
144
145 val = ot.sliced_wasserstein_distance(xb, yb, n_projections=n_projections, seed=0)
146 val2 = ot.sliced_wasserstein_distance(xb, yb, n_projections=n_projections, seed=0)
147
148 assert val > 0
149 assert val == val2
150
151 valb = nx.to_numpy(ot.sliced_wasserstein_distance(xb, yb, projections=Pb))
152
153 assert np.allclose(val0, valb)
154
155
156 def test_sliced_backend_type_devices(nx):
157 n = 100
158 rng = np.random.RandomState(0)
159
160 x = rng.randn(n, 2)
161 y = rng.randn(2 * n, 2)
162
163 P = rng.randn(2, 20)
164 P = P / np.sqrt((P**2).sum(0, keepdims=True))
165
166 for tp in nx.__type_list__:
167 print(nx.dtype_device(tp))
168
169 xb, yb, Pb = nx.from_numpy(x, y, P, type_as=tp)
170
171 valb = ot.sliced_wasserstein_distance(xb, yb, projections=Pb)
172
173 nx.assert_same_dtype_device(xb, valb)
174
175
176 @pytest.mark.skipif(not tf, reason="tf not installed")
177 def test_sliced_backend_device_tf():
178 nx = ot.backend.TensorflowBackend()
179 n = 100
180 rng = np.random.RandomState(0)
181 x = rng.randn(n, 2)
182 y = rng.randn(2 * n, 2)
183 P = rng.randn(2, 20)
184 P = P / np.sqrt((P**2).sum(0, keepdims=True))
185
186 # Check that everything stays on the CPU
187 with tf.device("/CPU:0"):
188 xb, yb, Pb = nx.from_numpy(x, y, P)
189 valb = ot.sliced_wasserstein_distance(xb, yb, projections=Pb)
190 nx.assert_same_dtype_device(xb, valb)
191
192 if len(tf.config.list_physical_devices("GPU")) > 0:
193 # Check that everything happens on the GPU
194 xb, yb, Pb = nx.from_numpy(x, y, P)
195 valb = ot.sliced_wasserstein_distance(xb, yb, projections=Pb)
196 nx.assert_same_dtype_device(xb, valb)
197 assert nx.dtype_device(valb)[1].startswith("GPU")
198
199
200 def test_max_sliced_backend(nx):
201 n = 100
202 rng = np.random.RandomState(0)
203
204 x = rng.randn(n, 2)
205 y = rng.randn(2 * n, 2)
206
207 P = rng.randn(2, 20)
208 P = P / np.sqrt((P**2).sum(0, keepdims=True))
209
210 n_projections = 20
211
212 xb, yb, Pb = nx.from_numpy(x, y, P)
213
214 val0 = ot.max_sliced_wasserstein_distance(x, y, projections=P)
215
216 val = ot.max_sliced_wasserstein_distance(
217 xb, yb, n_projections=n_projections, seed=0
218 )
219 val2 = ot.max_sliced_wasserstein_distance(
220 xb, yb, n_projections=n_projections, seed=0
221 )
222
223 assert val > 0
224 assert val == val2
225
226 valb = nx.to_numpy(ot.max_sliced_wasserstein_distance(xb, yb, projections=Pb))
227
228 assert np.allclose(val0, valb)
229
230
231 def test_max_sliced_backend_type_devices(nx):
232 n = 100
233 rng = np.random.RandomState(0)
234
235 x = rng.randn(n, 2)
236 y = rng.randn(2 * n, 2)
237
238 P = rng.randn(2, 20)
239 P = P / np.sqrt((P**2).sum(0, keepdims=True))
240
241 for tp in nx.__type_list__:
242 print(nx.dtype_device(tp))
243
244 xb, yb, Pb = nx.from_numpy(x, y, P, type_as=tp)
245
246 valb = ot.max_sliced_wasserstein_distance(xb, yb, projections=Pb)
247
248 nx.assert_same_dtype_device(xb, valb)
249
250
251 @pytest.mark.skipif(not tf, reason="tf not installed")
252 def test_max_sliced_backend_device_tf():
253 nx = ot.backend.TensorflowBackend()
254 n = 100
255 rng = np.random.RandomState(0)
256 x = rng.randn(n, 2)
257 y = rng.randn(2 * n, 2)
258 P = rng.randn(2, 20)
259 P = P / np.sqrt((P**2).sum(0, keepdims=True))
260
261 # Check that everything stays on the CPU
262 with tf.device("/CPU:0"):
263 xb, yb, Pb = nx.from_numpy(x, y, P)
264 valb = ot.max_sliced_wasserstein_distance(xb, yb, projections=Pb)
265 nx.assert_same_dtype_device(xb, valb)
266
267 if len(tf.config.list_physical_devices("GPU")) > 0:
268 # Check that everything happens on the GPU
269 xb, yb, Pb = nx.from_numpy(x, y, P)
270 valb = ot.max_sliced_wasserstein_distance(xb, yb, projections=Pb)
271 nx.assert_same_dtype_device(xb, valb)
272 assert nx.dtype_device(valb)[1].startswith("GPU")
273
274
275 def test_projections_stiefel():
276 rng = np.random.RandomState(0)
277
278 n_projs = 500
279 x = rng.randn(100, 3)
280 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
281
282 ssw, log = ot.sliced_wasserstein_sphere(
283 x, x, n_projections=n_projs, seed=rng, log=True
284 )
285
286 P = log["projections"]
287 P_T = np.transpose(P, [0, 2, 1])
288 np.testing.assert_almost_equal(
289 np.matmul(P_T, P), np.array([np.eye(2) for k in range(n_projs)])
290 )
291
292
293 def test_sliced_sphere_same_dist():
294 n = 100
295 rng = np.random.RandomState(0)
296
297 x = rng.randn(n, 3)
298 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
299 u = ot.utils.unif(n)
300
301 res = ot.sliced_wasserstein_sphere(x, x, u, u, 10, seed=rng)
302 np.testing.assert_almost_equal(res, 0.0)
303
304
305 def test_sliced_sphere_same_proj():
306 n_projections = 10
307 n = 100
308 rng = np.random.RandomState(0)
309
310 x = rng.randn(n, 3)
311 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
312
313 y = rng.randn(n, 3)
314 y = y / np.sqrt(np.sum(y**2, -1, keepdims=True))
315
316 seed = 42
317
318 cost1, log1 = ot.sliced_wasserstein_sphere(
319 x, y, seed=seed, n_projections=n_projections, log=True
320 )
321 cost2, log2 = ot.sliced_wasserstein_sphere(
322 x, y, seed=seed, n_projections=n_projections, log=True
323 )
324
325 assert np.allclose(log1["projections"], log2["projections"])
326 assert np.isclose(cost1, cost2)
327
328
329 def test_sliced_sphere_bad_shapes():
330 n = 100
331 rng = np.random.RandomState(0)
332
333 x = rng.randn(n, 3)
334 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
335
336 y = rng.randn(n, 4)
337 y = y / np.sqrt(np.sum(x**2, -1, keepdims=True))
338
339 u = ot.utils.unif(n)
340
341 with pytest.raises(ValueError):
342 _ = ot.sliced_wasserstein_sphere(x, y, u, u, 10, seed=rng)
343
344
345 def test_sliced_sphere_values_on_the_sphere():
346 n = 100
347 rng = np.random.RandomState(0)
348
349 x = rng.randn(n, 3)
350 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
351
352 y = rng.randn(n, 4)
353
354 u = ot.utils.unif(n)
355
356 with pytest.raises(ValueError):
357 _ = ot.sliced_wasserstein_sphere(x, y, u, u, 10, seed=rng)
358
359
360 def test_sliced_sphere_log():
361 n = 100
362 rng = np.random.RandomState(0)
363
364 x = rng.randn(n, 4)
365 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
366 y = rng.randn(n, 4)
367 y = y / np.sqrt(np.sum(y**2, -1, keepdims=True))
368 u = ot.utils.unif(n)
369
370 res, log = ot.sliced_wasserstein_sphere(x, y, u, u, 10, p=1, seed=rng, log=True)
371 assert len(log) == 2
372 projections = log["projections"]
373 projected_emds = log["projected_emds"]
374
375 assert projections.shape[0] == len(projected_emds) == 10
376 for emd in projected_emds:
377 assert emd > 0
378
379
380 def test_sliced_sphere_different_dists():
381 n = 100
382 rng = np.random.RandomState(0)
383
384 x = rng.randn(n, 3)
385 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
386
387 u = ot.utils.unif(n)
388 y = rng.randn(n, 3)
389 y = y / np.sqrt(np.sum(y**2, -1, keepdims=True))
390
391 res = ot.sliced_wasserstein_sphere(x, y, u, u, 10, seed=rng)
392 assert res > 0.0
393
394
395 def test_1d_sliced_sphere_equals_emd():
396 n = 100
397 m = 120
398 rng = np.random.RandomState(0)
399
400 x = rng.randn(n, 2)
401 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
402 x_coords = (np.arctan2(-x[:, 1], -x[:, 0]) + np.pi) / (2 * np.pi)
403 a = rng.uniform(0, 1, n)
404 a /= a.sum()
405
406 y = rng.randn(m, 2)
407 y = y / np.sqrt(np.sum(y**2, -1, keepdims=True))
408 y_coords = (np.arctan2(-y[:, 1], -y[:, 0]) + np.pi) / (2 * np.pi)
409 u = ot.utils.unif(m)
410
411 res = ot.sliced_wasserstein_sphere(x, y, a, u, 10, seed=42, p=2)
412 expected = ot.binary_search_circle(x_coords.T, y_coords.T, a, u, p=2)
413
414 res1 = ot.sliced_wasserstein_sphere(x, y, a, u, 10, seed=42, p=1)
415 expected1 = ot.binary_search_circle(x_coords.T, y_coords.T, a, u, p=1)
416
417 np.testing.assert_almost_equal(res**2, expected)
418 np.testing.assert_almost_equal(res1, expected1, decimal=3)
419
420
421 @pytest.skip_backend("tf")
422 def test_sliced_sphere_backend_type_devices(nx):
423 n = 100
424 rng = np.random.RandomState(0)
425
426 x = rng.randn(n, 3)
427 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
428
429 y = rng.randn(2 * n, 3)
430 y = y / np.sqrt(np.sum(y**2, -1, keepdims=True))
431
432 sw_np, log = ot.sliced_wasserstein_sphere(x, y, log=True)
433 P = log["projections"]
434
435 for tp in nx.__type_list__:
436 print(nx.dtype_device(tp))
437
438 xb, yb = nx.from_numpy(x, y, type_as=tp)
439
440 valb = ot.sliced_wasserstein_sphere(
441 xb, yb, projections=nx.from_numpy(P, type_as=tp)
442 )
443
444 nx.assert_same_dtype_device(xb, valb)
445 np.testing.assert_almost_equal(sw_np, nx.to_numpy(valb))
446
447
448 def test_sliced_sphere_gradient():
449 if torch:
450 import torch.nn.functional as F
451
452 X0 = torch.randn((20, 3))
453 X0 = F.normalize(X0, p=2, dim=-1)
454 X0.requires_grad_(True)
455
456 X1 = torch.randn((20, 3))
457 X1 = F.normalize(X1, p=2, dim=-1)
458
459 sw = ot.sliced_wasserstein_sphere(X1, X0, n_projections=100, p=2)
460 grad_x0 = torch.autograd.grad(sw, X0)[0]
461
462 assert not torch.any(torch.isnan(grad_x0))
463
464
465 def test_sliced_sphere_unif_values_on_the_sphere():
466 n = 100
467 rng = np.random.RandomState(0)
468
469 x = rng.randn(n, 3)
470 u = ot.utils.unif(n)
471
472 with pytest.raises(ValueError):
473 _ = ot.sliced_wasserstein_sphere_unif(x, u, 10, seed=rng)
474
475
476 def test_sliced_sphere_unif_log():
477 n = 100
478 rng = np.random.RandomState(0)
479
480 x = rng.randn(n, 4)
481 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
482 u = ot.utils.unif(n)
483
484 res, log = ot.sliced_wasserstein_sphere_unif(x, u, 10, seed=rng, log=True)
485 assert len(log) == 2
486 projections = log["projections"]
487 projected_emds = log["projected_emds"]
488
489 assert projections.shape[0] == len(projected_emds) == 10
490 for emd in projected_emds:
491 assert emd > 0
492
493
494 def test_sliced_sphere_unif_backend_type_devices(nx):
495 n = 100
496 rng = np.random.RandomState(0)
497
498 x = rng.randn(n, 3)
499 x = x / np.sqrt(np.sum(x**2, -1, keepdims=True))
500
501 for tp in nx.__type_list__:
502 print(nx.dtype_device(tp))
503
504 xb = nx.from_numpy(x, type_as=tp)
505
506 valb = ot.sliced_wasserstein_sphere_unif(xb)
507
508 nx.assert_same_dtype_device(xb, valb)