forked from dmlc/dgl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
208 lines (179 loc) · 6.18 KB
/
main.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
import argparse
import dgl
import torch as th
import torch.optim as optim
from model import CAREGNN
from sklearn.metrics import recall_score, roc_auc_score
from torch.nn.functional import softmax
from utils import EarlyStopping
def main(args):
# Step 1: Prepare graph data and retrieve train/validation/test index ============================= #
# Load dataset
dataset = dgl.data.FraudDataset(args.dataset, train_size=0.4)
graph = dataset[0]
num_classes = dataset.num_classes
# check cuda
if args.gpu >= 0 and th.cuda.is_available():
device = "cuda:{}".format(args.gpu)
else:
device = "cpu"
# retrieve labels of ground truth
labels = graph.ndata["label"].to(device)
# Extract node features
feat = graph.ndata["feature"].to(device)
# retrieve masks for train/validation/test
train_mask = graph.ndata["train_mask"]
val_mask = graph.ndata["val_mask"]
test_mask = graph.ndata["test_mask"]
train_idx = th.nonzero(train_mask, as_tuple=False).squeeze(1).to(device)
val_idx = th.nonzero(val_mask, as_tuple=False).squeeze(1).to(device)
test_idx = th.nonzero(test_mask, as_tuple=False).squeeze(1).to(device)
# Reinforcement learning module only for positive training nodes
rl_idx = th.nonzero(
train_mask.to(device) & labels.bool(), as_tuple=False
).squeeze(1)
graph = graph.to(device)
# Step 2: Create model =================================================================== #
model = CAREGNN(
in_dim=feat.shape[-1],
num_classes=num_classes,
hid_dim=args.hid_dim,
num_layers=args.num_layers,
activation=th.tanh,
step_size=args.step_size,
edges=graph.canonical_etypes,
)
model = model.to(device)
# Step 3: Create training components ===================================================== #
_, cnt = th.unique(labels, return_counts=True)
loss_fn = th.nn.CrossEntropyLoss(weight=1 / cnt)
optimizer = optim.Adam(
model.parameters(), lr=args.lr, weight_decay=args.weight_decay
)
if args.early_stop:
stopper = EarlyStopping(patience=100)
# Step 4: training epochs =============================================================== #
for epoch in range(args.max_epoch):
# Training and validation using a full graph
model.train()
logits_gnn, logits_sim = model(graph, feat)
# compute loss
tr_loss = loss_fn(
logits_gnn[train_idx], labels[train_idx]
) + args.sim_weight * loss_fn(logits_sim[train_idx], labels[train_idx])
tr_recall = recall_score(
labels[train_idx].cpu(),
logits_gnn.data[train_idx].argmax(dim=1).cpu(),
)
tr_auc = roc_auc_score(
labels[train_idx].cpu(),
softmax(logits_gnn, dim=1).data[train_idx][:, 1].cpu(),
)
# validation
val_loss = loss_fn(
logits_gnn[val_idx], labels[val_idx]
) + args.sim_weight * loss_fn(logits_sim[val_idx], labels[val_idx])
val_recall = recall_score(
labels[val_idx].cpu(), logits_gnn.data[val_idx].argmax(dim=1).cpu()
)
val_auc = roc_auc_score(
labels[val_idx].cpu(),
softmax(logits_gnn, dim=1).data[val_idx][:, 1].cpu(),
)
# backward
optimizer.zero_grad()
tr_loss.backward()
optimizer.step()
# Print out performance
print(
"Epoch {}, Train: Recall: {:.4f} AUC: {:.4f} Loss: {:.4f} | Val: Recall: {:.4f} AUC: {:.4f} Loss: {:.4f}".format(
epoch,
tr_recall,
tr_auc,
tr_loss.item(),
val_recall,
val_auc,
val_loss.item(),
)
)
# Adjust p value with reinforcement learning module
model.RLModule(graph, epoch, rl_idx)
if args.early_stop:
if stopper.step(val_auc, model):
break
# Test after all epoch
model.eval()
if args.early_stop:
model.load_state_dict(th.load("es_checkpoint.pt"))
# forward
logits_gnn, logits_sim = model.forward(graph, feat)
# compute loss
test_loss = loss_fn(
logits_gnn[test_idx], labels[test_idx]
) + args.sim_weight * loss_fn(logits_sim[test_idx], labels[test_idx])
test_recall = recall_score(
labels[test_idx].cpu(), logits_gnn[test_idx].argmax(dim=1).cpu()
)
test_auc = roc_auc_score(
labels[test_idx].cpu(),
softmax(logits_gnn, dim=1).data[test_idx][:, 1].cpu(),
)
print(
"Test Recall: {:.4f} AUC: {:.4f} Loss: {:.4f}".format(
test_recall, test_auc, test_loss.item()
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="GCN-based Anti-Spam Model")
parser.add_argument(
"--dataset",
type=str,
default="amazon",
help="DGL dataset for this model (yelp, or amazon)",
)
parser.add_argument(
"--gpu", type=int, default=-1, help="GPU index. Default: -1, using CPU."
)
parser.add_argument(
"--hid_dim", type=int, default=64, help="Hidden layer dimension"
)
parser.add_argument(
"--num_layers", type=int, default=1, help="Number of layers"
)
parser.add_argument(
"--max_epoch",
type=int,
default=30,
help="The max number of epochs. Default: 30",
)
parser.add_argument(
"--lr", type=float, default=0.01, help="Learning rate. Default: 0.01"
)
parser.add_argument(
"--weight_decay",
type=float,
default=0.001,
help="Weight decay. Default: 0.001",
)
parser.add_argument(
"--step_size",
type=float,
default=0.02,
help="RL action step size (lambda 2). Default: 0.02",
)
parser.add_argument(
"--sim_weight",
type=float,
default=2,
help="Similarity loss weight (lambda 1). Default: 2",
)
parser.add_argument(
"--early-stop",
action="store_true",
default=False,
help="indicates whether to use early stop",
)
args = parser.parse_args()
print(args)
th.manual_seed(717)
main(args)