Debian Codegraph @

test/gromov/test_partial.py

raw symbols SCIP
1 """Tests for gromov._partial.py"""
2
3 # Author:
4 # Laetitia Chapel <[email protected]>
5 # Cédric Vincent-Cuat <[email protected]>
6 #
7 # License: MIT License
8
9 import numpy as np
10 import scipy as sp
11 import ot
12 import pytest
13
14
15 def test_raise_errors():
16 n_samples = 20 # nb samples (gaussian)
17 n_noise = 20 # nb of samples (noise)
18
19 mu = np.array([0, 0])
20 cov = np.array([[1, 0], [0, 2]])
21
22 rng = np.random.RandomState(42)
23 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=rng)
24 xs = np.append(xs, (rng.rand(n_noise, 2) + 1) * 4).reshape((-1, 2))
25 xt = ot.datasets.make_2D_samples_gauss(n_samples, mu, cov, random_state=rng)
26 xt = np.append(xt, (rng.rand(n_noise, 2) + 1) * -3).reshape((-1, 2))
27
28 M = ot.dist(xs, xt)
29
30 p = ot.unif(n_samples + n_noise)
31 q = ot.unif(n_samples + n_noise)
32
33 with pytest.raises(ValueError):
34 ot.gromov.partial_gromov_wasserstein(M, M, p, q, m=2, log=True)
35
36 with pytest.raises(ValueError):
37 ot.gromov.partial_gromov_wasserstein(M, M, p, q, m=-1, log=True)
38
39 with pytest.raises(ValueError):
40 ot.gromov.entropic_partial_gromov_wasserstein(M, M, p, q, reg=1, m=2, log=True)
41
42 with pytest.raises(ValueError):
43 ot.gromov.entropic_partial_gromov_wasserstein(M, M, p, q, reg=1, m=-1, log=True)
44
45
46 def test_partial_gromov_wasserstein(nx):
47 rng = np.random.RandomState(42)
48 n_samples = 20 # nb samples
49 n_noise = 10 # nb of samples (noise)
50
51 p = ot.unif(n_samples + n_noise)
52 psub = ot.unif(n_samples - 5 + n_noise)
53 q = ot.unif(n_samples + n_noise)
54
55 mu_s = np.array([0, 0])
56 cov_s = np.array([[1, 0], [0, 1]])
57
58 mu_t = np.array([0, 0, 0])
59 cov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
60
61 # clean samples
62 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=rng)
63 P = sp.linalg.sqrtm(cov_t)
64 xt = rng.randn(n_samples, 3).dot(P) + mu_t
65 # add noise
66 xs = np.concatenate((xs, ((rng.rand(n_noise, 2) + 1) * 4)), axis=0)
67 xt = np.concatenate((xt, ((rng.rand(n_noise, 3) + 1) * 10)), axis=0)
68 xt2 = xs[::-1].copy()
69
70 C1 = ot.dist(xs, xs)
71 C1sub = ot.dist(xs[5:], xs[5:])
72
73 C2 = ot.dist(xt, xt)
74 C3 = ot.dist(xt2, xt2)
75
76 m = 2.0 / 3.0
77
78 C1b, C1subb, C2b, C3b, pb, psubb, qb = nx.from_numpy(C1, C1sub, C2, C3, p, psub, q)
79
80 G0 = (
81 np.outer(p, q) * m / (np.sum(p) * np.sum(q))
82 ) # make sure |G0|=m, G01_m\leq p, G0.T1_n\leq q.
83 G0b = nx.from_numpy(G0)
84
85 # check consistency across backends and stability w.r.t loss/marginals/sym
86 list_sym = [True, None]
87 for i, loss_fun in enumerate(["square_loss", "kl_loss"]):
88 res, log = ot.gromov.partial_gromov_wasserstein(
89 C1,
90 C3,
91 p=p,
92 q=None,
93 m=m,
94 loss_fun=loss_fun,
95 n_dummies=1,
96 G0=G0,
97 log=True,
98 symmetric=list_sym[i],
99 warn=True,
100 verbose=True,
101 )
102
103 resb, logb = ot.gromov.partial_gromov_wasserstein(
104 C1b,
105 C3b,
106 p=None,
107 q=qb,
108 m=m,
109 loss_fun=loss_fun,
110 n_dummies=1,
111 G0=G0b,
112 log=True,
113 symmetric=False,
114 warn=True,
115 verbose=True,
116 )
117
118 resb_ = nx.to_numpy(resb)
119 assert np.all(res.sum(1) <= p) # cf convergence wasserstein
120 assert np.all(res.sum(0) <= q) # cf convergence wasserstein
121
122 try:
123 # precision error while doubling numbers of computations with symmetric=False
124 # some instability can occur with kl. to investigate further.
125 # changing log offset in _transform_matrix was a way to solve it
126 # but it also negatively affects some other solvers in the API
127 np.testing.assert_allclose(res, resb_, rtol=1e-4)
128 except AssertionError:
129 pass
130
131 # tests with different number of samples across spaces
132 m = 2.0 / 3.0
133 res, log = ot.gromov.partial_gromov_wasserstein(
134 C1, C1sub, p=p, q=psub, m=m, log=True
135 )
136
137 resb, logb = ot.gromov.partial_gromov_wasserstein(
138 C1b, C1subb, p=pb, q=psubb, m=m, log=True
139 )
140
141 resb_ = nx.to_numpy(resb)
142 np.testing.assert_allclose(res, resb_, rtol=1e-4)
143 assert np.all(res.sum(1) <= p) # cf convergence wasserstein
144 assert np.all(res.sum(0) <= psub) # cf convergence wasserstein
145 np.testing.assert_allclose(np.sum(res), m, atol=1e-15)
146
147 # Edge cases - tests with m=1 set by default (coincide with gw)
148 m = 1
149 res0 = ot.gromov.partial_gromov_wasserstein(C1, C2, p, q, m=m, log=False)
150 res0b, log0b = ot.gromov.partial_gromov_wasserstein(
151 C1b, C2b, pb, qb, m=None, log=True
152 )
153 G = ot.gromov.gromov_wasserstein(C1, C2, p, q, "square_loss")
154 np.testing.assert_allclose(G, res0, rtol=1e-4)
155 np.testing.assert_allclose(res0b, res0, rtol=1e-4)
156
157 # tests for pGW2
158 for loss_fun in ["square_loss", "kl_loss"]:
159 w0, log0 = ot.gromov.partial_gromov_wasserstein2(
160 C1, C2, p=None, q=q, m=m, loss_fun=loss_fun, log=True
161 )
162 w0_val = ot.gromov.partial_gromov_wasserstein2(
163 C1b, C2b, p=pb, q=None, m=m, loss_fun=loss_fun, log=False
164 )
165 np.testing.assert_allclose(w0, w0_val, rtol=1e-4)
166
167 # tests integers
168 C1_int = C1.astype(int)
169 C1b_int = nx.from_numpy(C1_int)
170 C2_int = C2.astype(int)
171 C2b_int = nx.from_numpy(C2_int)
172
173 res0b, log0b = ot.gromov.partial_gromov_wasserstein(
174 C1b_int, C2b_int, pb, qb, m=m, log=True
175 )
176
177 assert nx.to_numpy(res0b).dtype == C1_int.dtype
178
179
180 def test_partial_partial_gromov_linesearch(nx):
181 rng = np.random.RandomState(42)
182 n_samples = 20 # nb samples
183 n_noise = 10 # nb of samples (noise)
184
185 p = ot.unif(n_samples + n_noise)
186 q = ot.unif(n_samples + n_noise)
187
188 mu_s = np.array([0, 0])
189 cov_s = np.array([[1, 0], [0, 1]])
190
191 mu_t = np.array([0, 0, 0])
192 cov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
193
194 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=rng)
195 xs = np.concatenate((xs, ((rng.rand(n_noise, 2) + 1) * 4)), axis=0)
196 P = sp.linalg.sqrtm(cov_t)
197 xt = rng.randn(n_samples, 3).dot(P) + mu_t
198 xt = np.concatenate((xt, ((rng.rand(n_noise, 3) + 1) * 10)), axis=0)
199 xt2 = xs[::-1].copy()
200
201 C1 = ot.dist(xs, xs)
202 C2 = ot.dist(xt, xt)
203 C3 = ot.dist(xt2, xt2)
204
205 m = 2.0 / 3.0
206
207 C1b, C2b, C3b, pb, qb = nx.from_numpy(C1, C2, C3, p, q)
208 G0 = (
209 np.outer(p, q) * m / (np.sum(p) * np.sum(q))
210 ) # make sure |G0|=m, G01_m\leq p, G0.T1_n\leq q.
211 G0b = nx.from_numpy(G0)
212
213 # computing necessary inputs to the line-search
214 Gb, _ = ot.gromov.partial_gromov_wasserstein(C1b, C2b, pb, qb, m=m, log=True)
215
216 deltaGb = Gb - G0b
217 fC1, fC2, hC1, hC2 = ot.gromov._utils._transform_matrix(C1b, C2b, "square_loss")
218 fC2t = fC2.T
219
220 ones_p = nx.ones(p.shape[0], type_as=pb)
221 ones_q = nx.ones(p.shape[0], type_as=pb)
222
223 constC1 = nx.outer(nx.dot(fC1, pb), ones_q)
224 constC2 = nx.outer(ones_p, nx.dot(qb, fC2t))
225 cost_G0b = ot.gromov.gwloss(constC1 + constC2, hC1, hC2, G0b)
226
227 df_G0b = ot.gromov.gwggrad(constC1 + constC2, hC1, hC2, G0b)
228 df_Gb = ot.gromov.gwggrad(constC1 + constC2, hC1, hC2, Gb)
229
230 # perform line-search
231 alpha, _, cost_Gb, _ = ot.gromov.solve_partial_gromov_linesearch(
232 G0b, deltaGb, cost_G0b, df_G0b, df_Gb, 0.0, 1.0, alpha_min=0.0, alpha_max=1.0
233 )
234
235 np.testing.assert_allclose(alpha, 1.0, rtol=1e-4)
236
237
238 @pytest.skip_backend("jax", reason="test very slow with jax backend")
239 @pytest.skip_backend("tf", reason="test very slow with tf backend")
240 def test_entropic_partial_gromov_wasserstein(nx):
241 rng = np.random.RandomState(42)
242 n_samples = 20 # nb samples
243 n_noise = 10 # nb of samples (noise)
244
245 p = ot.unif(n_samples + n_noise)
246 psub = ot.unif(n_samples - 5 + n_noise)
247 q = ot.unif(n_samples + n_noise)
248
249 mu_s = np.array([0, 0])
250 cov_s = np.array([[1, 0], [0, 1]])
251
252 mu_t = np.array([0, 0, 0])
253 cov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
254
255 # clean samples
256 xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s, random_state=rng)
257 P = sp.linalg.sqrtm(cov_t)
258 xt = rng.randn(n_samples, 3).dot(P) + mu_t
259 # add noise
260 xs = np.concatenate((xs, ((rng.rand(n_noise, 2) + 1) * 4)), axis=0)
261 xt = np.concatenate((xt, ((rng.rand(n_noise, 3) + 1) * 10)), axis=0)
262 xt2 = xs[::-1].copy()
263
264 C1 = ot.dist(xs, xs)
265 C1sub = ot.dist(xs[5:], xs[5:])
266
267 C2 = ot.dist(xt, xt)
268 C3 = ot.dist(xt2, xt2)
269
270 m = 2.0 / 3.0
271
272 C1b, C1subb, C2b, C3b, pb, psubb, qb = nx.from_numpy(C1, C1sub, C2, C3, p, psub, q)
273 G0 = (
274 np.outer(p, q) * m / (np.sum(p) * np.sum(q))
275 ) # make sure |G0|=m, G01_m\leq p, G0.T1_n\leq q.
276 G0b = nx.from_numpy(G0)
277
278 # check consistency across backends and stability w.r.t loss/marginals/sym
279 list_sym = [True, None]
280 for i, loss_fun in enumerate(["square_loss", "kl_loss"]):
281 res, log = ot.gromov.entropic_partial_gromov_wasserstein(
282 C1,
283 C3,
284 p=p,
285 q=None,
286 reg=1e4,
287 m=m,
288 loss_fun=loss_fun,
289 G0=None,
290 log=True,
291 symmetric=list_sym[i],
292 verbose=True,
293 )
294
295 resb, logb = ot.gromov.entropic_partial_gromov_wasserstein(
296 C1b,
297 C3b,
298 p=None,
299 q=qb,
300 reg=1e4,
301 m=m,
302 loss_fun=loss_fun,
303 G0=G0b,
304 log=True,
305 symmetric=False,
306 verbose=True,
307 )
308
309 resb_ = nx.to_numpy(resb)
310 try: # some instability can occur with kl. to investigate further.
311 np.testing.assert_allclose(res, resb_, rtol=1e-4)
312 except AssertionError:
313 pass
314
315 assert np.all(res.sum(1) <= p) # cf convergence wasserstein
316 assert np.all(res.sum(0) <= q) # cf convergence wasserstein
317
318 # tests with m is None
319 res = ot.gromov.entropic_partial_gromov_wasserstein(
320 C1,
321 C3,
322 p=p,
323 q=None,
324 reg=1e4,
325 G0=None,
326 log=False,
327 symmetric=list_sym[i],
328 verbose=True,
329 )
330
331 resb = ot.gromov.entropic_partial_gromov_wasserstein(
332 C1b,
333 C3b,
334 p=None,
335 q=qb,
336 reg=1e4,
337 G0=None,
338 log=False,
339 symmetric=False,
340 verbose=True,
341 )
342
343 resb_ = nx.to_numpy(resb)
344 np.testing.assert_allclose(res, resb_, rtol=1e-4)
345 np.testing.assert_allclose(np.sum(res), 1.0, rtol=1e-4)
346
347 # tests with different number of samples across spaces
348 m = 0.5
349 res, log = ot.gromov.entropic_partial_gromov_wasserstein(
350 C1, C1sub, p=p, q=psub, reg=1e4, m=m, log=True
351 )
352
353 resb, logb = ot.gromov.entropic_partial_gromov_wasserstein(
354 C1b, C1subb, p=pb, q=psubb, reg=1e4, m=m, log=True
355 )
356
357 resb_ = nx.to_numpy(resb)
358 np.testing.assert_allclose(res, resb_, rtol=1e-4)
359 assert np.all(res.sum(1) <= p) # cf convergence wasserstein
360 assert np.all(res.sum(0) <= psub) # cf convergence wasserstein
361 np.testing.assert_allclose(np.sum(res), m, rtol=1e-4)
362
363 # tests for pGW2
364 for loss_fun in ["square_loss", "kl_loss"]:
365 w0, log0 = ot.gromov.entropic_partial_gromov_wasserstein2(
366 C1, C2, p=None, q=q, reg=1e4, m=m, loss_fun=loss_fun, log=True
367 )
368 w0_val = ot.gromov.entropic_partial_gromov_wasserstein2(
369 C1b, C2b, p=pb, q=None, reg=1e4, m=m, loss_fun=loss_fun, log=False
370 )
371 np.testing.assert_allclose(w0, w0_val, rtol=1e-8)