Debian Codegraph @

examples/gromov/plot_gromov_barycenter.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 =====================================
4 Gromov-Wasserstein Barycenter example
5 =====================================
6
7 This example is designed to show how to use the Gromov-Wasserstein distance
8 computation in POT.
9 """
10
11 # Author: Erwan Vautier <[email protected]>
12 # Nicolas Courty <[email protected]>
13 #
14 # License: MIT License
15
16 import os
17 from pathlib import Path
18
19 import numpy as np
20 import scipy as sp
21
22 from matplotlib import pyplot as plt
23 from sklearn import manifold
24 from sklearn.decomposition import PCA
25
26 import ot
27
28 ##############################################################################
29 # Smacof MDS
30 # ----------
31 #
32 # This function allows to find an embedding of points given a dissimilarity matrix
33 # that will be given by the output of the algorithm
34
35
36 def smacof_mds(C, dim, max_iter=3000, eps=1e-9):
37 """
38 Returns an interpolated point cloud following the dissimilarity matrix C
39 using SMACOF multidimensional scaling (MDS) in specific dimensioned
40 target space
41
42 Parameters
43 ----------
44 C : ndarray, shape (ns, ns)
45 dissimilarity matrix
46 dim : int
47 dimension of the targeted space
48 max_iter : int
49 Maximum number of iterations of the SMACOF algorithm for a single run
50 eps : float
51 relative tolerance w.r.t stress to declare converge
52
53 Returns
54 -------
55 npos : ndarray, shape (R, dim)
56 Embedded coordinates of the interpolated point cloud (defined with
57 one isometry)
58 """
59
60 rng = np.random.RandomState(seed=3)
61
62 mds = manifold.MDS(
63 dim, max_iter=max_iter, eps=1e-9, dissimilarity="precomputed", n_init=1
64 )
65 pos = mds.fit(C).embedding_
66
67 nmds = manifold.MDS(
68 2,
69 max_iter=max_iter,
70 eps=1e-9,
71 dissimilarity="precomputed",
72 random_state=rng,
73 n_init=1,
74 )
75 npos = nmds.fit_transform(C, init=pos)
76
77 return npos
78
79
80 ##############################################################################
81 # Data preparation
82 # ----------------
83 #
84 # The four distributions are constructed from 4 simple images
85
86
87 def im2mat(img):
88 """Converts and image to matrix (one pixel per line)"""
89 return img.reshape((img.shape[0] * img.shape[1], img.shape[2]))
90
91
92 this_file = os.path.realpath("__file__")
93 data_path = os.path.join(Path(this_file).parent.parent.parent, "data")
94
95 square = plt.imread(os.path.join(data_path, "square.png")).astype(np.float64)[:, :, 2]
96 cross = plt.imread(os.path.join(data_path, "cross.png")).astype(np.float64)[:, :, 2]
97 triangle = plt.imread(os.path.join(data_path, "triangle.png")).astype(np.float64)[
98 :, :, 2
99 ]
100 star = plt.imread(os.path.join(data_path, "star.png")).astype(np.float64)[:, :, 2]
101
102 shapes = [square, cross, triangle, star]
103
104 S = 4
105 xs = [[] for i in range(S)]
106
107 for nb in range(4):
108 for i in range(8):
109 for j in range(8):
110 if shapes[nb][i, j] < 0.95:
111 xs[nb].append([j, 8 - i])
112
113 xs = [np.array(xs[s]) for s in range(S)]
114
115 ##############################################################################
116 # Barycenter computation
117 # ----------------------
118
119
120 ns = [len(xs[s]) for s in range(S)]
121 n_samples = 30
122
123 """Compute all distances matrices for the four shapes"""
124 Cs = [sp.spatial.distance.cdist(xs[s], xs[s]) for s in range(S)]
125 Cs = [cs / cs.max() for cs in Cs]
126
127 ps = [ot.unif(ns[s]) for s in range(S)]
128 p = ot.unif(n_samples)
129
130
131 lambdast = [[float(i) / 3, float(3 - i) / 3] for i in [1, 2]]
132
133 Ct01 = [0 for i in range(2)]
134 for i in range(2):
135 Ct01[i] = ot.gromov.gromov_barycenters(
136 n_samples,
137 [Cs[0], Cs[1]],
138 [ps[0], ps[1]],
139 p,
140 lambdast[i],
141 "square_loss", # 5e-4,
142 max_iter=100,
143 tol=1e-3,
144 )
145
146 Ct02 = [0 for i in range(2)]
147 for i in range(2):
148 Ct02[i] = ot.gromov.gromov_barycenters(
149 n_samples,
150 [Cs[0], Cs[2]],
151 [ps[0], ps[2]],
152 p,
153 lambdast[i],
154 "square_loss", # 5e-4,
155 max_iter=100,
156 tol=1e-3,
157 )
158
159 Ct13 = [0 for i in range(2)]
160 for i in range(2):
161 Ct13[i] = ot.gromov.gromov_barycenters(
162 n_samples,
163 [Cs[1], Cs[3]],
164 [ps[1], ps[3]],
165 p,
166 lambdast[i],
167 "square_loss", # 5e-4,
168 max_iter=100,
169 tol=1e-3,
170 )
171
172 Ct23 = [0 for i in range(2)]
173 for i in range(2):
174 Ct23[i] = ot.gromov.gromov_barycenters(
175 n_samples,
176 [Cs[2], Cs[3]],
177 [ps[2], ps[3]],
178 p,
179 lambdast[i],
180 "square_loss", # 5e-4,
181 max_iter=100,
182 tol=1e-3,
183 )
184
185
186 ##############################################################################
187 # Visualization
188 # -------------
189 #
190 # The PCA helps in getting consistency between the rotations
191
192
193 clf = PCA(n_components=2)
194 npos = [0, 0, 0, 0]
195 npos = [smacof_mds(Cs[s], 2) for s in range(S)]
196
197 npost01 = [0, 0]
198 npost01 = [smacof_mds(Ct01[s], 2) for s in range(2)]
199 npost01 = [clf.fit_transform(npost01[s]) for s in range(2)]
200
201 npost02 = [0, 0]
202 npost02 = [smacof_mds(Ct02[s], 2) for s in range(2)]
203 npost02 = [clf.fit_transform(npost02[s]) for s in range(2)]
204
205 npost13 = [0, 0]
206 npost13 = [smacof_mds(Ct13[s], 2) for s in range(2)]
207 npost13 = [clf.fit_transform(npost13[s]) for s in range(2)]
208
209 npost23 = [0, 0]
210 npost23 = [smacof_mds(Ct23[s], 2) for s in range(2)]
211 npost23 = [clf.fit_transform(npost23[s]) for s in range(2)]
212
213
214 fig = plt.figure(figsize=(10, 10))
215
216 ax1 = plt.subplot2grid((4, 4), (0, 0))
217 plt.xlim((-1, 1))
218 plt.ylim((-1, 1))
219 ax1.scatter(npos[0][:, 0], npos[0][:, 1], color="r")
220
221 ax2 = plt.subplot2grid((4, 4), (0, 1))
222 plt.xlim((-1, 1))
223 plt.ylim((-1, 1))
224 ax2.scatter(npost01[1][:, 0], npost01[1][:, 1], color="b")
225
226 ax3 = plt.subplot2grid((4, 4), (0, 2))
227 plt.xlim((-1, 1))
228 plt.ylim((-1, 1))
229 ax3.scatter(npost01[0][:, 0], npost01[0][:, 1], color="b")
230
231 ax4 = plt.subplot2grid((4, 4), (0, 3))
232 plt.xlim((-1, 1))
233 plt.ylim((-1, 1))
234 ax4.scatter(npos[1][:, 0], npos[1][:, 1], color="r")
235
236 ax5 = plt.subplot2grid((4, 4), (1, 0))
237 plt.xlim((-1, 1))
238 plt.ylim((-1, 1))
239 ax5.scatter(npost02[1][:, 0], npost02[1][:, 1], color="b")
240
241 ax6 = plt.subplot2grid((4, 4), (1, 3))
242 plt.xlim((-1, 1))
243 plt.ylim((-1, 1))
244 ax6.scatter(npost13[1][:, 0], npost13[1][:, 1], color="b")
245
246 ax7 = plt.subplot2grid((4, 4), (2, 0))
247 plt.xlim((-1, 1))
248 plt.ylim((-1, 1))
249 ax7.scatter(npost02[0][:, 0], npost02[0][:, 1], color="b")
250
251 ax8 = plt.subplot2grid((4, 4), (2, 3))
252 plt.xlim((-1, 1))
253 plt.ylim((-1, 1))
254 ax8.scatter(npost13[0][:, 0], npost13[0][:, 1], color="b")
255
256 ax9 = plt.subplot2grid((4, 4), (3, 0))
257 plt.xlim((-1, 1))
258 plt.ylim((-1, 1))
259 ax9.scatter(npos[2][:, 0], npos[2][:, 1], color="r")
260
261 ax10 = plt.subplot2grid((4, 4), (3, 1))
262 plt.xlim((-1, 1))
263 plt.ylim((-1, 1))
264 ax10.scatter(npost23[1][:, 0], npost23[1][:, 1], color="b")
265
266 ax11 = plt.subplot2grid((4, 4), (3, 2))
267 plt.xlim((-1, 1))
268 plt.ylim((-1, 1))
269 ax11.scatter(npost23[0][:, 0], npost23[0][:, 1], color="b")
270
271 ax12 = plt.subplot2grid((4, 4), (3, 3))
272 plt.xlim((-1, 1))
273 plt.ylim((-1, 1))
274 ax12.scatter(npos[3][:, 0], npos[3][:, 1], color="r")