-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_gnnshap.py
More file actions
141 lines (126 loc) · 4.62 KB
/
Copy pathrun_gnnshap.py
File metadata and controls
141 lines (126 loc) · 4.62 KB
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
import argparse
import pickle
import time
from collections import defaultdict
import numpy as np
import torch
from tqdm.auto import tqdm
from dataset.utils import get_model_data_config
from gnnshap.dist_explainer import DistShapExplainer
from gnnshap.sparse_utils import get_edge_names
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", type=str, default="CiteSeer")
parser.add_argument(
"--result_path",
type=str,
default="./results",
help=("Path to save the results."),
)
parser.add_argument(
"--num_samples",
type=int,
default=10000,
help="Number of samples to use for GNNShap",
)
parser.add_argument("--repeat", default=1, type=int)
parser.add_argument("--batch_size", type=int, default=100)
parser.add_argument("--device", type=int, default=0)
parser.add_argument(
"--solver",
type=str,
default="WLSSolver",
help="Solver to use for solving SVX",
choices=["WLSSolver", "WLRSolver", "CGLSSolver"],
)
parser.add_argument(
"--split",
type=str,
default="all",
help=(
"Split to use for evaluation. "
"all computes scores for all nodes, "
"train applies only on train nodes, "
"test applies only on test nodes"
),
choices=["all", "train", "test"],
)
args = parser.parse_args()
dataset_name = args.dataset
num_samples = args.num_samples
batch_size = args.batch_size
sampler_name = "GNNShapSampler"
solver_name = args.solver
device = torch.device(f"cuda:{args.device}" if torch.cuda.is_available() else "cpu")
model, data, config = get_model_data_config(
dataset_name, load_pretrained=True, device=device
)
if args.split == "all":
expl_nodes = range(data.num_nodes)
elif args.split == "train":
expl_nodes = (
data.train_mask.nonzero(as_tuple=False).cpu().numpy().flatten().tolist()
)
elif args.split == "test":
expl_nodes = (
data.test_mask.nonzero(as_tuple=False).cpu().numpy().flatten().tolist()
)
else:
raise ValueError(f"Invalid split: {args.split}")
for r in range(args.repeat):
failed_indices = []
score_dict = defaultdict(list)
pred_dict = defaultdict(list)
times = []
shap = DistShapExplainer(
model,
data,
nhops=config["num_hops"],
verbose=0,
device=device,
progress_hide=True,
precision=torch.double,
)
start_time = time.time()
for ind in tqdm(expl_nodes, desc=f"GNNShap explanations - run{r+1}"):
try:
# compute explanations for ground truth class if train split
# otherwise, compute explanations for predicted class
target_class = data.y[ind].item() if args.split == "train" else None
explanation = shap.explain(
ind,
nsamples=num_samples,
sampler_name=sampler_name,
batch_size=batch_size,
solver_name=solver_name,
target_class=target_class,
)
edge_scores = explanation.shap_values
pred = explanation.fx
times.append(explanation.time_total_comp)
edge_names = get_edge_names(explanation.sub_edge_index)
for i, edge in enumerate(edge_names):
score_dict[edge].append(edge_scores[i])
pred_dict[edge].append(pred)
except RuntimeError as e:
failed_indices.append(ind)
if "out of memory" in str(e):
print(f"Node {ind} has failed: out of memory")
else:
print(f"Node {ind} has failed: {e}")
except Exception as e: # pylint: disable=broad-exception-caught
# print(f"Node {ind} has failed. General error: {e}")
failed_indices.append(ind)
if len(failed_indices) > 0:
print(f"Failed indices: {failed_indices}")
print(f"Total time: {time.time()-start_time}")
rfile = (
f"{args.result_path}/{dataset_name}_GNNShap_{args.split}_"
f"{num_samples}_run{r+1}.pkl"
)
with open(rfile, "wb") as pkl_file:
pickle.dump(
{"score_dict": score_dict, "pred_dict": pred_dict, "times": times},
pkl_file,
)
print(f"Results saved to {rfile}")