Debian Codegraph @

examples/gromov/plot_barycenter_fgw.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 =================================
4 Plot graphs barycenter using FGW
5 =================================
6
7 This example illustrates the computation barycenter of labeled graphs using
8 FGW [18].
9
10 Requires networkx >=2
11
12 [18] Vayer Titouan, Chapel Laetitia, Flamary Rémi, Tavenard Romain
13 and Courty Nicolas
14 "Optimal Transport for structured data with application on graphs"
15 International Conference on Machine Learning (ICML). 2019.
16
17 """
18
19 # Author: Titouan Vayer <[email protected]>
20 #
21 # License: MIT License
22
23 # %% load libraries
24 import numpy as np
25 import matplotlib.pyplot as plt
26 import networkx as nx
27 import math
28 from scipy.sparse.csgraph import shortest_path
29 import matplotlib.colors as mcol
30 from matplotlib import cm
31 from ot.gromov import fgw_barycenters
32 # %% Graph functions
33
34
35 def find_thresh(C, inf=0.5, sup=3, step=10):
36 """Trick to find the adequate thresholds from where value of the C matrix are considered close enough to say that nodes are connected
37 The threshold is found by a linesearch between values "inf" and "sup" with "step" thresholds tested.
38 The optimal threshold is the one which minimizes the reconstruction error between the shortest_path matrix coming from the thresholded adjacency matrix
39 and the original matrix.
40 Parameters
41 ----------
42 C : ndarray, shape (n_nodes,n_nodes)
43 The structure matrix to threshold
44 inf : float
45 The beginning of the linesearch
46 sup : float
47 The end of the linesearch
48 step : integer
49 Number of thresholds tested
50 """
51 dist = []
52 search = np.linspace(inf, sup, step)
53 for thresh in search:
54 Cprime = sp_to_adjacency(C, 0, thresh)
55 SC = shortest_path(Cprime, method="D")
56 SC[SC == float("inf")] = 100
57 dist.append(np.linalg.norm(SC - C))
58 return search[np.argmin(dist)], dist
59
60
61 def sp_to_adjacency(C, threshinf=0.2, threshsup=1.8):
62 """Thresholds the structure matrix in order to compute an adjacency matrix.
63 All values between threshinf and threshsup are considered representing connected nodes and set to 1. Else are set to 0
64 Parameters
65 ----------
66 C : ndarray, shape (n_nodes,n_nodes)
67 The structure matrix to threshold
68 threshinf : float
69 The minimum value of distance from which the new value is set to 1
70 threshsup : float
71 The maximum value of distance from which the new value is set to 1
72 Returns
73 -------
74 C : ndarray, shape (n_nodes,n_nodes)
75 The threshold matrix. Each element is in {0,1}
76 """
77 H = np.zeros_like(C)
78 np.fill_diagonal(H, np.diagonal(C))
79 C = C - H
80 C = np.minimum(np.maximum(C, threshinf), threshsup)
81 C[C == threshsup] = 0
82 C[C != 0] = 1
83
84 return C
85
86
87 def build_noisy_circular_graph(
88 N=20, mu=0, sigma=0.3, with_noise=False, structure_noise=False, p=None
89 ):
90 """Create a noisy circular graph"""
91 g = nx.Graph()
92 g.add_nodes_from(list(range(N)))
93 for i in range(N):
94 noise = float(np.random.normal(mu, sigma, 1))
95 if with_noise:
96 g.add_node(i, attr_name=math.sin((2 * i * math.pi / N)) + noise)
97 else:
98 g.add_node(i, attr_name=math.sin(2 * i * math.pi / N))
99 g.add_edge(i, i + 1)
100 if structure_noise:
101 randomint = np.random.randint(0, p)
102 if randomint == 0:
103 if i <= N - 3:
104 g.add_edge(i, i + 2)
105 if i == N - 2:
106 g.add_edge(i, 0)
107 if i == N - 1:
108 g.add_edge(i, 1)
109 g.add_edge(N, 0)
110 noise = float(np.random.normal(mu, sigma, 1))
111 if with_noise:
112 g.add_node(N, attr_name=math.sin((2 * N * math.pi / N)) + noise)
113 else:
114 g.add_node(N, attr_name=math.sin(2 * N * math.pi / N))
115 return g
116
117
118 def graph_colors(nx_graph, vmin=0, vmax=7):
119 cnorm = mcol.Normalize(vmin=vmin, vmax=vmax)
120 cpick = cm.ScalarMappable(norm=cnorm, cmap="viridis")
121 cpick.set_array([])
122 val_map = {}
123 for k, v in nx.get_node_attributes(nx_graph, "attr_name").items():
124 val_map[k] = cpick.to_rgba(v)
125 colors = []
126 for node in nx_graph.nodes():
127 colors.append(val_map[node])
128 return colors
129
130
131 ##############################################################################
132 # Generate data
133 # -------------
134
135 # %% circular dataset
136 # We build a dataset of noisy circular graphs.
137 # Noise is added on the structures by random connections and on the features by gaussian noise.
138
139
140 np.random.seed(30)
141 X0 = []
142 for k in range(9):
143 X0.append(
144 build_noisy_circular_graph(
145 np.random.randint(15, 25), with_noise=True, structure_noise=True, p=3
146 )
147 )
148
149 ##############################################################################
150 # Plot data
151 # ---------
152
153 # %% Plot graphs
154
155 plt.figure(figsize=(8, 10))
156 for i in range(len(X0)):
157 plt.subplot(3, 3, i + 1)
158 g = X0[i]
159 pos = nx.kamada_kawai_layout(g)
160 nx.draw(
161 g,
162 pos=pos,
163 node_color=graph_colors(g, vmin=-1, vmax=1),
164 with_labels=False,
165 node_size=100,
166 )
167 plt.suptitle("Dataset of noisy graphs. Color indicates the label", fontsize=20)
168 plt.show()
169
170 ##############################################################################
171 # Barycenter computation
172 # ----------------------
173
174 # %% We compute the barycenter using FGW. Structure matrices are computed using the shortest_path distance in the graph
175 # Features distances are the euclidean distances
176 Cs = [shortest_path(nx.adjacency_matrix(x).todense()) for x in X0]
177 ps = [np.ones(len(x.nodes())) / len(x.nodes()) for x in X0]
178 Ys = [
179 np.array([v for (k, v) in nx.get_node_attributes(x, "attr_name").items()]).reshape(
180 -1, 1
181 )
182 for x in X0
183 ]
184 lambdas = np.array([np.ones(len(Ys)) / len(Ys)]).ravel()
185 sizebary = 15 # we choose a barycenter with 15 nodes
186
187 A, C, log = fgw_barycenters(sizebary, Ys, Cs, ps, lambdas, alpha=0.95, log=True)
188
189 ##############################################################################
190 # Plot Barycenter
191 # -------------------------
192
193 # %% Create the barycenter
194 bary = nx.from_numpy_array(
195 sp_to_adjacency(C, threshinf=0, threshsup=find_thresh(C, sup=100, step=100)[0])
196 )
197 for i, v in enumerate(A.ravel()):
198 bary.add_node(i, attr_name=v)
199
200 # %%
201 pos = nx.kamada_kawai_layout(bary)
202 nx.draw(
203 bary, pos=pos, node_color=graph_colors(bary, vmin=-1, vmax=1), with_labels=False
204 )
205 plt.suptitle("Barycenter", fontsize=20)
206 plt.show()