Debian Codegraph @

examples/gromov/plot_quantized_gromov_wasserstein.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 ===============================================
4 Quantized Fused Gromov-Wasserstein examples
5 ===============================================
6
7 These examples show how to use the quantized (Fused) Gromov-Wasserstein
8 solvers (qFGW) [68]. POT provides a generic solver `quantized_fused_gromov_wasserstein_partitioned`
9 that takes as inputs partitioned graphs potentially endowed with node features,
10 which have to be built by the user. On top of that, POT provides two wrappers:
11 i) `quantized_fused_gromov_wasserstein` operating over generic graphs, whose
12 partitioning is performed via `get_graph_partition` using e.g the Louvain algorithm,
13 and representant for each partition can be selected via `get_graph_representants`
14 using e.g the PageRank algorithm.
15
16 ii) `quantized_fused_gromov_wasserstein_samples` operating over point clouds,
17 e.g :math:`X_1 \in R^{n_1 * d_1}` and :math:`X_2 \in R^{n_2 * d_2}`
18 endowed with their respective euclidean geometry, whose partitioning and
19 representant selection is performed jointly using e.g the K-means algorithm
20 via the function `get_partition_and_representants_samples`.
21
22
23 We illustrate next how to compute the qGW distance on both types of data by:
24
25 i) Generating two graphs following Stochastic Block Models encoded as shortest
26 path matrices as qGW solvers tends to require dense structure to achieve a good
27 approximation of the GW distance (as qGW is an upper-bound of GW). In the meantime,
28 we illustrate an optional feature of our solvers, namely the use of auxiliary
29 structures e.g adjacency matrices to perform the graph partitioning.
30
31 ii) Generating two point clouds representing curves in 2D and 3D respectively.
32 We augment these point clouds by considering additional features of the same
33 dimensionaly :math:`F_1 \in R^{n_1 * d}` and :math:`F_2 \in R^{n_2 * d}`,
34 representing the color intensity associated to each sample of both distributions.
35 Then we compute the qFGW distance between these attributed point clouds.
36
37
38 [68] Chowdhury, S., Miller, D., & Needham, T. (2021). Quantized gromov-wasserstein.
39 ECML PKDD 2021. Springer International Publishing.
40 """
41
42 # Author: Cédric Vincent-Cuaz <[email protected]>
43 #
44 # License: MIT License
45
46 # sphinx_gallery_thumbnail_number = 2
47
48 import numpy as np
49 import matplotlib.pylab as pl
50 import matplotlib.pyplot as plt
51 import networkx
52 from networkx.generators.community import stochastic_block_model as sbm
53 from scipy.sparse.csgraph import shortest_path
54
55 from ot.gromov import (
56 quantized_fused_gromov_wasserstein_partitioned,
57 quantized_fused_gromov_wasserstein,
58 get_graph_partition,
59 get_graph_representants,
60 format_partitioned_graph,
61 quantized_fused_gromov_wasserstein_samples,
62 get_partition_and_representants_samples,
63 )
64
65 #############################################################################
66 #
67 # Generate graphs
68 # --------------------------------------------------------------------------
69 #
70 # Create two graphs following Stochastic Block models of 2 and 3 clusters.
71
72 N1 = 30 # 2 communities
73 N2 = 45 # 3 communities
74 p1 = [[0.8, 0.1], [0.1, 0.7]]
75 p2 = [[0.8, 0.1, 0.0], [0.1, 0.75, 0.1], [0.0, 0.1, 0.7]]
76 G1 = sbm(seed=0, sizes=[N1 // 2, N1 // 2], p=p1)
77 G2 = sbm(seed=0, sizes=[N2 // 3, N2 // 3, N2 // 3], p=p2)
78
79
80 C1 = networkx.to_numpy_array(G1)
81 C2 = networkx.to_numpy_array(G2)
82
83 spC1 = shortest_path(C1)
84 spC2 = shortest_path(C2)
85
86 h1 = np.ones(C1.shape[0]) / C1.shape[0]
87 h2 = np.ones(C2.shape[0]) / C2.shape[0]
88
89 # Add weights on the edges for visualization later on
90 weight_intra_G1 = 5
91 weight_inter_G1 = 0.5
92 weight_intra_G2 = 1.0
93 weight_inter_G2 = 1.5
94
95 weightedG1 = networkx.Graph()
96 part_G1 = [G1.nodes[i]["block"] for i in range(N1)]
97
98 for node in G1.nodes():
99 weightedG1.add_node(node)
100 for i, j in G1.edges():
101 if part_G1[i] == part_G1[j]:
102 weightedG1.add_edge(i, j, weight=weight_intra_G1)
103 else:
104 weightedG1.add_edge(i, j, weight=weight_inter_G1)
105
106 weightedG2 = networkx.Graph()
107 part_G2 = [G2.nodes[i]["block"] for i in range(N2)]
108
109 for node in G2.nodes():
110 weightedG2.add_node(node)
111 for i, j in G2.edges():
112 if part_G2[i] == part_G2[j]:
113 weightedG2.add_edge(i, j, weight=weight_intra_G2)
114 else:
115 weightedG2.add_edge(i, j, weight=weight_inter_G2)
116
117
118 # setup for graph visualization
119
120
121 def node_coloring(part, starting_color=0):
122 # get graphs partition and their coloring
123 unique_colors = ["C%s" % (starting_color + i) for i in np.unique(part)]
124 nodes_color_part = []
125 for cluster in part:
126 nodes_color_part.append(unique_colors[cluster])
127
128 return nodes_color_part
129
130
131 def draw_graph(
132 G,
133 C,
134 nodes_color_part,
135 rep_indices,
136 node_alphas=None,
137 pos=None,
138 edge_color="black",
139 alpha_edge=0.7,
140 node_size=None,
141 shiftx=0,
142 seed=0,
143 highlight_rep=False,
144 ):
145 if pos is None:
146 pos = networkx.spring_layout(G, scale=1.0, seed=seed)
147
148 if shiftx != 0:
149 for k, v in pos.items():
150 v[0] = v[0] + shiftx
151
152 width_edge = 1.5
153
154 if not highlight_rep:
155 networkx.draw_networkx_edges(
156 G, pos, width=width_edge, alpha=alpha_edge, edge_color=edge_color
157 )
158 else:
159 for edge in G.edges:
160 if (edge[0] in rep_indices) and (edge[1] in rep_indices):
161 networkx.draw_networkx_edges(
162 G,
163 pos,
164 edgelist=[edge],
165 width=width_edge,
166 alpha=alpha_edge,
167 edge_color=edge_color,
168 )
169 else:
170 networkx.draw_networkx_edges(
171 G,
172 pos,
173 edgelist=[edge],
174 width=width_edge,
175 alpha=0.2,
176 edge_color=edge_color,
177 )
178
179 for node, node_color in enumerate(nodes_color_part):
180 local_node_shape, local_node_size = "o", node_size
181
182 if highlight_rep:
183 if node in rep_indices:
184 local_node_shape, local_node_size = "*", 6 * node_size
185
186 if node_alphas is None:
187 alpha = 0.9
188 if highlight_rep:
189 alpha = 0.9 if node in rep_indices else 0.1
190
191 else:
192 alpha = node_alphas[node]
193
194 networkx.draw_networkx_nodes(
195 G,
196 pos,
197 nodelist=[node],
198 alpha=alpha,
199 node_shape=local_node_shape,
200 node_size=local_node_size,
201 node_color=node_color,
202 )
203
204 return pos
205
206
207 #############################################################################
208 #
209 # Compute their quantized Gromov-Wasserstein distance without using the wrapper
210 # ---------------------------------------------------------
211 #
212 # We detail next the steps implemented within the wrapper that preprocess graphs
213 # to form partitioned graphs, which are then passed as input to the generic qFGW solver.
214
215 # 1-a) Partition C1 and C2 in 2 and 3 clusters respectively using Louvain
216 # algorithm from Networkx. Then encode these partitions via vectors of assignments.
217
218 part_method = "louvain"
219 rep_method = "pagerank"
220
221 npart_1 = 2 # 2 clusters used to describe C1
222 npart_2 = 3 # 3 clusters used to describe C2
223
224 part1 = get_graph_partition(
225 C1, npart=npart_1, part_method=part_method, F=None, alpha=1.0
226 )
227 part2 = get_graph_partition(
228 C2, npart=npart_2, part_method=part_method, F=None, alpha=1.0
229 )
230
231 # 1-b) Select representant in each partition using the Pagerank algorithm
232 # implementation from networkx.
233
234 rep_indices1 = get_graph_representants(C1, part1, rep_method=rep_method)
235 rep_indices2 = get_graph_representants(C2, part2, rep_method=rep_method)
236
237 # 1-c) Format partitions such that:
238 # CR contains relations between representants in each space.
239 # list_R contains relations between samples and representants within each partition.
240 # list_h contains samples relative importance within each partition.
241
242 CR1, list_R1, list_h1 = format_partitioned_graph(
243 spC1, h1, part1, rep_indices1, F=None, M=None, alpha=1.0
244 )
245
246 CR2, list_R2, list_h2 = format_partitioned_graph(
247 spC2, h2, part2, rep_indices2, F=None, M=None, alpha=1.0
248 )
249
250 # 1-d) call to partitioned quantized gromov-wasserstein solver
251
252 OT_global_, OTs_local_, OT_, log_ = quantized_fused_gromov_wasserstein_partitioned(
253 CR1,
254 CR2,
255 list_R1,
256 list_R2,
257 list_h1,
258 list_h2,
259 MR=None,
260 alpha=1.0,
261 build_OT=True,
262 log=True,
263 )
264
265
266 # Visualization of the graph pre-processing
267
268 node_size = 40
269 fontsize = 10
270 seed_G1 = 0
271 seed_G2 = 3
272
273 part1_ = part1.astype(np.int32)
274 part2_ = part2.astype(np.int32)
275
276
277 nodes_color_part1 = node_coloring(part1_, starting_color=0)
278 nodes_color_part2 = node_coloring(
279 part2_, starting_color=np.unique(nodes_color_part1).shape[0]
280 )
281
282
283 pl.figure(1, figsize=(6, 5))
284 pl.clf()
285 pl.axis("off")
286 pl.subplot(2, 3, 1)
287 pl.title(r"Input graph: $\mathbf{spC_1}$", fontsize=fontsize)
288
289 pos1 = draw_graph(
290 G1, C1, ["C0" for _ in part1_], rep_indices1, node_size=node_size, seed=seed_G1
291 )
292
293 pl.subplot(2, 3, 2)
294 pl.title("Partitioning", fontsize=fontsize)
295
296 _ = draw_graph(
297 G1, C1, nodes_color_part1, rep_indices1, pos=pos1, node_size=node_size, seed=seed_G1
298 )
299
300 pl.subplot(2, 3, 3)
301 pl.title("Representant selection", fontsize=fontsize)
302
303 _ = draw_graph(
304 G1,
305 C1,
306 nodes_color_part1,
307 rep_indices1,
308 pos=pos1,
309 node_size=node_size,
310 seed=seed_G1,
311 highlight_rep=True,
312 )
313
314 pl.subplot(2, 3, 4)
315 pl.title(r"Input graph: $\mathbf{spC_2}$", fontsize=fontsize)
316
317 pos2 = draw_graph(
318 G2, C2, ["C0" for _ in part2_], rep_indices2, node_size=node_size, seed=seed_G2
319 )
320
321 pl.subplot(2, 3, 5)
322 pl.title(r"Partitioning", fontsize=fontsize)
323
324 _ = draw_graph(
325 G2, C2, nodes_color_part2, rep_indices2, pos=pos2, node_size=node_size, seed=seed_G2
326 )
327
328 pl.subplot(2, 3, 6)
329 pl.title(r"Representant selection", fontsize=fontsize)
330
331 _ = draw_graph(
332 G2,
333 C2,
334 nodes_color_part2,
335 rep_indices2,
336 pos=pos2,
337 node_size=node_size,
338 seed=seed_G2,
339 highlight_rep=True,
340 )
341 pl.tight_layout()
342
343 #############################################################################
344 #
345 # Compute the quantized Gromov-Wasserstein distance using the wrapper
346 # ---------------------------------------------------------
347 #
348 # Compute qGW(spC1, h1, spC2, h2). We also illustrate the use of auxiliary matrices
349 # such that the adjacency matrices `C1_aux=C1` and `C2_aux=C2` to partition the graph using
350 # Louvain algorithm, and the Pagerank algorithm for selecting representant within
351 # each partition. Notice that `C1_aux` and `C2_aux` are optional, if they are not
352 # specified these pre-processing algorithms will be applied to spC2 and spC3.
353
354
355 # no node features are considered on this synthetic dataset. Hence we simply
356 # let F1, F2 = None and set alpha = 1.
357 OT_global, OTs_local, OT, log = quantized_fused_gromov_wasserstein(
358 spC1,
359 spC2,
360 npart_1,
361 npart_2,
362 h1,
363 h2,
364 C1_aux=C1,
365 C2_aux=C2,
366 F1=None,
367 F2=None,
368 alpha=1.0,
369 part_method=part_method,
370 rep_method=rep_method,
371 log=True,
372 )
373
374 qGW_dist = log["qFGW_dist"]
375
376
377 #############################################################################
378 #
379 # Visualization of the quantized Gromov-Wasserstein matching
380 # --------------------------------------------------------------
381 #
382 # We color nodes of the graph based on the respective partition of each graph.
383 # On the first plot we illustrate the qGW matching between both shortest path matrices.
384 # While the GW matching across representants of each space is illustrated on the right.
385
386
387 def draw_transp_colored_qGW(
388 G1,
389 C1,
390 G2,
391 C2,
392 part1,
393 part2,
394 rep_indices1,
395 rep_indices2,
396 T,
397 pos1=None,
398 pos2=None,
399 shiftx=4,
400 switchx=False,
401 node_size=70,
402 seed_G1=0,
403 seed_G2=0,
404 highlight_rep=False,
405 ):
406 starting_color = 0
407 # get graphs partition and their coloring
408 unique_colors1 = ["C%s" % (starting_color + i) for i in np.unique(part1)]
409 nodes_color_part1 = []
410 for cluster in part1:
411 nodes_color_part1.append(unique_colors1[cluster])
412
413 starting_color = len(unique_colors1) + 1
414 unique_colors2 = ["C%s" % (starting_color + i) for i in np.unique(part2)]
415 nodes_color_part2 = []
416 for cluster in part2:
417 nodes_color_part2.append(unique_colors2[cluster])
418
419 pos1 = draw_graph(
420 G1,
421 C1,
422 nodes_color_part1,
423 rep_indices1,
424 pos=pos1,
425 node_size=node_size,
426 shiftx=0,
427 seed=seed_G1,
428 highlight_rep=highlight_rep,
429 )
430 pos2 = draw_graph(
431 G2,
432 C2,
433 nodes_color_part2,
434 rep_indices2,
435 pos=pos2,
436 node_size=node_size,
437 shiftx=shiftx,
438 seed=seed_G1,
439 highlight_rep=highlight_rep,
440 )
441
442 if not highlight_rep:
443 for k1, v1 in pos1.items():
444 max_Tk1 = np.max(T[k1, :])
445 for k2, v2 in pos2.items():
446 if T[k1, k2] > 0:
447 pl.plot(
448 [pos1[k1][0], pos2[k2][0]],
449 [pos1[k1][1], pos2[k2][1]],
450 "-",
451 lw=0.7,
452 alpha=T[k1, k2] / max_Tk1,
453 color=nodes_color_part1[k1],
454 )
455
456 else: # OT is only between representants
457 for id1, node_id1 in enumerate(rep_indices1):
458 max_Tk1 = np.max(T[id1, :])
459 for id2, node_id2 in enumerate(rep_indices2):
460 if T[id1, id2] > 0:
461 pl.plot(
462 [pos1[node_id1][0], pos2[node_id2][0]],
463 [pos1[node_id1][1], pos2[node_id2][1]],
464 "-",
465 lw=0.8,
466 alpha=T[id1, id2] / max_Tk1,
467 color=nodes_color_part1[node_id1],
468 )
469 return pos1, pos2
470
471
472 pl.figure(2, figsize=(5, 2.5))
473 pl.clf()
474 pl.axis("off")
475 pl.subplot(1, 2, 1)
476 pl.title(
477 r"qGW$(\mathbf{spC_1}, \mathbf{spC_1}) =%s$" % (np.round(qGW_dist, 3)),
478 fontsize=fontsize,
479 )
480
481 pos1, pos2 = draw_transp_colored_qGW(
482 weightedG1,
483 C1,
484 weightedG2,
485 C2,
486 part1_,
487 part2_,
488 rep_indices1,
489 rep_indices2,
490 T=OT_,
491 shiftx=1.5,
492 node_size=node_size,
493 seed_G1=seed_G1,
494 seed_G2=seed_G2,
495 )
496
497 pl.tight_layout()
498
499 pl.subplot(1, 2, 2)
500 pl.title(
501 r" GW$(\mathbf{CR_1}, \mathbf{CR_2}) =%s$" % (np.round(log_["global dist"], 3)),
502 fontsize=fontsize,
503 )
504
505 pos1, pos2 = draw_transp_colored_qGW(
506 weightedG1,
507 C1,
508 weightedG2,
509 C2,
510 part1_,
511 part2_,
512 rep_indices1,
513 rep_indices2,
514 T=OT_global,
515 shiftx=1.5,
516 node_size=node_size,
517 seed_G1=seed_G1,
518 seed_G2=seed_G2,
519 highlight_rep=True,
520 )
521
522 pl.tight_layout()
523 pl.show()
524
525 #############################################################################
526 #
527 # Generate attributed point clouds
528 # --------------------------------------------------------------------------
529 #
530 # Create two attributed point clouds representing curves in 2D and 3D respectively,
531 # whose samples are further associated to various color intensities.
532
533 n_samples = 100
534
535 # Generate 2D and 3D curves
536 theta = np.linspace(-4 * np.pi, 4 * np.pi, n_samples)
537 z = np.linspace(1, 2, n_samples)
538 r = z**2 + 1
539 x = r * np.sin(theta)
540 y = r * np.cos(theta)
541
542 # Source and target distribution across spaces encoded respectively via their
543 # squared euclidean distance matrices.
544
545 X = np.concatenate([x.reshape(-1, 1), z.reshape(-1, 1)], axis=1)
546 Y = np.concatenate([x.reshape(-1, 1), y.reshape(-1, 1), z.reshape(-1, 1)], axis=1)
547
548 # Further associated to color intensity features derived from z
549
550 FX = z - z.min() / (z.max() - z.min())
551 FX = np.clip(0.8 * FX + 0.2, a_min=0.2, a_max=1.0) # for numerical issues
552 FY = FX
553
554
555 #############################################################################
556 #
557 # Visualize partitioned attributed point clouds
558 # --------------------------------------------------------------------------
559 #
560 # Compute the partitioning and representant selection further used within
561 # qFGW wrapper, both provided by a K-means algorithm. Then visualize partitioned spaces.
562
563 part1, rep_indices1 = get_partition_and_representants_samples(X, 4, "kmeans", 0)
564 part2, rep_indices2 = get_partition_and_representants_samples(Y, 4, "kmeans", 0)
565
566 upart1 = np.unique(part1)
567 upart2 = np.unique(part2)
568
569 # Plot the source and target samples as distributions
570 s = 20
571 fig = plt.figure(3, figsize=(6, 3))
572
573 ax1 = fig.add_subplot(1, 3, 1)
574 ax1.set_title("2D curve")
575 ax1.scatter(X[:, 0], X[:, 1], color="C0", alpha=FX, s=s)
576 plt.axis("off")
577
578
579 ax2 = fig.add_subplot(1, 3, 2)
580 ax2.set_title("Partitioning")
581 for i, elem in enumerate(upart1):
582 idx = np.argwhere(part1 == elem)[:, 0]
583 ax2.scatter(X[idx, 0], X[idx, 1], color="C%s" % i, alpha=FX[idx], s=s)
584 plt.axis("off")
585
586 ax3 = fig.add_subplot(1, 3, 3)
587 ax3.set_title("Representant selection")
588 for i, elem in enumerate(upart1):
589 idx = np.argwhere(part1 == elem)[:, 0]
590 ax3.scatter(X[idx, 0], X[idx, 1], color="C%s" % i, alpha=FX[idx], s=10)
591 rep_idx = rep_indices1[i]
592 ax3.scatter(
593 [X[rep_idx, 0]], [X[rep_idx, 1]], color="C%s" % i, alpha=1, s=6 * s, marker="*"
594 )
595 plt.axis("off")
596 plt.tight_layout()
597 plt.show()
598
599 start_color = upart1.shape[0] + 1
600
601 fig = plt.figure(4, figsize=(6, 5))
602
603 ax4 = fig.add_subplot(1, 3, 1, projection="3d")
604 ax4.set_title("3D curve")
605 ax4.scatter(Y[:, 0], Y[:, 1], Y[:, 2], c="C0", alpha=FY, s=s)
606 plt.axis("off")
607
608 ax5 = fig.add_subplot(1, 3, 2, projection="3d")
609 ax5.set_title("Partitioning")
610 for i, elem in enumerate(upart2):
611 idx = np.argwhere(part2 == elem)[:, 0]
612 color = "C%s" % (start_color + i)
613 ax5.scatter(Y[idx, 0], Y[idx, 1], Y[idx, 2], c=color, alpha=FY[idx], s=s)
614 plt.axis("off")
615
616 ax6 = fig.add_subplot(1, 3, 3, projection="3d")
617 ax6.set_title("Representant selection")
618 for i, elem in enumerate(upart2):
619 idx = np.argwhere(part2 == elem)[:, 0]
620 color = "C%s" % (start_color + i)
621 rep_idx = rep_indices2[i]
622 ax6.scatter(Y[idx, 0], Y[idx, 1], Y[idx, 2], c=color, alpha=FY[idx], s=s)
623 ax6.scatter(
624 [Y[rep_idx, 0]],
625 [Y[rep_idx, 1]],
626 [Y[rep_idx, 2]],
627 c=color,
628 alpha=1,
629 s=6 * s,
630 marker="*",
631 )
632 plt.axis("off")
633 plt.tight_layout()
634 plt.show()
635
636 #############################################################################
637 #
638 # Compute the quantized Fused Gromov-Wasserstein distance between samples using the wrapper
639 # ---------------------------------------------------------
640 #
641 # Compute qFGW(X, FX, hX, Y, FY, HY), setting the trade-off parameter between
642 # structures and features `alpha=0.5`. This solver considers a squared euclidean structure
643 # for each distribution X and Y, and partition each of them into 4 clusters using
644 # the K-means algorithm before computing qFGW.
645
646 T_global, Ts_local, T, log = quantized_fused_gromov_wasserstein_samples(
647 X,
648 Y,
649 4,
650 4,
651 p=None,
652 q=None,
653 F1=FX[:, None],
654 F2=FY[:, None],
655 alpha=0.5,
656 method="kmeans",
657 log=True,
658 )
659
660 # Plot low rank GW with different ranks
661 pl.figure(5, figsize=(6, 3))
662 pl.subplot(1, 2, 1)
663 pl.title("OT between distributions")
664 pl.imshow(T, interpolation="nearest", aspect="auto")
665 pl.colorbar()
666 pl.axis("off")
667
668 pl.subplot(1, 2, 2)
669 pl.title("OT between representants")
670 pl.imshow(T_global, interpolation="nearest", aspect="auto")
671 pl.axis("off")
672 pl.colorbar()
673
674 pl.tight_layout()
675 pl.show()