Debian Codegraph @

examples/gromov/plot_semirelaxed_fgw.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 ===============================================
4 Semi-relaxed (Fused) Gromov-Wasserstein example
5 ===============================================
6
7 This example is designed to show how to use the semi-relaxed Gromov-Wasserstein
8 and the semi-relaxed Fused Gromov-Wasserstein divergences.
9
10 sr(F)GW between two graphs G1 and G2 searches for a reweighing of the nodes of
11 G2 at a minimal (F)GW distance from G1.
12
13 First, we generate two graphs following Stochastic Block Models, then show
14 how to compute their srGW matchings and illustrate them. These graphs are then
15 endowed with node features and we follow the same process with srFGW.
16
17 [48] Cédric Vincent-Cuaz, Rémi Flamary, Marco Corneli, Titouan Vayer, Nicolas Courty.
18 "Semi-relaxed Gromov-Wasserstein divergence and applications on graphs"
19 International Conference on Learning Representations (ICLR), 2021.
20 """
21
22 # Author: Cédric Vincent-Cuaz <[email protected]>
23 #
24 # License: MIT License
25
26 # sphinx_gallery_thumbnail_number = 1
27
28 import numpy as np
29 import matplotlib.pylab as pl
30 from ot.gromov import (
31 semirelaxed_gromov_wasserstein,
32 semirelaxed_fused_gromov_wasserstein,
33 gromov_wasserstein,
34 fused_gromov_wasserstein,
35 )
36 import networkx
37 from networkx.generators.community import stochastic_block_model as sbm
38
39 #############################################################################
40 #
41 # Generate two graphs following Stochastic Block models of 2 and 3 clusters.
42 # --------------------------------------------------------------------------
43
44
45 N2 = 20 # 2 communities
46 N3 = 30 # 3 communities
47 p2 = [[1.0, 0.1], [0.1, 0.9]]
48 p3 = [[1.0, 0.1, 0.0], [0.1, 0.95, 0.1], [0.0, 0.1, 0.9]]
49 G2 = sbm(seed=0, sizes=[N2 // 2, N2 // 2], p=p2)
50 G3 = sbm(seed=0, sizes=[N3 // 3, N3 // 3, N3 // 3], p=p3)
51
52
53 C2 = networkx.to_numpy_array(G2)
54 C3 = networkx.to_numpy_array(G3)
55
56 h2 = np.ones(C2.shape[0]) / C2.shape[0]
57 h3 = np.ones(C3.shape[0]) / C3.shape[0]
58
59 # Add weights on the edges for visualization later on
60 weight_intra_G2 = 5
61 weight_inter_G2 = 0.5
62 weight_intra_G3 = 1.0
63 weight_inter_G3 = 1.5
64
65 weightedG2 = networkx.Graph()
66 part_G2 = [G2.nodes[i]["block"] for i in range(N2)]
67
68 for node in G2.nodes():
69 weightedG2.add_node(node)
70 for i, j in G2.edges():
71 if part_G2[i] == part_G2[j]:
72 weightedG2.add_edge(i, j, weight=weight_intra_G2)
73 else:
74 weightedG2.add_edge(i, j, weight=weight_inter_G2)
75
76 weightedG3 = networkx.Graph()
77 part_G3 = [G3.nodes[i]["block"] for i in range(N3)]
78
79 for node in G3.nodes():
80 weightedG3.add_node(node)
81 for i, j in G3.edges():
82 if part_G3[i] == part_G3[j]:
83 weightedG3.add_edge(i, j, weight=weight_intra_G3)
84 else:
85 weightedG3.add_edge(i, j, weight=weight_inter_G3)
86
87 #############################################################################
88 #
89 # Compute their semi-relaxed Gromov-Wasserstein divergences
90 # ---------------------------------------------------------
91
92 # 0) GW(C2, h2, C3, h3) for reference
93 OT, log = gromov_wasserstein(C2, C3, h2, h3, symmetric=True, log=True)
94 gw = log["gw_dist"]
95
96 # 1) srGW(C2, h2, C3)
97 OT_23, log_23 = semirelaxed_gromov_wasserstein(
98 C2, C3, h2, symmetric=True, log=True, G0=None
99 )
100 srgw_23 = log_23["srgw_dist"]
101
102 # 2) srGW(C3, h3, C2)
103
104 OT_32, log_32 = semirelaxed_gromov_wasserstein(
105 C3, C2, h3, symmetric=None, log=True, G0=OT.T
106 )
107 srgw_32 = log_32["srgw_dist"]
108
109 print("GW(C2, C3) = ", gw)
110 print("srGW(C2, h2, C3) = ", srgw_23)
111 print("srGW(C3, h3, C2) = ", srgw_32)
112
113
114 #############################################################################
115 #
116 # Visualization of the semi-relaxed Gromov-Wasserstein matchings
117 # --------------------------------------------------------------
118 #
119 # We color nodes of the graph on the right - then project its node colors
120 # based on the optimal transport plan from the srGW matching
121
122
123 def draw_graph(
124 G,
125 C,
126 nodes_color_part,
127 Gweights=None,
128 pos=None,
129 edge_color="black",
130 node_size=None,
131 shiftx=0,
132 seed=0,
133 ):
134 if pos is None:
135 pos = networkx.spring_layout(G, scale=1.0, seed=seed)
136
137 if shiftx != 0:
138 for k, v in pos.items():
139 v[0] = v[0] + shiftx
140
141 alpha_edge = 0.7
142 width_edge = 1.8
143 if Gweights is None:
144 networkx.draw_networkx_edges(
145 G, pos, width=width_edge, alpha=alpha_edge, edge_color=edge_color
146 )
147 else:
148 # We make more visible connections between activated nodes
149 n = len(Gweights)
150 edgelist_activated = []
151 edgelist_deactivated = []
152 for i in range(n):
153 for j in range(n):
154 if Gweights[i] * Gweights[j] * C[i, j] > 0:
155 edgelist_activated.append((i, j))
156 elif C[i, j] > 0:
157 edgelist_deactivated.append((i, j))
158
159 networkx.draw_networkx_edges(
160 G,
161 pos,
162 edgelist=edgelist_activated,
163 width=width_edge,
164 alpha=alpha_edge,
165 edge_color=edge_color,
166 )
167 networkx.draw_networkx_edges(
168 G,
169 pos,
170 edgelist=edgelist_deactivated,
171 width=width_edge,
172 alpha=0.1,
173 edge_color=edge_color,
174 )
175
176 if Gweights is None:
177 for node, node_color in enumerate(nodes_color_part):
178 networkx.draw_networkx_nodes(
179 G,
180 pos,
181 nodelist=[node],
182 node_size=node_size,
183 alpha=1,
184 node_color=node_color,
185 )
186 else:
187 scaled_Gweights = Gweights / (0.5 * Gweights.max())
188 nodes_size = node_size * scaled_Gweights
189 for node, node_color in enumerate(nodes_color_part):
190 networkx.draw_networkx_nodes(
191 G,
192 pos,
193 nodelist=[node],
194 node_size=nodes_size[node],
195 alpha=1,
196 node_color=node_color,
197 )
198 return pos
199
200
201 def draw_transp_colored_srGW(
202 G1,
203 C1,
204 G2,
205 C2,
206 part_G1,
207 p1,
208 p2,
209 T,
210 pos1=None,
211 pos2=None,
212 shiftx=4,
213 switchx=False,
214 node_size=70,
215 seed_G1=0,
216 seed_G2=0,
217 ):
218 starting_color = 0
219 # get graphs partition and their coloring
220 part1 = part_G1.copy()
221 unique_colors = ["C%s" % (starting_color + i) for i in np.unique(part1)]
222 nodes_color_part1 = []
223 for cluster in part1:
224 nodes_color_part1.append(unique_colors[cluster])
225
226 nodes_color_part2 = []
227 # T: getting colors assignment from argmin of columns
228 for i in range(len(G2.nodes())):
229 j = np.argmax(T[:, i])
230 nodes_color_part2.append(nodes_color_part1[j])
231 pos1 = draw_graph(
232 G1,
233 C1,
234 nodes_color_part1,
235 Gweights=p1,
236 pos=pos1,
237 node_size=node_size,
238 shiftx=0,
239 seed=seed_G1,
240 )
241 pos2 = draw_graph(
242 G2,
243 C2,
244 nodes_color_part2,
245 Gweights=p2,
246 pos=pos2,
247 node_size=node_size,
248 shiftx=shiftx,
249 seed=seed_G2,
250 )
251 for k1, v1 in pos1.items():
252 for k2, v2 in pos2.items():
253 if T[k1, k2] > 0:
254 pl.plot(
255 [pos1[k1][0], pos2[k2][0]],
256 [pos1[k1][1], pos2[k2][1]],
257 "-",
258 lw=0.8,
259 alpha=0.5,
260 color=nodes_color_part1[k1],
261 )
262 return pos1, pos2
263
264
265 node_size = 40
266 fontsize = 10
267 seed_G2 = 0
268 seed_G3 = 4
269
270 pl.figure(1, figsize=(8, 2.5))
271 pl.clf()
272 pl.subplot(121)
273 pl.axis("off")
274 pl.axis
275 pl.title(
276 r"srGW$(\mathbf{C_2},\mathbf{h_2},\mathbf{C_3}) =%s$" % (np.round(srgw_23, 3)),
277 fontsize=fontsize,
278 )
279
280 hbar2 = OT_23.sum(axis=0)
281 pos1, pos2 = draw_transp_colored_srGW(
282 weightedG2,
283 C2,
284 weightedG3,
285 C3,
286 part_G2,
287 p1=None,
288 p2=hbar2,
289 T=OT_23,
290 shiftx=1.5,
291 node_size=node_size,
292 seed_G1=seed_G2,
293 seed_G2=seed_G3,
294 )
295 pl.subplot(122)
296 pl.axis("off")
297 hbar3 = OT_32.sum(axis=0)
298 pl.title(
299 r"srGW$(\mathbf{C_3}, \mathbf{h_3},\mathbf{C_2}) =%s$" % (np.round(srgw_32, 3)),
300 fontsize=fontsize,
301 )
302 pos1, pos2 = draw_transp_colored_srGW(
303 weightedG3,
304 C3,
305 weightedG2,
306 C2,
307 part_G3,
308 p1=None,
309 p2=hbar3,
310 T=OT_32,
311 pos1=pos2,
312 pos2=pos1,
313 shiftx=3.0,
314 node_size=node_size,
315 seed_G1=0,
316 seed_G2=0,
317 )
318 pl.tight_layout()
319
320 pl.show()
321
322 #############################################################################
323 #
324 # Add node features
325 # -----------------
326
327 # We add node features with given mean - by clusters
328 # and inversely proportional to clusters' intra-connectivity
329
330 F2 = np.zeros((N2, 1))
331 for i, c in enumerate(part_G2):
332 F2[i, 0] = np.random.normal(loc=c, scale=0.01)
333
334 F3 = np.zeros((N3, 1))
335 for i, c in enumerate(part_G3):
336 F3[i, 0] = np.random.normal(loc=2.0 - c, scale=0.01)
337
338 #############################################################################
339 #
340 # Compute their semi-relaxed Fused Gromov-Wasserstein divergences
341 # ---------------------------------------------------------------
342
343 alpha = 0.5
344 # Compute pairwise euclidean distance between node features
345 M = (F2**2).dot(np.ones((1, N3))) + np.ones((N2, 1)).dot((F3**2).T) - 2 * F2.dot(F3.T)
346
347 # 0) FGW_alpha(C2, F2, h2, C3, F3, h3) for reference
348
349 OT, log = fused_gromov_wasserstein(
350 M, C2, C3, h2, h3, symmetric=True, alpha=alpha, log=True
351 )
352 fgw = log["fgw_dist"]
353
354 # 1) srFGW(C2, F2, h2, C3, F3)
355 OT_23, log_23 = semirelaxed_fused_gromov_wasserstein(
356 M, C2, C3, h2, symmetric=True, alpha=0.5, log=True, G0=None
357 )
358 srfgw_23 = log_23["srfgw_dist"]
359
360 # 2) srFGW(C3, F3, h3, C2, F2)
361
362 OT_32, log_32 = semirelaxed_fused_gromov_wasserstein(
363 M.T, C3, C2, h3, symmetric=None, alpha=alpha, log=True, G0=None
364 )
365 srfgw_32 = log_32["srfgw_dist"]
366
367 print("FGW(C2, F2, C3, F3) = ", fgw)
368 print("srGW(C2, F2, h2, C3, F3) = ", srfgw_23)
369 print("srGW(C3, F3, h3, C2, F2) = ", srfgw_32)
370
371 #############################################################################
372 #
373 # Visualization of the semi-relaxed Fused Gromov-Wasserstein matchings
374 # --------------------------------------------------------------------
375 #
376 # We color nodes of the graph on the right - then project its node colors
377 # based on the optimal transport plan from the srFGW matching
378 # NB: colors refer to clusters - not to node features
379
380 pl.figure(2, figsize=(8, 2.5))
381 pl.clf()
382 pl.subplot(121)
383 pl.axis("off")
384 pl.axis
385 pl.title(
386 r"srFGW$(\mathbf{C_2},\mathbf{F_2},\mathbf{h_2},\mathbf{C_3},\mathbf{F_3}) =%s$"
387 % (np.round(srfgw_23, 3)),
388 fontsize=fontsize,
389 )
390
391 hbar2 = OT_23.sum(axis=0)
392 pos1, pos2 = draw_transp_colored_srGW(
393 weightedG2,
394 C2,
395 weightedG3,
396 C3,
397 part_G2,
398 p1=None,
399 p2=hbar2,
400 T=OT_23,
401 shiftx=1.5,
402 node_size=node_size,
403 seed_G1=seed_G2,
404 seed_G2=seed_G3,
405 )
406 pl.subplot(122)
407 pl.axis("off")
408 hbar3 = OT_32.sum(axis=0)
409 pl.title(
410 r"srFGW$(\mathbf{C_3}, \mathbf{F_3}, \mathbf{h_3}, \mathbf{C_2}, \mathbf{F_2}) =%s$"
411 % (np.round(srfgw_32, 3)),
412 fontsize=fontsize,
413 )
414 pos1, pos2 = draw_transp_colored_srGW(
415 weightedG3,
416 C3,
417 weightedG2,
418 C2,
419 part_G3,
420 p1=None,
421 p2=hbar3,
422 T=OT_32,
423 pos1=pos2,
424 pos2=pos1,
425 shiftx=3.0,
426 node_size=node_size,
427 seed_G1=0,
428 seed_G2=0,
429 )
430 pl.tight_layout()
431
432 pl.show()