-
Notifications
You must be signed in to change notification settings - Fork 30
/
fit_model.py
180 lines (161 loc) · 6.55 KB
/
fit_model.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
import argparse
import numpy as np
import time
import random
import torch
import torch.nn as nn
from torch.autograd import Variable
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from loader import (load_sage, load_gat)
from models import (EGraphSage, EResGAT)
np.random.seed(1)
random.seed(1)
data_class = {"UNSW-NB15":10,
"Darknet":9,
"CES-CIC":7,
"ToN-IoT":10}
data_lr = {"UNSW-NB15":0.007,
"Darknet":0.003,
"CES-CIC":0.003,
"ToN-IoT":0.01}
test_size = {"UNSW-NB15":210000,
"Darknet":45000,
"CES-CIC":75000,
"ToN-IoT":140000}
def fit(args):
alg = args.alg
data = args.dataset
binary = args.binary
residual = args.residual
path = "datasets/"+ data
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if alg == "sage":
enc2, edge_feat, label, node_map, adj = load_sage(path, binary)
model = EGraphSage(data_class[data], enc2, edge_feat, node_map, adj, residual)
else:
edge_feat, label, adj, adj_lists, config = load_gat(path, device, binary)
model = EResGAT(
num_of_layers=config['num_of_layers'],
num_heads_per_layer=config['num_heads_per_layer'],
num_features_per_layer=config['num_features_per_layer'],
num_identity_feats=config['num_identity_feats'],
edge_feat=edge_feat,
adj=adj,
adj_lists=adj_lists,
device=device,
add_skip_connection=config['add_skip_connection'],
residual=residual,
bias=config['bias'],
dropout=config['dropout']
).to(device)
# loss and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad,
model.parameters()),
lr=data_lr[data])
# train test split
num_edges = len(edge_feat)
train_val, test = train_test_split(np.arange(num_edges), test_size=test_size[data], stratify=label)
train, val = train_test_split(train_val, test_size=5000, stratify=label[train_val])
times = []
trainscores = []
valscores = []
for epoch in range(2):
print("Epoch: ", epoch)
random.shuffle(train)
epoch_start = time.time()
for batch in range(int(len(train) / 500)): # batches in train data
batch_edges = train[500 * batch:500 * (batch + 1)] # 500 records per batch
start_time = time.time()
# training
model.train()
output, _ = model(batch_edges)
if alg == "sage":
train_output = output.data.numpy()
acc_train = f1_score(label[batch_edges],
train_output.argmax(axis=1),
average="weighted")
loss = model.loss(batch_edges,
Variable(torch.LongTensor(label[np.array(batch_edges)])))
else:
_, out, _, idx = output
train_output = out.index_select(0, idx)
acc_train = f1_score(label[batch_edges],
torch.argmax(train_output, dim=-1),
average="weighted")
loss = loss_fn(train_output, label[batch_edges])
optimizer.zero_grad()
loss.backward()
optimizer.step()
end_time = time.time()
times.append(end_time - start_time)
trainscores.append(acc_train)
print('batch: {:03d}'.format(batch + 1),
'loss_train: {:.4f}'.format(loss.item()),
'acc_train: {:.4f}'.format(acc_train.item()),
'time: {:.4f}s'.format(end_time - start_time))
if batch >= 179:
break
epoch_end = time.time()
# Validation
acc_val, loss_val, val_output = predict_(alg, model, label, loss_fn, val)
valscores.append(acc_val)
print('loss_val: {:.4f}'.format(loss_val),
'acc_val: {:.4f}'.format(acc_val.item()),
'average batch time: {:.4f}s'.format(np.mean(times)),
'epoch time: {:.2f}min'.format((epoch_end - epoch_start)/60.0))
# Testing
acc_test, loss_test, predict_output = predict_(alg, model, label, loss_fn, test)
print("Test set results:", "loss= {:.4f}".format(loss_test),
"accuracy= {:.4f}".format(acc_test.item()),
"label acc=", f1_score(label[test], predict_output, average=None))
def predict_(alg, model, label, loss_fn, data_idx):
predict_output = []
loss = 0.0
# emb = []
for batch in range(int(len(data_idx) / 500)):
batch_edges = data_idx[500 * batch:500 * (batch + 1)]
batch_output, _ = model(batch_edges)
if alg == "sage":
batch_output = batch_output.data.numpy().argmax(axis=1)
batch_loss = model.loss(batch_edges,
Variable(torch.LongTensor(label[np.array(batch_edges)])))
else:
_, out, _, idx = batch_output
batch_output = out.index_select(0, idx)
batch_output = torch.argmax(batch_output, dim=-1)
batch_loss = loss_fn(batch_output, label[batch_edges])
predict_output.extend(batch_output)
loss += batch_loss.item()
# emb.append(embed)
loss /= batch + 1
acc = f1_score(label[data_idx], predict_output, average="weighted")
# emb = torch.stack(emb).view(5000, -1)
return acc, loss, predict_output
# -----------------------------------------------------------------------------
if __name__ == '__main__':
ALG = ['sage', 'gat']
DATA = ['UNSW-NB15', 'Darknet', 'CES-CIC', 'ToN-IoT']
p = argparse.ArgumentParser()
p.add_argument('--alg',
help='algorithm to use.',
default='gat',
choices=ALG)
p.add_argument('--dataset',
help='Experimental dataset.',
type=str,
default='Darknet',
choices=DATA)
p.add_argument('--binary',
help='Perform binary or muticlass task',
type=bool,
default=True)
p.add_argument('--residual',
help='Apply modified model with residuals or not',
type=bool,
default=True)
# Parse and validate script arguments.
args = p.parse_args()
# Training and testing
fit(args)