Skip to content

Commit c9b99df

Browse files
authored
Merge pull request #64 from rflamary/convolution
[MRG] Wasserstein convolutional barycenter This PR closes Issue #51
2 parents 4367a34 + ccbe274 commit c9b99df

File tree

9 files changed

+232
-4
lines changed

9 files changed

+232
-4
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,3 +228,5 @@ You can also post bug reports and feature requests in Github issues. Make sure t
228228
[19] Seguy, V., Bhushan Damodaran, B., Flamary, R., Courty, N., Rolet, A.& Blondel, M. [Large-scale Optimal Transport and Mapping Estimation](https://arxiv.org/pdf/1711.02283.pdf). International Conference on Learning Representation (2018)
229229

230230
[20] Cuturi, M. and Doucet, A. (2014) [Fast Computation of Wasserstein Barycenters](http://proceedings.mlr.press/v32/cuturi14.html). International Conference in Machine Learning
231+
232+
[21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015). [Convolutional wasserstein distances: Efficient optimal transportation on geometric domains](https://dl.acm.org/citation.cfm?id=2766963). ACM Transactions on Graphics (TOG), 34(4), 66.

data/duck.png

4.99 KB
Loading

data/heart.png

5.1 KB
Loading

data/redcross.png

1.64 KB
Loading

data/tooth.png

4.82 KB
Loading
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
2+
#%%
3+
# -*- coding: utf-8 -*-
4+
"""
5+
============================================
6+
Convolutional Wasserstein Barycenter example
7+
============================================
8+
9+
This example is designed to illustrate how the Convolutional Wasserstein Barycenter
10+
function of POT works.
11+
"""
12+
13+
# Author: Nicolas Courty <[email protected]>
14+
#
15+
# License: MIT License
16+
17+
18+
import numpy as np
19+
import pylab as pl
20+
import ot
21+
22+
##############################################################################
23+
# Data preparation
24+
# ----------------
25+
#
26+
# The four distributions are constructed from 4 simple images
27+
28+
29+
f1 = 1 - pl.imread('../data/redcross.png')[:, :, 2]
30+
f2 = 1 - pl.imread('../data/duck.png')[:, :, 2]
31+
f3 = 1 - pl.imread('../data/heart.png')[:, :, 2]
32+
f4 = 1 - pl.imread('../data/tooth.png')[:, :, 2]
33+
34+
A = []
35+
f1 = f1 / np.sum(f1)
36+
f2 = f2 / np.sum(f2)
37+
f3 = f3 / np.sum(f3)
38+
f4 = f4 / np.sum(f4)
39+
A.append(f1)
40+
A.append(f2)
41+
A.append(f3)
42+
A.append(f4)
43+
A = np.array(A)
44+
45+
nb_images = 5
46+
47+
# those are the four corners coordinates that will be interpolated by bilinear
48+
# interpolation
49+
v1 = np.array((1, 0, 0, 0))
50+
v2 = np.array((0, 1, 0, 0))
51+
v3 = np.array((0, 0, 1, 0))
52+
v4 = np.array((0, 0, 0, 1))
53+
54+
55+
##############################################################################
56+
# Barycenter computation and visualization
57+
# ----------------------------------------
58+
#
59+
60+
pl.figure(figsize=(10, 10))
61+
pl.title('Convolutional Wasserstein Barycenters in POT')
62+
cm = 'Blues'
63+
# regularization parameter
64+
reg = 0.004
65+
for i in range(nb_images):
66+
for j in range(nb_images):
67+
pl.subplot(nb_images, nb_images, i * nb_images + j + 1)
68+
tx = float(i) / (nb_images - 1)
69+
ty = float(j) / (nb_images - 1)
70+
71+
# weights are constructed by bilinear interpolation
72+
tmp1 = (1 - tx) * v1 + tx * v2
73+
tmp2 = (1 - tx) * v3 + tx * v4
74+
weights = (1 - ty) * tmp1 + ty * tmp2
75+
76+
if i == 0 and j == 0:
77+
pl.imshow(f1, cmap=cm)
78+
pl.axis('off')
79+
elif i == 0 and j == (nb_images - 1):
80+
pl.imshow(f3, cmap=cm)
81+
pl.axis('off')
82+
elif i == (nb_images - 1) and j == 0:
83+
pl.imshow(f2, cmap=cm)
84+
pl.axis('off')
85+
elif i == (nb_images - 1) and j == (nb_images - 1):
86+
pl.imshow(f4, cmap=cm)
87+
pl.axis('off')
88+
else:
89+
# call to barycenter computation
90+
pl.imshow(ot.bregman.convolutional_barycenter2d(A, reg, weights), cmap=cm)
91+
pl.axis('off')
92+
pl.show()

ot/bregman.py

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,116 @@ def barycenter(A, M, reg, weights=None, numItermax=1000,
919919
return geometricBar(weights, UKv)
920920

921921

922+
def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False):
923+
"""Compute the entropic regularized wasserstein barycenter of distributions A
924+
where A is a collection of 2D images.
925+
926+
The function solves the following optimization problem:
927+
928+
.. math::
929+
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
930+
931+
where :
932+
933+
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
934+
- :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}`
935+
- reg is the regularization strength scalar value
936+
937+
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_
938+
939+
Parameters
940+
----------
941+
A : np.ndarray (n,w,h)
942+
n distributions (2D images) of size w x h
943+
reg : float
944+
Regularization term >0
945+
weights : np.ndarray (n,)
946+
Weights of each image on the simplex (barycentric coodinates)
947+
numItermax : int, optional
948+
Max number of iterations
949+
stopThr : float, optional
950+
Stop threshol on error (>0)
951+
stabThr : float, optional
952+
Stabilization threshold to avoid numerical precision issue
953+
verbose : bool, optional
954+
Print information along iterations
955+
log : bool, optional
956+
record log if True
957+
958+
959+
Returns
960+
-------
961+
a : (w,h) ndarray
962+
2D Wasserstein barycenter
963+
log : dict
964+
log dictionary return only if log==True in parameters
965+
966+
967+
References
968+
----------
969+
970+
.. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).
971+
Convolutional wasserstein distances: Efficient optimal transportation on geometric domains
972+
ACM Transactions on Graphics (TOG), 34(4), 66
973+
974+
975+
"""
976+
977+
if weights is None:
978+
weights = np.ones(A.shape[0]) / A.shape[0]
979+
else:
980+
assert(len(weights) == A.shape[0])
981+
982+
if log:
983+
log = {'err': []}
984+
985+
b = np.zeros_like(A[0, :, :])
986+
U = np.ones_like(A)
987+
KV = np.ones_like(A)
988+
989+
cpt = 0
990+
err = 1
991+
992+
# build the convolution operator
993+
t = np.linspace(0, 1, A.shape[1])
994+
[Y, X] = np.meshgrid(t, t)
995+
xi1 = np.exp(-(X - Y)**2 / reg)
996+
997+
def K(x):
998+
return np.dot(np.dot(xi1, x), xi1)
999+
1000+
while (err > stopThr and cpt < numItermax):
1001+
1002+
bold = b
1003+
cpt = cpt + 1
1004+
1005+
b = np.zeros_like(A[0, :, :])
1006+
for r in range(A.shape[0]):
1007+
KV[r, :, :] = K(A[r, :, :] / np.maximum(stabThr, K(U[r, :, :])))
1008+
b += weights[r] * np.log(np.maximum(stabThr, U[r, :, :] * KV[r, :, :]))
1009+
b = np.exp(b)
1010+
for r in range(A.shape[0]):
1011+
U[r, :, :] = b / np.maximum(stabThr, KV[r, :, :])
1012+
1013+
if cpt % 10 == 1:
1014+
err = np.sum(np.abs(bold - b))
1015+
# log and verbose print
1016+
if log:
1017+
log['err'].append(err)
1018+
1019+
if verbose:
1020+
if cpt % 200 == 0:
1021+
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
1022+
print('{:5d}|{:8e}|'.format(cpt, err))
1023+
1024+
if log:
1025+
log['niter'] = cpt
1026+
log['U'] = U
1027+
return b, log
1028+
else:
1029+
return b
1030+
1031+
9221032
def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000,
9231033
stopThr=1e-3, verbose=False, log=False):
9241034
"""

test/test_bregman.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,30 @@ def test_bary():
105105
ot.bregman.barycenter(A, M, reg, log=True, verbose=True)
106106

107107

108+
def test_wassersteinbary():
109+
110+
size = 100 # size of a square image
111+
a1 = np.random.randn(size, size)
112+
a1 += a1.min()
113+
a1 = a1 / np.sum(a1)
114+
a2 = np.random.randn(size, size)
115+
a2 += a2.min()
116+
a2 = a2 / np.sum(a2)
117+
# creating matrix A containing all distributions
118+
A = np.zeros((2, 100, 100))
119+
A[0, :, :] = a1
120+
A[1, :, :] = a2
121+
122+
# wasserstein
123+
reg = 1e-3
124+
bary_wass = ot.bregman.convolutional_barycenter2d(A, reg)
125+
126+
np.testing.assert_allclose(1, np.sum(bary_wass))
127+
128+
# help in checking if log and verbose do not bug the function
129+
ot.bregman.convolutional_barycenter2d(A, reg, log=True, verbose=True)
130+
131+
108132
def test_unmix():
109133

110134
n_bins = 50 # nb bins

test/test_stochastic.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def test_stochastic_sag():
3232
# test sag
3333
n = 15
3434
reg = 1
35-
numItermax = 300000
35+
numItermax = 30000
3636
rng = np.random.RandomState(0)
3737

3838
x = rng.randn(n, 2)
@@ -62,7 +62,7 @@ def test_stochastic_asgd():
6262
# test asgd
6363
n = 15
6464
reg = 1
65-
numItermax = 300000
65+
numItermax = 100000
6666
rng = np.random.RandomState(0)
6767

6868
x = rng.randn(n, 2)
@@ -92,7 +92,7 @@ def test_sag_asgd_sinkhorn():
9292
# test all algorithms
9393
n = 15
9494
reg = 1
95-
nb_iter = 300000
95+
nb_iter = 100000
9696
rng = np.random.RandomState(0)
9797

9898
x = rng.randn(n, 2)
@@ -167,7 +167,7 @@ def test_dual_sgd_sinkhorn():
167167
# test all dual algorithms
168168
n = 10
169169
reg = 1
170-
nb_iter = 150000
170+
nb_iter = 15000
171171
batch_size = 10
172172
rng = np.random.RandomState(0)
173173

0 commit comments

Comments
 (0)