Debian Codegraph @

examples/gromov/plot_gromov_wasserstein_dictionary_learning.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 r"""
4 =====================================================
5 (Fused) Gromov-Wasserstein Linear Dictionary Learning
6 =====================================================
7
8 In this example, we illustrate how to learn a Gromov-Wasserstein dictionary on
9 a dataset of structured data such as graphs, denoted
10 :math:`\{ \mathbf{C_s} \}_{s \in [S]}` where every nodes have uniform weights.
11 Given a dictionary :math:`\mathbf{C_{dict}}` composed of D structures of a fixed
12 size nt, each graph :math:`(\mathbf{C_s}, \mathbf{p_s})`
13 is modeled as a convex combination :math:`\mathbf{w_s} \in \Sigma_D` of these
14 dictionary atoms as :math:`\sum_d w_{s,d} \mathbf{C_{dict}[d]}`.
15
16
17 First, we consider a dataset composed of graphs generated by Stochastic Block models
18 with variable sizes taken in :math:`\{30, ... , 50\}` and quantities of clusters
19 varying in :math:`\{ 1, 2, 3\}`. We learn a dictionary of 3 atoms, by minimizing
20 the Gromov-Wasserstein distance from all samples to its model in the dictionary
21 with respect to the dictionary atoms.
22
23 Second, we illustrate the extension of this dictionary learning framework to
24 structured data endowed with node features by using the Fused Gromov-Wasserstein
25 distance. Starting from the aforementioned dataset of unattributed graphs, we
26 add discrete labels uniformly depending on the number of clusters. Then we learn
27 and visualize attributed graph atoms where each sample is modeled as a joint convex
28 combination between atom structures and features.
29
30
31 [38] C. Vincent-Cuaz, T. Vayer, R. Flamary, M. Corneli, N. Courty, Online Graph
32 Dictionary Learning, International Conference on Machine Learning (ICML), 2021.
33
34 """
35 # Author: Cédric Vincent-Cuaz <[email protected]>
36 #
37 # License: MIT License
38
39 # sphinx_gallery_thumbnail_number = 4
40
41 import numpy as np
42 import matplotlib.pylab as pl
43 from sklearn.manifold import MDS
44 from ot.gromov import (
45 gromov_wasserstein_linear_unmixing,
46 gromov_wasserstein_dictionary_learning,
47 fused_gromov_wasserstein_linear_unmixing,
48 fused_gromov_wasserstein_dictionary_learning,
49 )
50 import ot
51 import networkx
52 from networkx.generators.community import stochastic_block_model as sbm
53
54 #############################################################################
55 #
56 # Generate a dataset composed of graphs following Stochastic Block models of 1, 2 and 3 clusters.
57 # -----------------------------------------------------------------------------------------------
58
59 np.random.seed(42)
60
61 N = 60 # number of graphs in the dataset
62 # For every number of clusters, we generate SBM with fixed inter/intra-clusters probability.
63 clusters = [1, 2, 3]
64 Nc = N // len(clusters) # number of graphs by cluster
65 nlabels = len(clusters)
66 dataset = []
67 labels = []
68
69 p_inter = 0.1
70 p_intra = 0.9
71 for n_cluster in clusters:
72 for i in range(Nc):
73 n_nodes = int(np.random.uniform(low=30, high=50))
74
75 if n_cluster > 1:
76 P = p_inter * np.ones((n_cluster, n_cluster))
77 np.fill_diagonal(P, p_intra)
78 else:
79 P = p_intra * np.eye(1)
80 sizes = np.round(n_nodes * np.ones(n_cluster) / n_cluster).astype(np.int32)
81 G = sbm(sizes, P, seed=i, directed=False)
82 C = networkx.to_numpy_array(G)
83 dataset.append(C)
84 labels.append(n_cluster)
85
86
87 # Visualize samples
88
89
90 def plot_graph(x, C, binary=True, color="C0", s=None):
91 for j in range(C.shape[0]):
92 for i in range(j):
93 if binary:
94 if C[i, j] > 0:
95 pl.plot(
96 [x[i, 0], x[j, 0]], [x[i, 1], x[j, 1]], alpha=0.2, color="k"
97 )
98 else: # connection intensity proportional to C[i,j]
99 pl.plot(
100 [x[i, 0], x[j, 0]], [x[i, 1], x[j, 1]], alpha=C[i, j], color="k"
101 )
102
103 pl.scatter(
104 x[:, 0], x[:, 1], c=color, s=s, zorder=10, edgecolors="k", cmap="tab10", vmax=9
105 )
106
107
108 pl.figure(1, (12, 8))
109 pl.clf()
110 for idx_c, c in enumerate(clusters):
111 C = dataset[(c - 1) * Nc] # sample with c clusters
112 # get 2d position for nodes
113 x = MDS(dissimilarity="precomputed", random_state=0).fit_transform(1 - C)
114 pl.subplot(2, nlabels, c)
115 pl.title("(graph) sample from label " + str(c), fontsize=14)
116 plot_graph(x, C, binary=True, color="C0", s=50.0)
117 pl.axis("off")
118 pl.subplot(2, nlabels, nlabels + c)
119 pl.title("(matrix) sample from label %s \n" % c, fontsize=14)
120 pl.imshow(C, interpolation="nearest")
121 pl.axis("off")
122 pl.tight_layout()
123 pl.show()
124
125 #############################################################################
126 #
127 # Estimate the Gromov-Wasserstein dictionary from the dataset
128 # -----------------------------------------------------------
129
130
131 np.random.seed(0)
132 ps = [ot.unif(C.shape[0]) for C in dataset]
133
134 D = 3 # 3 atoms in the dictionary
135 nt = 6 # of 6 nodes each
136
137 q = ot.unif(nt)
138 reg = 0.0 # regularization coefficient to promote sparsity of unmixings {w_s}
139
140 Cdict_GW, log = gromov_wasserstein_dictionary_learning(
141 Cs=dataset,
142 D=D,
143 nt=nt,
144 ps=ps,
145 q=q,
146 epochs=10,
147 batch_size=16,
148 learning_rate=0.1,
149 reg=reg,
150 projection="nonnegative_symmetric",
151 tol_outer=10 ** (-5),
152 tol_inner=10 ** (-5),
153 max_iter_outer=30,
154 max_iter_inner=300,
155 use_log=True,
156 use_adam_optimizer=True,
157 verbose=True,
158 )
159 # visualize loss evolution over epochs
160 pl.figure(2, (4, 3))
161 pl.clf()
162 pl.title("loss evolution by epoch", fontsize=14)
163 pl.plot(log["loss_epochs"])
164 pl.xlabel("epochs", fontsize=12)
165 pl.ylabel("loss", fontsize=12)
166 pl.tight_layout()
167 pl.show()
168
169 #############################################################################
170 #
171 # Visualization of the estimated dictionary atoms
172 # -----------------------------------------------
173
174
175 # Continuous connections between nodes of the atoms are colored in shades of grey (1: dark / 2: white)
176
177 pl.figure(3, (12, 8))
178 pl.clf()
179 for idx_atom, atom in enumerate(Cdict_GW):
180 scaled_atom = (atom - atom.min()) / (atom.max() - atom.min())
181 x = MDS(dissimilarity="precomputed", random_state=0).fit_transform(1 - scaled_atom)
182 pl.subplot(2, D, idx_atom + 1)
183 pl.title("(graph) atom " + str(idx_atom + 1), fontsize=14)
184 plot_graph(x, atom / atom.max(), binary=False, color="C0", s=100.0)
185 pl.axis("off")
186 pl.subplot(2, D, D + idx_atom + 1)
187 pl.title("(matrix) atom %s \n" % (idx_atom + 1), fontsize=14)
188 pl.imshow(scaled_atom, interpolation="nearest")
189 pl.colorbar()
190 pl.axis("off")
191 pl.tight_layout()
192 pl.show()
193
194 #############################################################################
195 #
196 # Visualization of the embedding space
197 # ------------------------------------
198
199 unmixings = []
200 reconstruction_errors = []
201 for C in dataset:
202 p = ot.unif(C.shape[0])
203 unmixing, Cembedded, OT, reconstruction_error = gromov_wasserstein_linear_unmixing(
204 C,
205 Cdict_GW,
206 p=p,
207 q=q,
208 reg=reg,
209 tol_outer=10 ** (-5),
210 tol_inner=10 ** (-5),
211 max_iter_outer=30,
212 max_iter_inner=300,
213 )
214 unmixings.append(unmixing)
215 reconstruction_errors.append(reconstruction_error)
216 unmixings = np.array(unmixings)
217 print("cumulated reconstruction error:", np.array(reconstruction_errors).sum())
218
219
220 # Compute the 2D representation of the unmixing living in the 2-simplex of probability
221 unmixings2D = np.zeros(shape=(N, 2))
222 for i, w in enumerate(unmixings):
223 unmixings2D[i, 0] = (2.0 * w[1] + w[2]) / 2.0
224 unmixings2D[i, 1] = (np.sqrt(3.0) * w[2]) / 2.0
225 x = [0.0, 0.0]
226 y = [1.0, 0.0]
227 z = [0.5, np.sqrt(3) / 2.0]
228 extremities = np.stack([x, y, z])
229
230 pl.figure(4, (4, 4))
231 pl.clf()
232 pl.title("Embedding space", fontsize=14)
233 for cluster in range(nlabels):
234 start, end = Nc * cluster, Nc * (cluster + 1)
235 if cluster == 0:
236 pl.scatter(
237 unmixings2D[start:end, 0],
238 unmixings2D[start:end, 1],
239 c="C" + str(cluster),
240 marker="o",
241 s=40.0,
242 label="1 cluster",
243 )
244 else:
245 pl.scatter(
246 unmixings2D[start:end, 0],
247 unmixings2D[start:end, 1],
248 c="C" + str(cluster),
249 marker="o",
250 s=40.0,
251 label="%s clusters" % (cluster + 1),
252 )
253 pl.scatter(
254 extremities[:, 0], extremities[:, 1], c="black", marker="x", s=80.0, label="atoms"
255 )
256 pl.plot([x[0], y[0]], [x[1], y[1]], color="black", linewidth=2.0)
257 pl.plot([x[0], z[0]], [x[1], z[1]], color="black", linewidth=2.0)
258 pl.plot([y[0], z[0]], [y[1], z[1]], color="black", linewidth=2.0)
259 pl.axis("off")
260 pl.legend(fontsize=11)
261 pl.tight_layout()
262 pl.show()
263
264 #############################################################################
265 #
266 # Endow the dataset with node features
267 # ------------------------------------
268 # We follow this feature assignment on all nodes of a graph depending on its label/number of clusters
269 # 1 cluster --> 0 as nodes feature
270 # 2 clusters --> 1 as nodes feature
271 # 3 clusters --> 2 as nodes feature
272 # features are one-hot encoded following these assignments
273 dataset_features = []
274 for i in range(len(dataset)):
275 n = dataset[i].shape[0]
276 F = np.zeros((n, 3))
277 if i < Nc: # graph with 1 cluster
278 F[:, 0] = 1.0
279 elif i < 2 * Nc: # graph with 2 clusters
280 F[:, 1] = 1.0
281 else: # graph with 3 clusters
282 F[:, 2] = 1.0
283 dataset_features.append(F)
284
285 pl.figure(5, (12, 8))
286 pl.clf()
287 for idx_c, c in enumerate(clusters):
288 C = dataset[(c - 1) * Nc] # sample with c clusters
289 F = dataset_features[(c - 1) * Nc]
290 colors = ["C" + str(np.argmax(F[i])) for i in range(F.shape[0])]
291 # get 2d position for nodes
292 x = MDS(dissimilarity="precomputed", random_state=0).fit_transform(1 - C)
293 pl.subplot(2, nlabels, c)
294 pl.title("(graph) sample from label " + str(c), fontsize=14)
295 plot_graph(x, C, binary=True, color=colors, s=50)
296 pl.axis("off")
297 pl.subplot(2, nlabels, nlabels + c)
298 pl.title("(matrix) sample from label %s \n" % c, fontsize=14)
299 pl.imshow(C, interpolation="nearest")
300 pl.axis("off")
301 pl.tight_layout()
302 pl.show()
303
304 #############################################################################
305 #
306 # Estimate a Fused Gromov-Wasserstein dictionary from the dataset of attributed graphs
307 # ------------------------------------------------------------------------------------
308 np.random.seed(0)
309 ps = [ot.unif(C.shape[0]) for C in dataset]
310 D = 3 # 6 atoms instead of 3
311 nt = 6
312 q = ot.unif(nt)
313 reg = 0.001
314 alpha = 0.5 # trade-off parameter between structure and feature information of Fused Gromov-Wasserstein
315
316
317 Cdict_FGW, Ydict_FGW, log = fused_gromov_wasserstein_dictionary_learning(
318 Cs=dataset,
319 Ys=dataset_features,
320 D=D,
321 nt=nt,
322 ps=ps,
323 q=q,
324 alpha=alpha,
325 epochs=10,
326 batch_size=16,
327 learning_rate_C=0.1,
328 learning_rate_Y=0.1,
329 reg=reg,
330 tol_outer=10 ** (-5),
331 tol_inner=10 ** (-5),
332 max_iter_outer=30,
333 max_iter_inner=300,
334 projection="nonnegative_symmetric",
335 use_log=True,
336 use_adam_optimizer=True,
337 verbose=True,
338 )
339 # visualize loss evolution
340 pl.figure(6, (4, 3))
341 pl.clf()
342 pl.title("loss evolution by epoch", fontsize=14)
343 pl.plot(log["loss_epochs"])
344 pl.xlabel("epochs", fontsize=12)
345 pl.ylabel("loss", fontsize=12)
346 pl.tight_layout()
347 pl.show()
348
349 #############################################################################
350 #
351 # Visualization of the estimated dictionary atoms
352 # -----------------------------------------------
353
354 pl.figure(7, (12, 8))
355 pl.clf()
356 max_features = Ydict_FGW.max()
357 min_features = Ydict_FGW.min()
358
359 for idx_atom, (Catom, Fatom) in enumerate(zip(Cdict_FGW, Ydict_FGW)):
360 scaled_atom = (Catom - Catom.min()) / (Catom.max() - Catom.min())
361 # scaled_F = 2 * (Fatom - min_features) / (max_features - min_features)
362 colors = ["C%s" % np.argmax(Fatom[i]) for i in range(Fatom.shape[0])]
363 x = MDS(dissimilarity="precomputed", random_state=0).fit_transform(1 - scaled_atom)
364 pl.subplot(2, D, idx_atom + 1)
365 pl.title("(attributed graph) atom " + str(idx_atom + 1), fontsize=14)
366 plot_graph(x, Catom / Catom.max(), binary=False, color=colors, s=100)
367 pl.axis("off")
368 pl.subplot(2, D, D + idx_atom + 1)
369 pl.title("(matrix) atom %s \n" % (idx_atom + 1), fontsize=14)
370 pl.imshow(scaled_atom, interpolation="nearest")
371 pl.colorbar()
372 pl.axis("off")
373 pl.tight_layout()
374 pl.show()
375
376 #############################################################################
377 #
378 # Visualization of the embedding space
379 # ------------------------------------
380
381 unmixings = []
382 reconstruction_errors = []
383 for i in range(len(dataset)):
384 C = dataset[i]
385 Y = dataset_features[i]
386 p = ot.unif(C.shape[0])
387 unmixing, Cembedded, Yembedded, OT, reconstruction_error = (
388 fused_gromov_wasserstein_linear_unmixing(
389 C,
390 Y,
391 Cdict_FGW,
392 Ydict_FGW,
393 p=p,
394 q=q,
395 alpha=alpha,
396 reg=reg,
397 tol_outer=10 ** (-6),
398 tol_inner=10 ** (-6),
399 max_iter_outer=30,
400 max_iter_inner=300,
401 )
402 )
403 unmixings.append(unmixing)
404 reconstruction_errors.append(reconstruction_error)
405 unmixings = np.array(unmixings)
406 print("cumulated reconstruction error:", np.array(reconstruction_errors).sum())
407
408 # Visualize unmixings in the 2-simplex of probability
409 unmixings2D = np.zeros(shape=(N, 2))
410 for i, w in enumerate(unmixings):
411 unmixings2D[i, 0] = (2.0 * w[1] + w[2]) / 2.0
412 unmixings2D[i, 1] = (np.sqrt(3.0) * w[2]) / 2.0
413 x = [0.0, 0.0]
414 y = [1.0, 0.0]
415 z = [0.5, np.sqrt(3) / 2.0]
416 extremities = np.stack([x, y, z])
417
418 pl.figure(8, (4, 4))
419 pl.clf()
420 pl.title("Embedding space", fontsize=14)
421 for cluster in range(nlabels):
422 start, end = Nc * cluster, Nc * (cluster + 1)
423 if cluster == 0:
424 pl.scatter(
425 unmixings2D[start:end, 0],
426 unmixings2D[start:end, 1],
427 c="C" + str(cluster),
428 marker="o",
429 s=40.0,
430 label="1 cluster",
431 )
432 else:
433 pl.scatter(
434 unmixings2D[start:end, 0],
435 unmixings2D[start:end, 1],
436 c="C" + str(cluster),
437 marker="o",
438 s=40.0,
439 label="%s clusters" % (cluster + 1),
440 )
441
442 pl.scatter(
443 extremities[:, 0], extremities[:, 1], c="black", marker="x", s=80.0, label="atoms"
444 )
445 pl.plot([x[0], y[0]], [x[1], y[1]], color="black", linewidth=2.0)
446 pl.plot([x[0], z[0]], [x[1], z[1]], color="black", linewidth=2.0)
447 pl.plot([y[0], z[0]], [y[1], z[1]], color="black", linewidth=2.0)
448 pl.axis("off")
449 pl.legend(fontsize=11)
450 pl.tight_layout()
451 pl.show()