Debian Codegraph @

ot/bregman/_convolutional.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Bregman projections solvers for entropic regularized Wasserstein convolutional barycenters
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 # Nicolas Courty <[email protected]>
8 #
9 # License: MIT License
10
11 import warnings
12
13 from ..utils import list_to_array
14 from ..backend import get_backend
15
16
17 def convolutional_barycenter2d(
18 A,
19 reg,
20 weights=None,
21 method="sinkhorn",
22 numItermax=10000,
23 stopThr=1e-4,
24 verbose=False,
25 log=False,
26 warn=True,
27 **kwargs,
28 ):
29 r"""Compute the entropic regularized wasserstein barycenter of distributions :math:`\mathbf{A}`
30 where :math:`\mathbf{A}` is a collection of 2D images.
31
32 The function solves the following optimization problem:
33
34 .. math::
35 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
36
37 where :
38
39 - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein
40 distance (see :py:func:`ot.bregman.sinkhorn`)
41 - :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions
42 of matrix :math:`\mathbf{A}`
43 - `reg` is the regularization strength scalar value
44
45 The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm
46 as proposed in :ref:`[21] <references-convolutional-barycenter-2d>`
47
48 Parameters
49 ----------
50 A : array-like, shape (n_hists, width, height)
51 `n` distributions (2D images) of size `width` x `height`
52 reg : float
53 Regularization term >0
54 weights : array-like, shape (n_hists,)
55 Weights of each image on the simplex (barycentric coordinates)
56 method : string, optional
57 method used for the solver either 'sinkhorn' or 'sinkhorn_log'
58 numItermax : int, optional
59 Max number of iterations
60 stopThr : float, optional
61 Stop threshold on error (> 0)
62 stabThr : float, optional
63 Stabilization threshold to avoid numerical precision issue
64 verbose : bool, optional
65 Print information along iterations
66 log : bool, optional
67 record log if True
68 warn : bool, optional
69 if True, raises a warning if the algorithm doesn't convergence.
70
71 Returns
72 -------
73 a : array-like, shape (width, height)
74 2D Wasserstein barycenter
75 log : dict
76 log dictionary return only if log==True in parameters
77
78
79 .. _references-convolutional-barycenter-2d:
80 References
81 ----------
82
83 .. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher,
84 A., Nguyen, A. & Guibas, L. (2015). Convolutional wasserstein distances:
85 Efficient optimal transportation on geometric domains. ACM Transactions
86 on Graphics (TOG), 34(4), 66
87
88 .. [37] Janati, H., Cuturi, M., Gramfort, A. Proceedings of the 37th
89 International Conference on Machine Learning, PMLR 119:4692-4701, 2020
90 """
91
92 if method.lower() == "sinkhorn":
93 return _convolutional_barycenter2d(
94 A,
95 reg,
96 weights=weights,
97 numItermax=numItermax,
98 stopThr=stopThr,
99 verbose=verbose,
100 log=log,
101 warn=warn,
102 **kwargs,
103 )
104 elif method.lower() == "sinkhorn_log":
105 return _convolutional_barycenter2d_log(
106 A,
107 reg,
108 weights=weights,
109 numItermax=numItermax,
110 stopThr=stopThr,
111 verbose=verbose,
112 log=log,
113 warn=warn,
114 **kwargs,
115 )
116 else:
117 raise ValueError("Unknown method '%s'." % method)
118
119
120 def _convolutional_barycenter2d(
121 A,
122 reg,
123 weights=None,
124 numItermax=10000,
125 stopThr=1e-9,
126 stabThr=1e-30,
127 verbose=False,
128 log=False,
129 warn=True,
130 ):
131 r"""Compute the entropic regularized wasserstein barycenter of distributions A
132 where A is a collection of 2D images.
133 """
134
135 A = list_to_array(A)
136
137 nx = get_backend(A)
138
139 if weights is None:
140 weights = nx.ones((A.shape[0],), type_as=A) / A.shape[0]
141 else:
142 assert len(weights) == A.shape[0]
143
144 if log:
145 log = {"err": []}
146
147 bar = nx.ones(A.shape[1:], type_as=A)
148 bar /= nx.sum(bar)
149 U = nx.ones(A.shape, type_as=A)
150 V = nx.ones(A.shape, type_as=A)
151 err = 1
152
153 # build the convolution operator
154 # this is equivalent to blurring on horizontal then vertical directions
155 t = nx.linspace(0, 1, A.shape[1], type_as=A)
156 [Y, X] = nx.meshgrid(t, t)
157 K1 = nx.exp(-((X - Y) ** 2) / reg)
158
159 t = nx.linspace(0, 1, A.shape[2], type_as=A)
160 [Y, X] = nx.meshgrid(t, t)
161 K2 = nx.exp(-((X - Y) ** 2) / reg)
162
163 def convol_imgs(imgs):
164 kx = nx.einsum("...ij,kjl->kil", K1, imgs)
165 kxy = nx.einsum("...ij,klj->kli", K2, kx)
166 return kxy
167
168 KU = convol_imgs(U)
169 for ii in range(numItermax):
170 V = bar[None] / KU
171 KV = convol_imgs(V)
172 U = A / KV
173 KU = convol_imgs(U)
174 bar = nx.exp(nx.sum(weights[:, None, None] * nx.log(KU + stabThr), axis=0))
175 if ii % 10 == 9:
176 err = nx.sum(nx.std(V * KU, axis=0))
177 # log and verbose print
178 if log:
179 log["err"].append(err)
180
181 if verbose:
182 if ii % 200 == 0:
183 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
184 print("{:5d}|{:8e}|".format(ii, err))
185 if err < stopThr:
186 break
187
188 else:
189 if warn:
190 warnings.warn(
191 "Convolutional Sinkhorn did not converge. "
192 "Try a larger number of iterations `numItermax` "
193 "or a larger entropy `reg`."
194 )
195 if log:
196 log["niter"] = ii
197 log["U"] = U
198 return bar, log
199 else:
200 return bar
201
202
203 def _convolutional_barycenter2d_log(
204 A,
205 reg,
206 weights=None,
207 numItermax=10000,
208 stopThr=1e-4,
209 stabThr=1e-30,
210 verbose=False,
211 log=False,
212 warn=True,
213 ):
214 r"""Compute the entropic regularized wasserstein barycenter of distributions A
215 where A is a collection of 2D images in log-domain.
216 """
217
218 A = list_to_array(A)
219
220 nx = get_backend(A)
221 if nx.__name__ in ("jax", "tf"):
222 raise NotImplementedError(
223 "Log-domain functions are not yet implemented"
224 " for Jax and TF. Use numpy or torch arrays instead."
225 )
226
227 n_hists, width, height = A.shape
228
229 if weights is None:
230 weights = nx.ones((n_hists,), type_as=A) / n_hists
231 else:
232 assert len(weights) == n_hists
233
234 if log:
235 log = {"err": []}
236
237 err = 1
238 # build the convolution operator
239 # this is equivalent to blurring on horizontal then vertical directions
240 t = nx.linspace(0, 1, width, type_as=A)
241 [Y, X] = nx.meshgrid(t, t)
242 M1 = -((X - Y) ** 2) / reg
243
244 t = nx.linspace(0, 1, height, type_as=A)
245 [Y, X] = nx.meshgrid(t, t)
246 M2 = -((X - Y) ** 2) / reg
247
248 def convol_img(log_img):
249 log_img = nx.logsumexp(M1[:, :, None] + log_img[None], axis=1)
250 log_img = nx.logsumexp(M2[:, :, None] + log_img.T[None], axis=1).T
251 return log_img
252
253 logA = nx.log(A + stabThr)
254 log_KU, G, F = nx.zeros((3, *logA.shape), type_as=A)
255 err = 1
256 for ii in range(numItermax):
257 log_bar = nx.zeros((width, height), type_as=A)
258 for k in range(n_hists):
259 f = logA[k] - convol_img(G[k])
260 log_KU[k] = convol_img(f)
261 log_bar = log_bar + weights[k] * log_KU[k]
262
263 if ii % 10 == 9:
264 err = nx.exp(G + log_KU).std(axis=0).sum()
265 # log and verbose print
266 if log:
267 log["err"].append(err)
268
269 if verbose:
270 if ii % 200 == 0:
271 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
272 print("{:5d}|{:8e}|".format(ii, err))
273 if err < stopThr:
274 break
275 G = log_bar[None, :, :] - log_KU
276
277 else:
278 if warn:
279 warnings.warn(
280 "Convolutional Sinkhorn did not converge. "
281 "Try a larger number of iterations `numItermax` "
282 "or a larger entropy `reg`."
283 )
284 if log:
285 log["niter"] = ii
286 return nx.exp(log_bar), log
287 else:
288 return nx.exp(log_bar)
289
290
291 def convolutional_barycenter2d_debiased(
292 A,
293 reg,
294 weights=None,
295 method="sinkhorn",
296 numItermax=10000,
297 stopThr=1e-3,
298 verbose=False,
299 log=False,
300 warn=True,
301 **kwargs,
302 ):
303 r"""Compute the debiased sinkhorn barycenter of distributions :math:`\mathbf{A}`
304 where :math:`\mathbf{A}` is a collection of 2D images.
305
306 The function solves the following optimization problem:
307
308 .. math::
309 \mathbf{a} = \mathop{\arg \min}_\mathbf{a} \quad \sum_i S_{reg}(\mathbf{a},\mathbf{a}_i)
310
311 where :
312
313 - :math:`S_{reg}(\cdot,\cdot)` is the debiased entropic regularized Wasserstein
314 distance (see :py:func:`ot.bregman.barycenter_debiased`)
315 - :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two
316 dimensions of matrix :math:`\mathbf{A}`
317 - `reg` is the regularization strength scalar value
318
319 The algorithm used for solving the problem is the debiased Sinkhorn scaling
320 algorithm as proposed in :ref:`[37] <references-convolutional-barycenter2d-debiased>`
321
322 Parameters
323 ----------
324 A : array-like, shape (n_hists, width, height)
325 `n` distributions (2D images) of size `width` x `height`
326 reg : float
327 Regularization term >0
328 weights : array-like, shape (n_hists,)
329 Weights of each image on the simplex (barycentric coordinates)
330 method : string, optional
331 method used for the solver either 'sinkhorn' or 'sinkhorn_log'
332 numItermax : int, optional
333 Max number of iterations
334 stopThr : float, optional
335 Stop threshold on error (> 0)
336 stabThr : float, optional
337 Stabilization threshold to avoid numerical precision issue
338 verbose : bool, optional
339 Print information along iterations
340 log : bool, optional
341 record log if True
342 warn : bool, optional
343 if True, raises a warning if the algorithm doesn't convergence.
344
345
346 Returns
347 -------
348 a : array-like, shape (width, height)
349 2D Wasserstein barycenter
350 log : dict
351 log dictionary return only if log==True in parameters
352
353
354 .. _references-convolutional-barycenter2d-debiased:
355 References
356 ----------
357
358 .. [37] Janati, H., Cuturi, M., Gramfort, A. Proceedings of the 37th International
359 Conference on Machine Learning, PMLR 119:4692-4701, 2020
360 """
361
362 if method.lower() == "sinkhorn":
363 return _convolutional_barycenter2d_debiased(
364 A,
365 reg,
366 weights=weights,
367 numItermax=numItermax,
368 stopThr=stopThr,
369 verbose=verbose,
370 log=log,
371 warn=warn,
372 **kwargs,
373 )
374 elif method.lower() == "sinkhorn_log":
375 return _convolutional_barycenter2d_debiased_log(
376 A,
377 reg,
378 weights=weights,
379 numItermax=numItermax,
380 stopThr=stopThr,
381 verbose=verbose,
382 log=log,
383 warn=warn,
384 **kwargs,
385 )
386 else:
387 raise ValueError("Unknown method '%s'." % method)
388
389
390 def _convolutional_barycenter2d_debiased(
391 A,
392 reg,
393 weights=None,
394 numItermax=10000,
395 stopThr=1e-3,
396 stabThr=1e-15,
397 verbose=False,
398 log=False,
399 warn=True,
400 ):
401 r"""Compute the debiased barycenter of 2D images via sinkhorn convolutions."""
402
403 A = list_to_array(A)
404 n_hists, width, height = A.shape
405
406 nx = get_backend(A)
407
408 if weights is None:
409 weights = nx.ones((n_hists,), type_as=A) / n_hists
410 else:
411 assert len(weights) == n_hists
412
413 if log:
414 log = {"err": []}
415
416 bar = nx.ones((width, height), type_as=A)
417 bar /= width * height
418 U = nx.ones(A.shape, type_as=A)
419 V = nx.ones(A.shape, type_as=A)
420 c = nx.ones(A.shape[1:], type_as=A)
421 err = 1
422
423 # build the convolution operator
424 # this is equivalent to blurring on horizontal then vertical directions
425 t = nx.linspace(0, 1, width, type_as=A)
426 [Y, X] = nx.meshgrid(t, t)
427 K1 = nx.exp(-((X - Y) ** 2) / reg)
428
429 t = nx.linspace(0, 1, height, type_as=A)
430 [Y, X] = nx.meshgrid(t, t)
431 K2 = nx.exp(-((X - Y) ** 2) / reg)
432
433 def convol_imgs(imgs):
434 kx = nx.einsum("...ij,kjl->kil", K1, imgs)
435 kxy = nx.einsum("...ij,klj->kli", K2, kx)
436 return kxy
437
438 KU = convol_imgs(U)
439 for ii in range(numItermax):
440 V = bar[None] / KU
441 KV = convol_imgs(V)
442 U = A / KV
443 KU = convol_imgs(U)
444 bar = c * nx.exp(nx.sum(weights[:, None, None] * nx.log(KU + stabThr), axis=0))
445
446 for _ in range(10):
447 c = (c * bar / nx.squeeze(convol_imgs(c[None]))) ** 0.5
448
449 if ii % 10 == 9:
450 err = nx.sum(nx.std(V * KU, axis=0))
451 # log and verbose print
452 if log:
453 log["err"].append(err)
454
455 if verbose:
456 if ii % 200 == 0:
457 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
458 print("{:5d}|{:8e}|".format(ii, err))
459
460 # debiased Sinkhorn does not converge monotonically
461 # guarantee a few iterations are done before stopping
462 if err < stopThr and ii > 20:
463 break
464 else:
465 if warn:
466 warnings.warn(
467 "Sinkhorn did not converge. You might want to "
468 "increase the number of iterations `numItermax` "
469 "or the regularization parameter `reg`."
470 )
471 if log:
472 log["niter"] = ii
473 log["U"] = U
474 return bar, log
475 else:
476 return bar
477
478
479 def _convolutional_barycenter2d_debiased_log(
480 A,
481 reg,
482 weights=None,
483 numItermax=10000,
484 stopThr=1e-3,
485 stabThr=1e-30,
486 verbose=False,
487 log=False,
488 warn=True,
489 ):
490 r"""Compute the debiased barycenter of 2D images in log-domain."""
491
492 A = list_to_array(A)
493 n_hists, width, height = A.shape
494 nx = get_backend(A)
495 if nx.__name__ in ("jax", "tf"):
496 raise NotImplementedError(
497 "Log-domain functions are not yet implemented"
498 " for Jax and TF. Use numpy or torch arrays instead."
499 )
500 if weights is None:
501 weights = nx.ones((n_hists,), type_as=A) / n_hists
502 else:
503 assert len(weights) == A.shape[0]
504
505 if log:
506 log = {"err": []}
507
508 err = 1
509 # build the convolution operator
510 # this is equivalent to blurring on horizontal then vertical directions
511 t = nx.linspace(0, 1, width, type_as=A)
512 [Y, X] = nx.meshgrid(t, t)
513 M1 = -((X - Y) ** 2) / reg
514
515 t = nx.linspace(0, 1, height, type_as=A)
516 [Y, X] = nx.meshgrid(t, t)
517 M2 = -((X - Y) ** 2) / reg
518
519 def convol_img(log_img):
520 log_img = nx.logsumexp(M1[:, :, None] + log_img[None], axis=1)
521 log_img = nx.logsumexp(M2[:, :, None] + log_img.T[None], axis=1).T
522 return log_img
523
524 logA = nx.log(A + stabThr)
525 log_bar, c = nx.zeros((2, width, height), type_as=A)
526 log_KU, G, F = nx.zeros((3, *logA.shape), type_as=A)
527 err = 1
528 for ii in range(numItermax):
529 log_bar = nx.zeros((width, height), type_as=A)
530 for k in range(n_hists):
531 f = logA[k] - convol_img(G[k])
532 log_KU[k] = convol_img(f)
533 log_bar = log_bar + weights[k] * log_KU[k]
534 log_bar += c
535 for _ in range(10):
536 c = 0.5 * (c + log_bar - convol_img(c))
537
538 if ii % 10 == 9:
539 err = nx.sum(nx.std(nx.exp(G + log_KU), axis=0))
540 # log and verbose print
541 if log:
542 log["err"].append(err)
543
544 if verbose:
545 if ii % 200 == 0:
546 print("{:5s}|{:12s}".format("It.", "Err") + "\n" + "-" * 19)
547 print("{:5d}|{:8e}|".format(ii, err))
548 if err < stopThr and ii > 20:
549 break
550 G = log_bar[None, :, :] - log_KU
551
552 else:
553 if warn:
554 warnings.warn(
555 "Convolutional Sinkhorn did not converge. "
556 "Try a larger number of iterations `numItermax` "
557 "or a larger entropy `reg`."
558 )
559 if log:
560 log["niter"] = ii
561 return nx.exp(log_bar), log
562 else:
563 return nx.exp(log_bar)