-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathfg_attack.py
67 lines (56 loc) · 2.79 KB
/
fg_attack.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
import os.path as osp
import torch
import torch_geometric.transforms as T
from greatx.attack.targeted import FGAttack
from greatx.datasets import GraphDataset
from greatx.nn.models import GCN
from greatx.training import Trainer
from greatx.training.callbacks import ModelCheckpoint
from greatx.utils import mark, split_nodes
dataset = 'Cora'
root = osp.join(osp.dirname(osp.realpath(__file__)), '../../..', 'data')
dataset = GraphDataset(root=root, name=dataset,
transform=T.LargestConnectedComponents())
data = dataset[0]
splits = split_nodes(data.y, random_state=15)
num_features = data.x.size(-1)
num_classes = data.y.max().item() + 1
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# ================================================================== #
# Attack Setting #
# ================================================================== #
target = 1 # target node to attack
target_label = data.y[target].item()
# ================================================================== #
# Before Attack #
# ================================================================== #
trainer_before = Trainer(GCN(num_features, num_classes), device=device)
ckp = ModelCheckpoint('model_before.pth', monitor='val_acc')
trainer_before.fit(data, mask=(splits.train_nodes, splits.val_nodes),
callbacks=[ckp])
output = trainer_before.predict(data, mask=target)
print("Before attack:")
print(mark(output, target_label))
# ================================================================== #
# Attacking #
# ================================================================== #
attacker = FGAttack(data, device=device)
attacker.setup_surrogate(trainer_before.model)
attacker.reset()
attacker.attack(target)
# ================================================================== #
# After evasion Attack #
# ================================================================== #
output = trainer_before.predict(attacker.data(), mask=target)
print("After evasion attack:")
print(mark(output, target_label))
# ================================================================== #
# After poisoning Attack #
# ================================================================== #
trainer_after = Trainer(GCN(num_features, num_classes), device=device)
ckp = ModelCheckpoint('model_after.pth', monitor='val_acc')
trainer_after.fit(attacker.data(), mask=(splits.train_nodes, splits.val_nodes),
callbacks=[ckp])
output = trainer_after.predict(attacker.data(), mask=target)
print("After poisoning attack:")
print(mark(output, target_label))