-
Notifications
You must be signed in to change notification settings - Fork 1
/
gnn_explainer.py
369 lines (294 loc) · 13.6 KB
/
gnn_explainer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
from copy import copy
from math import sqrt
from typing import Optional
import torch
from tqdm import tqdm
import matplotlib.pyplot as plt
import networkx as nx
from torch_geometric.nn import MessagePassing
from torch_geometric.data import Data
from torch_geometric.utils import k_hop_subgraph, to_networkx
import numpy as np
import time
plt.switch_backend('agg')
EPS = 1e-15
class GNNExplainer(torch.nn.Module):
r"""The GNN-Explainer model from the `"GNNExplainer: Generating
Explanations for Graph Neural Networks"
<https://arxiv.org/abs/1903.03894>`_ paper for identifying compact subgraph
structures and small subsets node features that play a crucial role in a
GNN’s node-predictions.
.. note::
For an example of using GNN-Explainer, see `examples/gnn_explainer.py
<https://github.com/rusty1s/pytorch_geometric/blob/master/examples/
gnn_explainer.py>`_.
Args:
model (torch.nn.Module): The GNN module to explain.
epochs (int, optional): The number of epochs to train.
(default: :obj:`100`)
lr (float, optional): The learning rate to apply.
(default: :obj:`0.01`)
num_hops (int, optional): The number of hops the :obj:`model` is
aggregating information from.
If set to :obj:`None`, will automatically try to detect this
information based on the number of
:class:`~torch_geometric.nn.conv.message_passing.MessagePassing`
layers inside :obj:`model`. (default: :obj:`None`)
log (bool, optional): If set to :obj:`False`, will not log any learning
progress. (default: :obj:`True`)
"""
coeffs = {
'edge_size': 0.005,
'edge_reduction': 'sum',
'node_feat_size': 1.0,
'node_feat_reduction': 'mean',
'edge_ent': 1.0,
'node_feat_ent': 0.1,
}
def __init__(self, model, epochs: int = 100, lr: float = 0.01,
num_hops: Optional[int] = None, log: bool = True):
super(GNNExplainer, self).__init__()
self.model = model
self.epochs = epochs
self.lr = lr
self.__num_hops__ = num_hops
self.log = log
def __set_masks__(self, x, edge_index, init="normal"):
(N, F), E = x.size(), edge_index.size(1)
std = 0.1
self.node_feat_mask = torch.nn.Parameter(torch.randn(F) * 0.1)
std = torch.nn.init.calculate_gain('relu') * sqrt(2.0 / (2 * N))
self.edge_mask = torch.nn.Parameter(torch.randn(E) * std)
for module in self.model.modules():
if isinstance(module, MessagePassing):
module.__explain__ = True
module.__edge_mask__ = self.edge_mask
def __clear_masks__(self):
for module in self.model.modules():
if isinstance(module, MessagePassing):
module.__explain__ = False
module.__edge_mask__ = None
self.node_feat_masks = None
self.edge_mask = None
@property
def num_hops(self):
if self.__num_hops__ is not None:
return self.__num_hops__
k = 0
for module in self.model.modules():
if isinstance(module, MessagePassing):
k += 1
return k
def __flow__(self):
for module in self.model.modules():
if isinstance(module, MessagePassing):
return module.flow
return 'source_to_target'
def __subgraph__(self, node_idx, x, edge_index, **kwargs):
num_nodes, num_edges = x.size(0), edge_index.size(1)
subset, edge_index, mapping, edge_mask = k_hop_subgraph(
node_idx, self.num_hops, edge_index, relabel_nodes=True,
num_nodes=num_nodes, flow=self.__flow__())
x = x[subset]
for key, item in kwargs.items():
if torch.is_tensor(item) and item.size(0) == num_nodes:
item = item[subset]
elif torch.is_tensor(item) and item.size(0) == num_edges:
item = item[edge_mask]
kwargs[key] = item
return x, edge_index, mapping, edge_mask, kwargs
def __loss__(self, node_idx, log_logits, pred_label):
# loss = -log_logits[node_idx, pred_label[node_idx]]
# loss = -log_logits[node_idx]
loss = abs(log_logits[node_idx] - pred_label[node_idx])
# print(loss)
m = self.edge_mask.sigmoid()
edge_reduce = getattr(torch, self.coeffs['edge_reduction'])
loss = loss + self.coeffs['edge_size'] * edge_reduce(m)
ent = -m * torch.log(m + EPS) - (1 - m) * torch.log(1 - m + EPS)
loss = loss + self.coeffs['edge_ent'] * ent.mean()
m = self.node_feat_mask.sigmoid()
node_feat_reduce = getattr(torch, self.coeffs['node_feat_reduction'])
loss = loss + self.coeffs['node_feat_size'] * node_feat_reduce(m)
ent = -m * torch.log(m + EPS) - (1 - m) * torch.log(1 - m + EPS)
loss = loss + self.coeffs['node_feat_ent'] * ent.mean()
return loss
def explain_node(self, node_idx, x, edge_index, **kwargs):
r"""Learns and returns a node feature mask and an edge mask that play a
crucial role to explain the prediction made by the GNN for node
:attr:`node_idx`.
Args:
node_idx (int): The node to explain.
x (Tensor): The node feature matrix.
edge_index (LongTensor): The edge indices.
**kwargs (optional): Additional arguments passed to the GNN module.
:rtype: (:class:`Tensor`, :class:`Tensor`)
"""
self.model.eval()
self.__clear_masks__()
num_edges = edge_index.size(1)
# Only operate on a k-hop subgraph around `node_idx`.
x, edge_index, mapping, hard_edge_mask, kwargs = self.__subgraph__(
node_idx, x, edge_index, **kwargs)
# Get the initial prediction.
with torch.no_grad():
log_logits = self.model(x=x, edge_index=edge_index, **kwargs)
pred_label = log_logits > 0.5
pred_label = pred_label.to(int)
# pred_label = log_logits.argmax(dim=-1)
self.__set_masks__(x, edge_index)
self.to(x.device)
optimizer = torch.optim.Adam([self.node_feat_mask, self.edge_mask],
lr=self.lr)
if self.log: # pragma: no cover
pbar = tqdm(total=self.epochs)
pbar.set_description(f'Explain node {node_idx}')
for epoch in range(1, self.epochs + 1):
optimizer.zero_grad()
h = x * self.node_feat_mask.view(1, -1).sigmoid()
# log_logits = self.model(x=h, edge_index=edge_index, **kwargs)
log_logits = self.model(x=h, edge_index=edge_index, **kwargs)
if h.shape[0] == 1:
log_logits = torch.tensor([log_logits]).to(x.device)
pred_label = torch.tensor([pred_label]).to(x.device)
loss = self.__loss__(mapping, log_logits, pred_label)
loss.backward()
optimizer.step()
if self.log: # pragma: no cover
pbar.update(1)
if self.log: # pragma: no cover
pbar.close()
node_feat_mask = self.node_feat_mask.detach().sigmoid()
edge_mask = self.edge_mask.new_zeros(num_edges)
edge_mask[hard_edge_mask] = self.edge_mask.detach().sigmoid()
self.__clear_masks__()
return node_feat_mask, edge_mask
def visualize_subgraph(self, node_idx, edge_index, edge_mask, y=None,
threshold=None, **kwargs):
r"""Visualizes the subgraph around :attr:`node_idx` given an edge mask
:attr:`edge_mask`.
Args:
node_idx (int): The node id to explain.
edge_index (LongTensor): The edge indices.
edge_mask (Tensor): The edge mask.
y (Tensor, optional): The ground-truth node-prediction labels used
as node colorings. (default: :obj:`None`)
threshold (float, optional): Sets a threshold for visualizing
important edges. If set to :obj:`None`, will visualize all
edges with transparancy indicating the importance of edges.
(default: :obj:`None`)
**kwargs (optional): Additional arguments passed to
:func:`nx.draw`.
:rtype: :class:`matplotlib.axes.Axes`, :class:`networkx.DiGraph`
"""
assert edge_mask.size(0) == edge_index.size(1)
# Only operate on a k-hop subgraph around `node_idx`.
subset, edge_index, _, hard_edge_mask = k_hop_subgraph(
node_idx, self.num_hops, edge_index, relabel_nodes=True,
num_nodes=None, flow=self.__flow__())
edge_mask = edge_mask[hard_edge_mask]
if threshold is not None:
edge_mask = (edge_mask >= threshold).to(torch.float)
y_tmp = y
if y is None:
y = torch.zeros(edge_index.max().item() + 1,
device=edge_index.device)
else:
y = y[subset].to(torch.float) / y.max().item()
data = Data(edge_index=edge_index, att=edge_mask, y=y,
num_nodes=y.size(0)).to('cpu')
if data.y.shape[0] == 1:
return to_networkx(data), [], [], []
G = to_networkx(data, node_attrs=['y'], edge_attrs=['att'])
mapping = {k: i for k, i in enumerate(subset.tolist())}
G = nx.relabel_nodes(G, mapping)
edge_index = np.array(list(G.edges))
edge_mask = edge_mask.cpu().numpy().reshape(edge_mask.shape[0], 1)
candidata = [node_idx]
edge_mask_sorted = 1/np.sort(1/edge_mask, axis=0)
edge_list = []
edge_connected_list = []
edge_mask_list = np.array([])
top5_edge_list = []
for i in range(5):
j = 0
for num in edge_mask_sorted:
tmp = np.argwhere(edge_mask==num)[0][0]
if edge_index[tmp][0] in candidata:
candidata.append(edge_index[tmp][1])
edge_list.append((edge_index[tmp][0], edge_index[tmp][1]))
top5_edge_list.append((edge_index[tmp][0], edge_index[tmp][1]))
# edge_mask_list = np.append(edge_mask_list, num)
edge_connected_list.append(num)
edge_mask = np.delete(edge_mask, tmp)
edge_mask_sorted = np.delete(edge_mask_sorted, j)
edge_index = np.delete(edge_index, tmp, axis=0)
break
elif edge_index[tmp][1] in candidata:
candidata.append(edge_index[tmp][0])
edge_list.append((edge_index[tmp][0], edge_index[tmp][1]))
edge_connected_list.append(num)
top5_edge_list.append((edge_index[tmp][0], edge_index[tmp][1]))
edge_mask = np.delete(edge_mask, tmp)
edge_mask_sorted = np.delete(edge_mask_sorted, j)
edge_index = np.delete(edge_index, tmp, axis=0)
break
j += 1
for i in range(5, 10):
j = 0
for num in edge_mask_sorted:
tmp = np.argwhere(edge_mask==num)[0][0]
if edge_index[tmp][0] in candidata:
candidata.append(edge_index[tmp][1])
edge_list.append((edge_index[tmp][0], edge_index[tmp][1]))
# edge_mask_list = np.append(edge_mask_list, num)
edge_connected_list.append(num)
edge_mask = np.delete(edge_mask, tmp)
edge_mask_sorted = np.delete(edge_mask_sorted, j)
edge_index = np.delete(edge_index, tmp, axis=0)
break
elif edge_index[tmp][1] in candidata:
candidata.append(edge_index[tmp][0])
edge_list.append((edge_index[tmp][0], edge_index[tmp][1]))
edge_connected_list.append(num)
edge_mask = np.delete(edge_mask, tmp)
edge_mask_sorted = np.delete(edge_mask_sorted, j)
edge_index = np.delete(edge_index, tmp, axis=0)
break
j += 1
y_list = []
top5_G = nx.Graph()
top5_G.add_edges_from(top5_edge_list)
G = nx.Graph()
G.add_edges_from(edge_list)
pos = nx.spring_layout(top5_G)
for num in list(top5_G.nodes):
if num == node_idx:
y_list.append(1)
else:
y_list.append(0)
if len(list(G.nodes)) == 1:
return G, top5_G, edge_list, edge_connected_list
node_kwargs = copy(kwargs)
node_kwargs['node_size'] = kwargs.get('node_size') or 400
node_kwargs['cmap'] = kwargs.get('cmap') or 'cool'
label_kwargs = copy(kwargs)
label_kwargs['font_size'] = kwargs.get('font_size') or 10
pos = nx.spring_layout(top5_G)
ax = plt.gca()
for source, target, data in top5_G.edges(data=True):
ax.annotate(
'', xy=pos[target], xytext=pos[source],
# arrowprops=dict(
# # arrowstyle="->",
# shrinkA=sqrt(node_kwargs['node_size']) * 2 / 2.0,
# shrinkB=sqrt(node_kwargs['node_size']) * 2 / 2.0,
# # connectionstyle="arc3,rad=0.1",
# )
)
# nx.draw_networkx_nodes(G, pos, node_color=y_list, **node_kwargs)
# nx.draw_networkx_labels(G, pos, **label_kwargs)
nx.draw(top5_G)
return G, top5_G, edge_list, edge_connected_list
def __repr__(self):
return f'{self.__class__.__name__}()'