Debian Codegraph @

ot/gnn/_utils.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 GNN layers utils
4 """
5
6 # Author: Sonia Mazelet <[email protected]>
7 # Rémi Flamary <[email protected]>
8 #
9 # License: MIT License
10
11 import torch
12 from ..utils import dist
13 from ..gromov import fused_gromov_wasserstein2
14 from ..lp import emd2
15 from torch_geometric.utils import subgraph
16
17
18 def TFGW_template_initialization(
19 n_tplt, n_tplt_nodes, n_features, feature_init_mean=0.0, feature_init_std=1.0
20 ):
21 """
22 Initializes templates for the Template Fused Gromov Wasserstein layer.
23 Returns the adjacency matrices and the features of the nodes of the templates.
24 Adjacency matrices are initialized uniformly with values in :math:`[0,1]`.
25 Node features are initialized following a normal distribution.
26
27 Parameters
28 ----------
29
30 n_tplt: int
31 Number of templates.
32 n_tplt_nodes: int
33 Number of nodes per template.
34 n_features: int
35 Number of features for the nodes.
36 feature_init_mean: float, optional
37 Mean of the random normal law to initialize the template features.
38 feature_init_std: float, optional
39 Standard deviation of the random normal law to initialize the template features.
40
41 Returns
42 ----------
43 tplt_adjacencies: torch.Tensor, shape (n_templates, n_template_nodes, n_template_nodes)
44 Adjacency matrices for the templates.
45 tplt_features: torch.Tensor, shape (n_templates, n_template_nodes, n_features)
46 Node features for each template.
47 q: torch.Tensor, shape (n_templates, n_template_nodes)
48 weight on the template nodes.
49 """
50
51 tplt_adjacencies = torch.rand((n_tplt, n_tplt_nodes, n_tplt_nodes))
52 tplt_features = torch.Tensor(n_tplt, n_tplt_nodes, n_features)
53
54 torch.nn.init.normal_(tplt_features, mean=feature_init_mean, std=feature_init_std)
55
56 q = torch.zeros(n_tplt, n_tplt_nodes)
57
58 tplt_adjacencies = 0.5 * (
59 tplt_adjacencies + torch.transpose(tplt_adjacencies, 1, 2)
60 )
61
62 return tplt_adjacencies, tplt_features, q
63
64
65 def FGW_distance_to_templates(
66 G_edges,
67 tplt_adjacencies,
68 G_features,
69 tplt_features,
70 tplt_weights,
71 alpha=0.5,
72 multi_alpha=False,
73 batch=None,
74 ):
75 """
76 Computes the FGW distances between a graph and templates.
77
78 Parameters
79 ----------
80 G_edges : torch.Tensor, shape (n_edges, 2)
81 Edge indices of the graph in the Pytorch Geometric format.
82 tplt_adjacencies : list of torch.Tensor, shape (n_templates, n_template_nodes, n_templates_nodes)
83 List of the adjacency matrices of the templates.
84 G_features : torch.Tensor, shape (n_nodes, n_features)
85 Graph node features.
86 tplt_features : list of torch.Tensor, shape (n_templates, n_template_nodes, n_features)
87 List of the node features of the templates.
88 weights : torch.Tensor, shape (n_templates, n_template_nodes)
89 Weights on the nodes of the templates.
90 alpha : float, optional
91 Trade-off parameter (0 < alpha < 1).
92 Weights features (alpha=0) and structure (alpha=1).
93 multi_alpha: bool, optional
94 If True, the alpha parameter is a vector of size n_templates.
95 batch: torch.Tensor, optional
96 Batch vector which assigns each node to its graph.
97
98 Returns
99 -------
100 distances : torch.Tensor, shape (n_templates) if batch=None, else shape (n_graphs, n_templates).
101 Vector of fused Gromov-Wasserstein distances between the graph and the templates.
102 """
103
104 if batch is None:
105 n, n_feat = G_features.shape
106 n_T, _, n_feat_T = tplt_features.shape
107
108 weights_G = torch.ones(n) / n
109
110 C = torch.sparse_coo_tensor(
111 G_edges, torch.ones(len(G_edges[0])), size=(n, n)
112 ).type(torch.float)
113 C = C.to_dense()
114
115 if not n_feat == n_feat_T:
116 raise ValueError(
117 "The templates and the graphs must have the same feature dimension."
118 )
119
120 distances = torch.zeros(n_T)
121
122 for j in range(n_T):
123 template_features = tplt_features[j].reshape(
124 len(tplt_features[j]), n_feat_T
125 )
126 M = dist(G_features, template_features).type(torch.float)
127
128 # if alpha is zero the emd distance is used
129 if multi_alpha and torch.any(alpha > 0):
130 embedding = fused_gromov_wasserstein2(
131 M,
132 C,
133 tplt_adjacencies[j],
134 weights_G,
135 tplt_weights[j],
136 alpha=alpha[j],
137 symmetric=True,
138 max_iter=50,
139 )
140 elif not multi_alpha and torch.all(alpha == 0):
141 embedding = emd2(weights_G, tplt_weights[j], M, numItermax=50)
142 elif not multi_alpha and alpha > 0:
143 embedding = fused_gromov_wasserstein2(
144 M,
145 C,
146 tplt_adjacencies[j],
147 weights_G,
148 tplt_weights[j],
149 alpha=alpha,
150 symmetric=True,
151 max_iter=50,
152 )
153 else:
154 embedding = emd2(weights_G, tplt_weights[j], M, numItermax=50)
155
156 distances[j] = embedding
157
158 else:
159 n_T, _, n_feat_T = tplt_features.shape
160
161 num_graphs = torch.max(batch) + 1
162 distances = torch.zeros(num_graphs, n_T)
163
164 # iterate over the graphs in the batch
165 for i in range(num_graphs):
166 nodes = torch.where(batch == i)[0]
167
168 G_edges_i, _ = subgraph(nodes, edge_index=G_edges, relabel_nodes=True)
169 G_features_i = G_features[nodes]
170
171 n, n_feat = G_features_i.shape
172
173 weights_G = torch.ones(n) / n
174
175 n_edges = len(G_edges_i[0])
176
177 C = torch.sparse_coo_tensor(
178 G_edges_i, torch.ones(n_edges), size=(n, n)
179 ).type(torch.float)
180 C = C.to_dense()
181
182 if not n_feat == n_feat_T:
183 raise ValueError(
184 "The templates and the graphs must have the same feature dimension."
185 )
186
187 for j in range(n_T):
188 template_features = tplt_features[j].reshape(
189 len(tplt_features[j]), n_feat_T
190 )
191 M = dist(G_features_i, template_features).type(torch.float)
192
193 # if alpha is zero the emd distance is used
194 if multi_alpha and torch.any(alpha > 0):
195 embedding = fused_gromov_wasserstein2(
196 M,
197 C,
198 tplt_adjacencies[j],
199 weights_G,
200 tplt_weights[j],
201 alpha=alpha[j],
202 symmetric=True,
203 max_iter=50,
204 )
205 elif not multi_alpha and torch.all(alpha == 0):
206 embedding = emd2(weights_G, tplt_weights[j], M, numItermax=50)
207 elif not multi_alpha and alpha > 0:
208 embedding = fused_gromov_wasserstein2(
209 M,
210 C,
211 tplt_adjacencies[j],
212 weights_G,
213 tplt_weights[j],
214 alpha=alpha,
215 symmetric=True,
216 max_iter=50,
217 )
218 else:
219 embedding = emd2(weights_G, tplt_weights[j], M, numItermax=50)
220
221 distances[i, j] = embedding
222
223 return distances
224
225
226 def wasserstein_distance_to_templates(
227 G_features, tplt_features, tplt_weights, batch=None
228 ):
229 """
230 Computes the Wasserstein distances between a graph and graph templates.
231
232 Parameters
233 ----------
234 G_features : torch.Tensor, shape (n_nodes, n_features)
235 Node features of the graph.
236 tplt_features : list of torch.Tensor, shape (n_templates, n_template_nodes, n_features)
237 List of the node features of the templates.
238 weights : torch.Tensor, shape (n_templates, n_template_nodes)
239 Weights on the nodes of the templates.
240 batch: torch.Tensor, optional
241 Batch vector which assigns each node to its graph.
242
243 Returns
244 -------
245 distances : torch.Tensor, shape (n_templates) if batch=None, else shape (n_graphs, n_templates)
246 Vector of Wasserstein distances between the graph and the templates.
247 """
248
249 if batch is None:
250 n, n_feat = G_features.shape
251 n_T, _, n_feat_T = tplt_features.shape
252
253 weights_G = torch.ones(n) / n
254
255 if not n_feat == n_feat_T:
256 raise ValueError(
257 "The templates and the graphs must have the same feature dimension."
258 )
259
260 distances = torch.zeros(n_T)
261
262 for j in range(n_T):
263 template_features = tplt_features[j].reshape(
264 len(tplt_features[j]), n_feat_T
265 )
266 M = dist(G_features, template_features).type(torch.float)
267
268 distances[j] = emd2(weights_G, tplt_weights[j], M, numItermax=50)
269
270 else:
271 n_T, _, n_feat_T = tplt_features.shape
272
273 num_graphs = torch.max(batch) + 1
274 distances = torch.zeros(num_graphs, n_T)
275
276 # iterate over the graphs in the batch
277 for i in range(num_graphs):
278 nodes = torch.where(batch == i)[0]
279
280 G_features_i = G_features[nodes]
281
282 n, n_feat = G_features_i.shape
283
284 weights_G = torch.ones(n) / n
285
286 if not n_feat == n_feat_T:
287 raise ValueError(
288 "The templates and the graphs must have the same feature dimension."
289 )
290
291 for j in range(n_T):
292 template_features = tplt_features[j].reshape(
293 len(tplt_features[j]), n_feat_T
294 )
295 M = dist(G_features_i, template_features).type(torch.float)
296
297 distances[i, j] = emd2(weights_G, tplt_weights[j], M, numItermax=50)
298
299 return distances