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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
|
import copy
from typing import Dict, List, Optional, Union
import torch
from torch import Tensor
from torch_geometric.data.data import Data, warn_or_raise
from torch_geometric.data.hetero_data import HeteroData
from torch_geometric.explain.config import ThresholdConfig, ThresholdType
from torch_geometric.typing import EdgeType, NodeType
from torch_geometric.visualization import visualize_graph
class ExplanationMixin:
@property
def available_explanations(self) -> List[str]:
"""Returns the available explanation masks."""
return [key for key in self.keys() if key.endswith('_mask')]
def validate_masks(self, raise_on_error: bool = True) -> bool:
r"""Validates the correctness of the :class:`Explanation` masks."""
status = True
for store in self.node_stores:
if 'node_mask' not in store:
continue
if store.node_mask.dim() != 2:
status = False
warn_or_raise(
f"Expected a 'node_mask' with two dimensions (got "
f"{store.node_mask.dim()} dimensions)", raise_on_error)
if store.node_mask.size(0) not in {1, store.num_nodes}:
status = False
warn_or_raise(
f"Expected a 'node_mask' with {store.num_nodes} nodes "
f"(got {store.node_mask.size(0)} nodes)", raise_on_error)
if 'x' in store:
num_features = store.x.size(-1)
else:
num_features = store.node_mask.size(-1)
if store.node_mask.size(1) not in {1, num_features}:
status = False
warn_or_raise(
f"Expected a 'node_mask' with {num_features} features ("
f"got {store.node_mask.size(1)} features)", raise_on_error)
for store in self.edge_stores:
if 'edge_mask' not in store:
continue
if store.edge_mask.dim() != 1:
status = False
warn_or_raise(
f"Expected an 'edge_mask' with one dimension (got "
f"{store.edge_mask.dim()} dimensions)", raise_on_error)
if store.edge_mask.size(0) != store.num_edges:
status = False
warn_or_raise(
f"Expected an 'edge_mask' with {store.num_edges} edges "
f"(got {store.edge_mask.size(0)} edges)", raise_on_error)
return status
def _threshold_mask(
self,
mask: Optional[Tensor],
threshold_config: ThresholdConfig,
) -> Optional[Tensor]:
if mask is None:
return None
if threshold_config.type == ThresholdType.hard:
return (mask > threshold_config.value).float()
if threshold_config.type in [
ThresholdType.topk,
ThresholdType.topk_hard,
]:
if threshold_config.value >= mask.numel():
if threshold_config.type == ThresholdType.topk:
return mask
else:
return torch.ones_like(mask)
value, index = torch.topk(
mask.flatten(),
k=threshold_config.value,
)
out = torch.zeros_like(mask.flatten())
if threshold_config.type == ThresholdType.topk:
out[index] = value
else:
out[index] = 1.0
return out.view(mask.size())
assert False
def threshold(
self,
*args,
**kwargs,
) -> Union['Explanation', 'HeteroExplanation']:
"""Thresholds the explanation masks according to the thresholding
method.
Args:
*args: Arguments passed to :class:`ThresholdConfig`.
**kwargs: Keyword arguments passed to :class:`ThresholdConfig`.
"""
threshold_config = ThresholdConfig.cast(*args, **kwargs)
if threshold_config is None:
return self
# Avoid modification of the original explanation:
out = copy.copy(self)
for store in out.node_stores:
store.node_mask = self._threshold_mask(store.get('node_mask'),
threshold_config)
for store in out.edge_stores:
store.edge_mask = self._threshold_mask(store.get('edge_mask'),
threshold_config)
return out
class Explanation(Data, ExplanationMixin):
r"""Holds all the obtained explanations of a homogeneous graph.
The explanation object is a :obj:`~torch_geometric.data.Data` object and
can hold node attributions and edge attributions.
It can also hold the original graph if needed.
Args:
node_mask (Tensor, optional): Node-level mask with shape
:obj:`[num_nodes, 1]`, :obj:`[1, num_features]` or
:obj:`[num_nodes, num_features]`. (default: :obj:`None`)
edge_mask (Tensor, optional): Edge-level mask with shape
:obj:`[num_edges]`. (default: :obj:`None`)
**kwargs (optional): Additional attributes.
"""
def validate(self, raise_on_error: bool = True) -> bool:
r"""Validates the correctness of the :class:`Explanation` object."""
status = super().validate(raise_on_error)
status &= self.validate_masks(raise_on_error)
return status
def get_explanation_subgraph(self) -> 'Explanation':
r"""Returns the induced subgraph, in which all nodes and edges with
zero attribution are masked out.
"""
node_mask = self.get('node_mask')
if node_mask is not None:
node_mask = node_mask.sum(dim=-1) > 0
edge_mask = self.get('edge_mask')
if edge_mask is not None:
edge_mask = edge_mask > 0
return self._apply_masks(node_mask, edge_mask)
def get_complement_subgraph(self) -> 'Explanation':
r"""Returns the induced subgraph, in which all nodes and edges with any
attribution are masked out.
"""
node_mask = self.get('node_mask')
if node_mask is not None:
node_mask = node_mask.sum(dim=-1) == 0
edge_mask = self.get('edge_mask')
if edge_mask is not None:
edge_mask = edge_mask == 0
return self._apply_masks(node_mask, edge_mask)
def _apply_masks(
self,
node_mask: Optional[Tensor] = None,
edge_mask: Optional[Tensor] = None,
) -> 'Explanation':
out = copy.copy(self)
if edge_mask is not None:
for key, value in self.items():
if key == 'edge_index':
out.edge_index = value[:, edge_mask]
elif self.is_edge_attr(key):
out[key] = value[edge_mask]
if node_mask is not None:
out = out.subgraph(node_mask)
return out
def visualize_feature_importance(
self,
path: Optional[str] = None,
feat_labels: Optional[List[str]] = None,
top_k: Optional[int] = None,
):
r"""Creates a bar plot of the node feature importances by summing up
the node mask across all nodes.
Args:
path (str, optional): The path to where the plot is saved.
If set to :obj:`None`, will visualize the plot on-the-fly.
(default: :obj:`None`)
feat_labels (List[str], optional): The labels of features.
(default :obj:`None`)
top_k (int, optional): Top k features to plot. If :obj:`None`
plots all features. (default: :obj:`None`)
"""
node_mask = self.get('node_mask')
if node_mask is None:
raise ValueError(f"The attribute 'node_mask' is not available "
f"in '{self.__class__.__name__}' "
f"(got {self.available_explanations})")
if node_mask.dim() != 2 or node_mask.size(1) <= 1:
raise ValueError(f"Cannot compute feature importance for "
f"object-level 'node_mask' "
f"(got shape {node_mask.size()})")
if feat_labels is None:
feat_labels = range(node_mask.size(1))
score = node_mask.sum(dim=0)
return _visualize_score(score, feat_labels, path, top_k)
def visualize_graph(
self,
path: Optional[str] = None,
backend: Optional[str] = None,
node_labels: Optional[List[str]] = None,
) -> None:
r"""Visualizes the explanation graph with edge opacity corresponding to
edge importance.
Args:
path (str, optional): The path to where the plot is saved.
If set to :obj:`None`, will visualize the plot on-the-fly.
(default: :obj:`None`)
backend (str, optional): The graph drawing backend to use for
visualization (:obj:`"graphviz"`, :obj:`"networkx"`).
If set to :obj:`None`, will use the most appropriate
visualization backend based on available system packages.
(default: :obj:`None`)
node_labels (list[str], optional): The labels/IDs of nodes.
(default: :obj:`None`)
"""
edge_mask = self.get('edge_mask')
if edge_mask is None:
raise ValueError(f"The attribute 'edge_mask' is not available "
f"in '{self.__class__.__name__}' "
f"(got {self.available_explanations})")
visualize_graph(self.edge_index, edge_mask, path, backend, node_labels)
class HeteroExplanation(HeteroData, ExplanationMixin):
r"""Holds all the obtained explanations of a heterogeneous graph.
The explanation object is a :obj:`~torch_geometric.data.HeteroData` object
and can hold node attributions and edge attributions.
It can also hold the original graph if needed.
"""
def validate(self, raise_on_error: bool = True) -> bool:
r"""Validates the correctness of the :class:`Explanation` object."""
status = super().validate(raise_on_error)
status &= self.validate_masks(raise_on_error)
return status
def get_explanation_subgraph(self) -> 'HeteroExplanation':
r"""Returns the induced subgraph, in which all nodes and edges with
zero attribution are masked out.
"""
return self._apply_masks(
node_mask_dict={
key: mask.sum(dim=-1) > 0
for key, mask in self.collect('node_mask', True).items()
},
edge_mask_dict={
key: mask > 0
for key, mask in self.collect('edge_mask', True).items()
},
)
def get_complement_subgraph(self) -> 'HeteroExplanation':
r"""Returns the induced subgraph, in which all nodes and edges with any
attribution are masked out.
"""
return self._apply_masks(
node_mask_dict={
key: mask.sum(dim=-1) == 0
for key, mask in self.collect('node_mask', True).items()
},
edge_mask_dict={
key: mask == 0
for key, mask in self.collect('edge_mask', True).items()
},
)
def _apply_masks(
self,
node_mask_dict: Dict[NodeType, Tensor],
edge_mask_dict: Dict[EdgeType, Tensor],
) -> 'HeteroExplanation':
out = copy.copy(self)
for edge_type, edge_mask in edge_mask_dict.items():
for key, value in self[edge_type].items():
if key == 'edge_index':
out[edge_type].edge_index = value[:, edge_mask]
elif self[edge_type].is_edge_attr(key):
out[edge_type][key] = value[edge_mask]
return out.subgraph(node_mask_dict)
def visualize_feature_importance(
self,
path: Optional[str] = None,
feat_labels: Optional[Dict[NodeType, List[str]]] = None,
top_k: Optional[int] = None,
):
r"""Creates a bar plot of the node feature importances by summing up
node masks across all nodes for each node type.
Args:
path (str, optional): The path to where the plot is saved.
If set to :obj:`None`, will visualize the plot on-the-fly.
(default: :obj:`None`)
feat_labels (Dict[NodeType, List[str]], optional): The labels of
features for each node type. (default :obj:`None`)
top_k (int, optional): Top k features to plot. If :obj:`None`
plots all features. (default: :obj:`None`)
"""
node_mask_dict = self.node_mask_dict
for node_mask in node_mask_dict.values():
if node_mask.dim() != 2:
raise ValueError(f"Cannot compute feature importance for "
f"object-level 'node_mask' "
f"(got shape {node_mask.size()})")
if feat_labels is None:
feat_labels = {}
for node_type, node_mask in node_mask_dict.items():
feat_labels[node_type] = range(node_mask.size(1))
score = torch.cat(
[node_mask.sum(dim=0) for node_mask in node_mask_dict.values()],
dim=0)
all_feat_labels = []
for node_type in node_mask_dict.keys():
all_feat_labels += [
f'{node_type}#{label}' for label in feat_labels[node_type]
]
return _visualize_score(score, all_feat_labels, path, top_k)
def _visualize_score(
score: torch.Tensor,
labels: List[str],
path: Optional[str] = None,
top_k: Optional[int] = None,
):
import matplotlib.pyplot as plt
import pandas as pd
if len(labels) != score.numel():
raise ValueError(f"The number of labels (got {len(labels)}) must "
f"match the number of scores (got {score.numel()})")
score = score.cpu().numpy()
df = pd.DataFrame({'score': score}, index=labels)
df = df.sort_values('score', ascending=False)
df = df.round(decimals=3)
if top_k is not None:
df = df.head(top_k)
title = f"Feature importance for top {len(df)} features"
else:
title = f"Feature importance for {len(df)} features"
ax = df.plot(
kind='barh',
figsize=(10, 7),
title=title,
ylabel='Feature label',
xlim=[0, float(df['score'].max()) + 0.3],
legend=False,
)
plt.gca().invert_yaxis()
ax.bar_label(container=ax.containers[0], label_type='edge')
if path is not None:
plt.savefig(path)
else:
plt.show()
plt.close()
|