Debian Codegraph @

examples/gromov/plot_fgw_solvers.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 ==============================
4 Comparison of Fused Gromov-Wasserstein solvers
5 ==============================
6
7 This example illustrates the computation of FGW for attributed graphs
8 using 4 different solvers to estimate the distance based on Conditional
9 Gradient [24], Sinkhorn projections [12, 51] and alternated Bregman
10 projections [63, 64].
11
12 We generate two graphs following Stochastic Block Models further endowed with
13 node features and compute their FGW matchings.
14
15 [12] Gabriel Peyré, Marco Cuturi, and Justin Solomon (2016),
16 "Gromov-Wasserstein averaging of kernel and distance matrices".
17 International Conference on Machine Learning (ICML).
18
19 [24] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain
20 and Courty Nicolas
21 "Optimal Transport for structured data with application on graphs"
22 International Conference on Machine Learning (ICML). 2019.
23
24 [51] Xu, H., Luo, D., Zha, H., & Duke, L. C. (2019).
25 "Gromov-wasserstein learning for graph matching and node embedding".
26 In International Conference on Machine Learning (ICML), 2019.
27
28 [63] Li, J., Tang, J., Kong, L., Liu, H., Li, J., So, A. M. C., & Blanchet, J.
29 "A Convergent Single-Loop Algorithm for Relaxation of Gromov-Wasserstein in
30 Graph Data". International Conference on Learning Representations (ICLR), 2023.
31
32 [64] Ma, X., Chu, X., Wang, Y., Lin, Y., Zhao, J., Ma, L., & Zhu, W.
33 "Fused Gromov-Wasserstein Graph Mixup for Graph-level Classifications".
34 In Thirty-seventh Conference on Neural Information Processing Systems
35 (NeurIPS), 2023.
36
37 """
38
39 # Author: Cédric Vincent-Cuaz <[email protected]>
40 #
41 # License: MIT License
42
43 # sphinx_gallery_thumbnail_number = 1
44
45 import numpy as np
46 import matplotlib.pylab as pl
47 from ot.gromov import (
48 fused_gromov_wasserstein,
49 entropic_fused_gromov_wasserstein,
50 BAPG_fused_gromov_wasserstein,
51 )
52 import networkx
53 from networkx.generators.community import stochastic_block_model as sbm
54 from time import time
55
56 #############################################################################
57 #
58 # Generate two graphs following Stochastic Block models of 2 and 3 clusters.
59 # ---------------------------------------------
60 np.random.seed(0)
61
62 N2 = 20 # 2 communities
63 N3 = 30 # 3 communities
64 p2 = [[1.0, 0.1], [0.1, 0.9]]
65 p3 = [[1.0, 0.1, 0.0], [0.1, 0.95, 0.1], [0.0, 0.1, 0.9]]
66 G2 = sbm(seed=0, sizes=[N2 // 2, N2 // 2], p=p2)
67 G3 = sbm(seed=0, sizes=[N3 // 3, N3 // 3, N3 // 3], p=p3)
68 part_G2 = [G2.nodes[i]["block"] for i in range(N2)]
69 part_G3 = [G3.nodes[i]["block"] for i in range(N3)]
70
71 C2 = networkx.to_numpy_array(G2)
72 C3 = networkx.to_numpy_array(G3)
73
74
75 # We add node features with given mean - by clusters
76 # and inversely proportional to clusters' intra-connectivity
77
78 F2 = np.zeros((N2, 1))
79 for i, c in enumerate(part_G2):
80 F2[i, 0] = np.random.normal(loc=c, scale=0.01)
81
82 F3 = np.zeros((N3, 1))
83 for i, c in enumerate(part_G3):
84 F3[i, 0] = np.random.normal(loc=2.0 - c, scale=0.01)
85
86 # Compute pairwise euclidean distance between node features
87 M = (F2**2).dot(np.ones((1, N3))) + np.ones((N2, 1)).dot((F3**2).T) - 2 * F2.dot(F3.T)
88
89 h2 = np.ones(C2.shape[0]) / C2.shape[0]
90 h3 = np.ones(C3.shape[0]) / C3.shape[0]
91
92 #############################################################################
93 #
94 # Compute their Fused Gromov-Wasserstein distances
95 # ---------------------------------------------
96
97 alpha = 0.5
98
99
100 # Conditional Gradient algorithm
101 print("Conditional Gradient \n")
102 start_cg = time()
103 T_cg, log_cg = fused_gromov_wasserstein(
104 M, C2, C3, h2, h3, "square_loss", alpha=alpha, tol_rel=1e-9, verbose=True, log=True
105 )
106 end_cg = time()
107 time_cg = 1000 * (end_cg - start_cg)
108
109 # Proximal Point algorithm with Kullback-Leibler as proximal operator
110 print("Proximal Point Algorithm \n")
111 start_ppa = time()
112 T_ppa, log_ppa = entropic_fused_gromov_wasserstein(
113 M,
114 C2,
115 C3,
116 h2,
117 h3,
118 "square_loss",
119 alpha=alpha,
120 epsilon=1.0,
121 solver="PPA",
122 tol=1e-9,
123 log=True,
124 verbose=True,
125 warmstart=False,
126 numItermax=10,
127 )
128 end_ppa = time()
129 time_ppa = 1000 * (end_ppa - start_ppa)
130
131 # Projected Gradient algorithm with entropic regularization
132 print("Projected Gradient Descent \n")
133 start_pgd = time()
134 T_pgd, log_pgd = entropic_fused_gromov_wasserstein(
135 M,
136 C2,
137 C3,
138 h2,
139 h3,
140 "square_loss",
141 alpha=alpha,
142 epsilon=0.01,
143 solver="PGD",
144 tol=1e-9,
145 log=True,
146 verbose=True,
147 warmstart=False,
148 numItermax=10,
149 )
150 end_pgd = time()
151 time_pgd = 1000 * (end_pgd - start_pgd)
152
153 # Alternated Bregman Projected Gradient algorithm with Kullback-Leibler as proximal operator
154 print("Bregman Alternated Projected Gradient \n")
155 start_bapg = time()
156 T_bapg, log_bapg = BAPG_fused_gromov_wasserstein(
157 M,
158 C2,
159 C3,
160 h2,
161 h3,
162 "square_loss",
163 alpha=alpha,
164 epsilon=1.0,
165 tol=1e-9,
166 marginal_loss=True,
167 verbose=True,
168 log=True,
169 )
170 end_bapg = time()
171 time_bapg = 1000 * (end_bapg - start_bapg)
172
173 print(
174 "Fused Gromov-Wasserstein distance estimated with Conditional Gradient solver: "
175 + str(log_cg["fgw_dist"])
176 )
177 print(
178 "Fused Gromov-Wasserstein distance estimated with Proximal Point solver: "
179 + str(log_ppa["fgw_dist"])
180 )
181 print(
182 "Entropic Fused Gromov-Wasserstein distance estimated with Projected Gradient solver: "
183 + str(log_pgd["fgw_dist"])
184 )
185 print(
186 "Fused Gromov-Wasserstein distance estimated with Projected Gradient solver: "
187 + str(log_bapg["fgw_dist"])
188 )
189
190 # compute OT sparsity level
191 T_cg_sparsity = 100 * (T_cg == 0.0).astype(np.float64).sum() / (N2 * N3)
192 T_ppa_sparsity = 100 * (T_ppa == 0.0).astype(np.float64).sum() / (N2 * N3)
193 T_pgd_sparsity = 100 * (T_pgd == 0.0).astype(np.float64).sum() / (N2 * N3)
194 T_bapg_sparsity = 100 * (T_bapg == 0.0).astype(np.float64).sum() / (N2 * N3)
195
196 # Methods using Sinkhorn/Bregman projections tend to produce feasibility errors on the
197 # marginal constraints
198
199 err_cg = np.linalg.norm(T_cg.sum(1) - h2) + np.linalg.norm(T_cg.sum(0) - h3)
200 err_ppa = np.linalg.norm(T_ppa.sum(1) - h2) + np.linalg.norm(T_ppa.sum(0) - h3)
201 err_pgd = np.linalg.norm(T_pgd.sum(1) - h2) + np.linalg.norm(T_pgd.sum(0) - h3)
202 err_bapg = np.linalg.norm(T_bapg.sum(1) - h2) + np.linalg.norm(T_bapg.sum(0) - h3)
203
204 #############################################################################
205 #
206 # Visualization of the Fused Gromov-Wasserstein matchings
207 # ---------------------------------------------
208 #
209 # We color nodes of the graph on the right - then project its node colors
210 # based on the optimal transport plan from the FGW matchings
211 # We adjust the intensity of links across domains proportionaly to the mass
212 # sent, adding a minimal intensity of 0.1 if mass sent is not zero.
213 # For each matching, all node sizes are proportionnal to their mass computed
214 # from marginals of the OT plan to illustrate potential feasibility errors.
215 # NB: colors refer to clusters - not to node features
216
217 # Add weights on the edges for visualization later on
218 weight_intra_G2 = 5
219 weight_inter_G2 = 0.5
220 weight_intra_G3 = 1.0
221 weight_inter_G3 = 1.5
222
223 weightedG2 = networkx.Graph()
224 part_G2 = [G2.nodes[i]["block"] for i in range(N2)]
225
226 for node in G2.nodes():
227 weightedG2.add_node(node)
228 for i, j in G2.edges():
229 if part_G2[i] == part_G2[j]:
230 weightedG2.add_edge(i, j, weight=weight_intra_G2)
231 else:
232 weightedG2.add_edge(i, j, weight=weight_inter_G2)
233
234 weightedG3 = networkx.Graph()
235 part_G3 = [G3.nodes[i]["block"] for i in range(N3)]
236
237 for node in G3.nodes():
238 weightedG3.add_node(node)
239 for i, j in G3.edges():
240 if part_G3[i] == part_G3[j]:
241 weightedG3.add_edge(i, j, weight=weight_intra_G3)
242 else:
243 weightedG3.add_edge(i, j, weight=weight_inter_G3)
244
245
246 def draw_graph(
247 G,
248 C,
249 nodes_color_part,
250 Gweights=None,
251 pos=None,
252 edge_color="black",
253 node_size=None,
254 shiftx=0,
255 seed=0,
256 ):
257 if pos is None:
258 pos = networkx.spring_layout(G, scale=1.0, seed=seed)
259
260 if shiftx != 0:
261 for k, v in pos.items():
262 v[0] = v[0] + shiftx
263
264 alpha_edge = 0.7
265 width_edge = 1.8
266 if Gweights is None:
267 networkx.draw_networkx_edges(
268 G, pos, width=width_edge, alpha=alpha_edge, edge_color=edge_color
269 )
270 else:
271 # We make more visible connections between activated nodes
272 n = len(Gweights)
273 edgelist_activated = []
274 edgelist_deactivated = []
275 for i in range(n):
276 for j in range(n):
277 if Gweights[i] * Gweights[j] * C[i, j] > 0:
278 edgelist_activated.append((i, j))
279 elif C[i, j] > 0:
280 edgelist_deactivated.append((i, j))
281
282 networkx.draw_networkx_edges(
283 G,
284 pos,
285 edgelist=edgelist_activated,
286 width=width_edge,
287 alpha=alpha_edge,
288 edge_color=edge_color,
289 )
290 networkx.draw_networkx_edges(
291 G,
292 pos,
293 edgelist=edgelist_deactivated,
294 width=width_edge,
295 alpha=0.1,
296 edge_color=edge_color,
297 )
298
299 if Gweights is None:
300 for node, node_color in enumerate(nodes_color_part):
301 networkx.draw_networkx_nodes(
302 G,
303 pos,
304 nodelist=[node],
305 node_size=node_size,
306 alpha=1,
307 node_color=node_color,
308 )
309 else:
310 scaled_Gweights = Gweights / (0.5 * Gweights.max())
311 nodes_size = node_size * scaled_Gweights
312 for node, node_color in enumerate(nodes_color_part):
313 networkx.draw_networkx_nodes(
314 G,
315 pos,
316 nodelist=[node],
317 node_size=nodes_size[node],
318 alpha=1,
319 node_color=node_color,
320 )
321 return pos
322
323
324 def draw_transp_colored_GW(
325 G1,
326 C1,
327 G2,
328 C2,
329 part_G1,
330 p1,
331 p2,
332 T,
333 pos1=None,
334 pos2=None,
335 shiftx=4,
336 switchx=False,
337 node_size=70,
338 seed_G1=0,
339 seed_G2=0,
340 ):
341 starting_color = 0
342 # get graphs partition and their coloring
343 part1 = part_G1.copy()
344 unique_colors = ["C%s" % (starting_color + i) for i in np.unique(part1)]
345 nodes_color_part1 = []
346 for cluster in part1:
347 nodes_color_part1.append(unique_colors[cluster])
348
349 nodes_color_part2 = []
350 # T: getting colors assignment from argmin of columns
351 for i in range(len(G2.nodes())):
352 j = np.argmax(T[:, i])
353 nodes_color_part2.append(nodes_color_part1[j])
354 pos1 = draw_graph(
355 G1,
356 C1,
357 nodes_color_part1,
358 Gweights=p1,
359 pos=pos1,
360 node_size=node_size,
361 shiftx=0,
362 seed=seed_G1,
363 )
364 pos2 = draw_graph(
365 G2,
366 C2,
367 nodes_color_part2,
368 Gweights=p2,
369 pos=pos2,
370 node_size=node_size,
371 shiftx=shiftx,
372 seed=seed_G2,
373 )
374
375 for k1, v1 in pos1.items():
376 max_Tk1 = np.max(T[k1, :])
377 for k2, v2 in pos2.items():
378 if T[k1, k2] > 0:
379 pl.plot(
380 [pos1[k1][0], pos2[k2][0]],
381 [pos1[k1][1], pos2[k2][1]],
382 "-",
383 lw=0.7,
384 alpha=min(T[k1, k2] / max_Tk1 + 0.1, 1.0),
385 color=nodes_color_part1[k1],
386 )
387 return pos1, pos2
388
389
390 node_size = 40
391 fontsize = 13
392 seed_G2 = 0
393 seed_G3 = 4
394
395 pl.figure(2, figsize=(15, 3.5))
396 pl.clf()
397 pl.subplot(141)
398 pl.axis("off")
399
400 pl.title(
401 "(CG) FGW=%s\n \n OT sparsity = %s \n marg. error = %s \n runtime = %s"
402 % (
403 np.round(log_cg["fgw_dist"], 3),
404 str(np.round(T_cg_sparsity, 2)) + " %",
405 np.round(err_cg, 4),
406 str(np.round(time_cg, 2)) + " ms",
407 ),
408 fontsize=fontsize,
409 )
410
411 pos1, pos2 = draw_transp_colored_GW(
412 weightedG2,
413 C2,
414 weightedG3,
415 C3,
416 part_G2,
417 p1=T_cg.sum(1),
418 p2=T_cg.sum(0),
419 T=T_cg,
420 shiftx=1.5,
421 node_size=node_size,
422 seed_G1=seed_G2,
423 seed_G2=seed_G3,
424 )
425
426 pl.subplot(142)
427 pl.axis("off")
428
429 pl.title(
430 "(PPA) FGW=%s\n \n OT sparsity = %s \n marg. error = %s \n runtime = %s"
431 % (
432 np.round(log_ppa["fgw_dist"], 3),
433 str(np.round(T_ppa_sparsity, 2)) + " %",
434 np.round(err_ppa, 4),
435 str(np.round(time_ppa, 2)) + " ms",
436 ),
437 fontsize=fontsize,
438 )
439
440 pos1, pos2 = draw_transp_colored_GW(
441 weightedG2,
442 C2,
443 weightedG3,
444 C3,
445 part_G2,
446 p1=T_ppa.sum(1),
447 p2=T_ppa.sum(0),
448 T=T_ppa,
449 pos1=pos1,
450 pos2=pos2,
451 shiftx=0.0,
452 node_size=node_size,
453 seed_G1=0,
454 seed_G2=0,
455 )
456
457 pl.subplot(143)
458 pl.axis("off")
459
460 pl.title(
461 "(PGD) Entropic FGW=%s\n \n OT sparsity = %s \n marg. error = %s \n runtime = %s"
462 % (
463 np.round(log_pgd["fgw_dist"], 3),
464 str(np.round(T_pgd_sparsity, 2)) + " %",
465 np.round(err_pgd, 4),
466 str(np.round(time_pgd, 2)) + " ms",
467 ),
468 fontsize=fontsize,
469 )
470
471 pos1, pos2 = draw_transp_colored_GW(
472 weightedG2,
473 C2,
474 weightedG3,
475 C3,
476 part_G2,
477 p1=T_pgd.sum(1),
478 p2=T_pgd.sum(0),
479 T=T_pgd,
480 pos1=pos1,
481 pos2=pos2,
482 shiftx=0.0,
483 node_size=node_size,
484 seed_G1=0,
485 seed_G2=0,
486 )
487
488
489 pl.subplot(144)
490 pl.axis("off")
491
492 pl.title(
493 "(BAPG) FGW=%s\n \n OT sparsity = %s \n marg. error = %s \n runtime = %s"
494 % (
495 np.round(log_bapg["fgw_dist"], 3),
496 str(np.round(T_bapg_sparsity, 2)) + " %",
497 np.round(err_bapg, 4),
498 str(np.round(time_bapg, 2)) + " ms",
499 ),
500 fontsize=fontsize,
501 )
502
503 pos1, pos2 = draw_transp_colored_GW(
504 weightedG2,
505 C2,
506 weightedG3,
507 C3,
508 part_G2,
509 p1=T_bapg.sum(1),
510 p2=T_bapg.sum(0),
511 T=T_bapg,
512 pos1=pos1,
513 pos2=pos2,
514 shiftx=0.0,
515 node_size=node_size,
516 seed_G1=0,
517 seed_G2=0,
518 )
519
520 pl.tight_layout()
521
522 pl.show()