Debian Codegraph @

examples/gromov/plot_entropic_semirelaxed_fgw.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 ==========================
4 Entropic-regularized semi-relaxed (Fused) Gromov-Wasserstein example
5 ==========================
6
7 This example is designed to show how to use the entropic semi-relaxed Gromov-Wasserstein
8 and the entropic semi-relaxed Fused Gromov-Wasserstein divergences.
9
10 Entropic-regularized sr(F)GW between two graphs G1 and G2 searches for a reweighing of the nodes of
11 G2 at a minimal entropic-regularized (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 entropic_semirelaxed_gromov_wasserstein,
32 entropic_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 entropic-regularized 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_e(C2, h2, C3)
97 OT_23, log_23 = entropic_semirelaxed_gromov_wasserstein(
98 C2, C3, h2, symmetric=True, epsilon=1.0, G0=None, log=True
99 )
100 srgw_23 = log_23["srgw_dist"]
101
102 # 2) srGW_e(C3, h3, C2)
103
104 OT_32, log_32 = entropic_semirelaxed_gromov_wasserstein(
105 C3, C2, h3, symmetric=None, epsilon=1.0, G0=None, log=True
106 )
107 srgw_32 = log_32["srgw_dist"]
108
109 print("GW(C2, C3) = ", gw)
110 print("srGW_e(C2, h2, C3) = ", srgw_23)
111 print("srGW_e(C3, h3, C2) = ", srgw_32)
112
113
114 #############################################################################
115 #
116 # Visualization of the entropic-regularized 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 entropic srGW matching.
121 # We adjust the intensity of links across domains proportionaly to the mass
122 # sent, adding a minimal intensity of 0.1 if mass sent is not zero.
123
124
125 def draw_graph(
126 G,
127 C,
128 nodes_color_part,
129 Gweights=None,
130 pos=None,
131 edge_color="black",
132 node_size=None,
133 shiftx=0,
134 seed=0,
135 ):
136 if pos is None:
137 pos = networkx.spring_layout(G, scale=1.0, seed=seed)
138
139 if shiftx != 0:
140 for k, v in pos.items():
141 v[0] = v[0] + shiftx
142
143 alpha_edge = 0.7
144 width_edge = 1.8
145 if Gweights is None:
146 networkx.draw_networkx_edges(
147 G, pos, width=width_edge, alpha=alpha_edge, edge_color=edge_color
148 )
149 else:
150 # We make more visible connections between activated nodes
151 n = len(Gweights)
152 edgelist_activated = []
153 edgelist_deactivated = []
154 for i in range(n):
155 for j in range(n):
156 if Gweights[i] * Gweights[j] * C[i, j] > 0:
157 edgelist_activated.append((i, j))
158 elif C[i, j] > 0:
159 edgelist_deactivated.append((i, j))
160
161 networkx.draw_networkx_edges(
162 G,
163 pos,
164 edgelist=edgelist_activated,
165 width=width_edge,
166 alpha=alpha_edge,
167 edge_color=edge_color,
168 )
169 networkx.draw_networkx_edges(
170 G,
171 pos,
172 edgelist=edgelist_deactivated,
173 width=width_edge,
174 alpha=0.1,
175 edge_color=edge_color,
176 )
177
178 if Gweights is None:
179 for node, node_color in enumerate(nodes_color_part):
180 networkx.draw_networkx_nodes(
181 G,
182 pos,
183 nodelist=[node],
184 node_size=node_size,
185 alpha=1,
186 node_color=node_color,
187 )
188 else:
189 scaled_Gweights = Gweights / (0.5 * Gweights.max())
190 nodes_size = node_size * scaled_Gweights
191 for node, node_color in enumerate(nodes_color_part):
192 networkx.draw_networkx_nodes(
193 G,
194 pos,
195 nodelist=[node],
196 node_size=nodes_size[node],
197 alpha=1,
198 node_color=node_color,
199 )
200 return pos
201
202
203 def draw_transp_colored_srGW(
204 G1,
205 C1,
206 G2,
207 C2,
208 part_G1,
209 p1,
210 p2,
211 T,
212 pos1=None,
213 pos2=None,
214 shiftx=4,
215 switchx=False,
216 node_size=70,
217 seed_G1=0,
218 seed_G2=0,
219 ):
220 starting_color = 0
221 # get graphs partition and their coloring
222 part1 = part_G1.copy()
223 unique_colors = ["C%s" % (starting_color + i) for i in np.unique(part1)]
224 nodes_color_part1 = []
225 for cluster in part1:
226 nodes_color_part1.append(unique_colors[cluster])
227
228 nodes_color_part2 = []
229 # T: getting colors assignment from argmin of columns
230 for i in range(len(G2.nodes())):
231 j = np.argmax(T[:, i])
232 nodes_color_part2.append(nodes_color_part1[j])
233 pos1 = draw_graph(
234 G1,
235 C1,
236 nodes_color_part1,
237 Gweights=p1,
238 pos=pos1,
239 node_size=node_size,
240 shiftx=0,
241 seed=seed_G1,
242 )
243 pos2 = draw_graph(
244 G2,
245 C2,
246 nodes_color_part2,
247 Gweights=p2,
248 pos=pos2,
249 node_size=node_size,
250 shiftx=shiftx,
251 seed=seed_G2,
252 )
253 for k1, v1 in pos1.items():
254 max_Tk1 = np.max(T[k1, :])
255 for k2, v2 in pos2.items():
256 if T[k1, k2] > 0:
257 pl.plot(
258 [pos1[k1][0], pos2[k2][0]],
259 [pos1[k1][1], pos2[k2][1]],
260 "-",
261 lw=0.6,
262 alpha=min(T[k1, k2] / max_Tk1 + 0.1, 1.0),
263 color=nodes_color_part1[k1],
264 )
265 return pos1, pos2
266
267
268 node_size = 40
269 fontsize = 10
270 seed_G2 = 0
271 seed_G3 = 4
272
273 pl.figure(1, figsize=(8, 2.5))
274 pl.clf()
275 pl.subplot(121)
276 pl.axis("off")
277 pl.axis
278 pl.title(
279 r"$srGW_e(\mathbf{C_2},\mathbf{h_2},\mathbf{C_3}) =%s$" % (np.round(srgw_23, 3)),
280 fontsize=fontsize,
281 )
282
283 hbar2 = OT_23.sum(axis=0)
284 pos1, pos2 = draw_transp_colored_srGW(
285 weightedG2,
286 C2,
287 weightedG3,
288 C3,
289 part_G2,
290 p1=None,
291 p2=hbar2,
292 T=OT_23,
293 shiftx=1.5,
294 node_size=node_size,
295 seed_G1=seed_G2,
296 seed_G2=seed_G3,
297 )
298 pl.subplot(122)
299 pl.axis("off")
300 hbar3 = OT_32.sum(axis=0)
301 pl.title(
302 r"$srGW_e(\mathbf{C_3}, \mathbf{h_3},\mathbf{C_2}) =%s$" % (np.round(srgw_32, 3)),
303 fontsize=fontsize,
304 )
305 pos1, pos2 = draw_transp_colored_srGW(
306 weightedG3,
307 C3,
308 weightedG2,
309 C2,
310 part_G3,
311 p1=None,
312 p2=hbar3,
313 T=OT_32,
314 pos1=pos2,
315 pos2=pos1,
316 shiftx=3.0,
317 node_size=node_size,
318 seed_G1=0,
319 seed_G2=0,
320 )
321 pl.tight_layout()
322
323 pl.show()
324
325 #############################################################################
326 #
327 # Add node features
328 # ---------------------------------------------
329
330 # We add node features with given mean - by clusters
331 # and inversely proportional to clusters' intra-connectivity
332
333 F2 = np.zeros((N2, 1))
334 for i, c in enumerate(part_G2):
335 F2[i, 0] = np.random.normal(loc=c, scale=0.01)
336
337 F3 = np.zeros((N3, 1))
338 for i, c in enumerate(part_G3):
339 F3[i, 0] = np.random.normal(loc=2.0 - c, scale=0.01)
340
341 #############################################################################
342 #
343 # Compute their semi-relaxed Fused Gromov-Wasserstein divergences
344 # ---------------------------------------------
345
346 alpha = 0.5
347 # Compute pairwise euclidean distance between node features
348 M = (F2**2).dot(np.ones((1, N3))) + np.ones((N2, 1)).dot((F3**2).T) - 2 * F2.dot(F3.T)
349
350 # 0) FGW_alpha(C2, F2, h2, C3, F3, h3) for reference
351
352 OT, log = fused_gromov_wasserstein(
353 M, C2, C3, h2, h3, symmetric=True, alpha=alpha, log=True
354 )
355 fgw = log["fgw_dist"]
356
357 # 1) srFGW_e(C2, F2, h2, C3, F3)
358 OT_23, log_23 = entropic_semirelaxed_fused_gromov_wasserstein(
359 M, C2, C3, h2, symmetric=True, epsilon=1.0, alpha=0.5, log=True, G0=None
360 )
361 srfgw_23 = log_23["srfgw_dist"]
362
363 # 2) srFGW(C3, F3, h3, C2, F2)
364
365 OT_32, log_32 = entropic_semirelaxed_fused_gromov_wasserstein(
366 M.T, C3, C2, h3, symmetric=None, epsilon=1.0, alpha=alpha, log=True, G0=None
367 )
368 srfgw_32 = log_32["srfgw_dist"]
369
370 print("FGW(C2, F2, C3, F3) = ", fgw)
371 print(r"$srGW_e$(C2, F2, h2, C3, F3) = ", srfgw_23)
372 print(r"$srGW_e$(C3, F3, h3, C2, F2) = ", srfgw_32)
373
374 #############################################################################
375 #
376 # Visualization of the entropic semi-relaxed Fused Gromov-Wasserstein matchings
377 # ---------------------------------------------
378 #
379 # We color nodes of the graph on the right - then project its node colors
380 # based on the optimal transport plan from the srFGW matching
381 # NB: colors refer to clusters - not to node features
382
383 pl.figure(2, figsize=(8, 2.5))
384 pl.clf()
385 pl.subplot(121)
386 pl.axis("off")
387 pl.axis
388 pl.title(
389 r"$srFGW_e(\mathbf{C_2},\mathbf{F_2},\mathbf{h_2},\mathbf{C_3},\mathbf{F_3}) =%s$"
390 % (np.round(srfgw_23, 3)),
391 fontsize=fontsize,
392 )
393
394 hbar2 = OT_23.sum(axis=0)
395 pos1, pos2 = draw_transp_colored_srGW(
396 weightedG2,
397 C2,
398 weightedG3,
399 C3,
400 part_G2,
401 p1=None,
402 p2=hbar2,
403 T=OT_23,
404 shiftx=1.5,
405 node_size=node_size,
406 seed_G1=seed_G2,
407 seed_G2=seed_G3,
408 )
409 pl.subplot(122)
410 pl.axis("off")
411 hbar3 = OT_32.sum(axis=0)
412 pl.title(
413 r"$srFGW_e(\mathbf{C_3}, \mathbf{F_3}, \mathbf{h_3}, \mathbf{C_2}, \mathbf{F_2}) =%s$"
414 % (np.round(srfgw_32, 3)),
415 fontsize=fontsize,
416 )
417 pos1, pos2 = draw_transp_colored_srGW(
418 weightedG3,
419 C3,
420 weightedG2,
421 C2,
422 part_G3,
423 p1=None,
424 p2=hbar3,
425 T=OT_32,
426 pos1=pos2,
427 pos2=pos1,
428 shiftx=3.0,
429 node_size=node_size,
430 seed_G1=0,
431 seed_G2=0,
432 )
433 pl.tight_layout()
434
435 pl.show()