forked from BunsenFeng/BotRGCN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CrossValTrainTestRGCN.py
385 lines (290 loc) · 15.7 KB
/
CrossValTrainTestRGCN.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
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
from model import BotRGCN
from augmodels import TweetAugmentedRGCN, TweetAugmentedHAN
# from Dataset import Twibot20
from TwibotSmallTruncatedSVD import TwibotSmallTruncatedSVD
from TwibotSmallAugmentedTSVDHomogeneous import TwibotSmallAugmentedTSVDHomogeneous
from TwibotSmallEdgeHetero import TwibotSmallEdgeHetero
from HeteroTwibot import HeteroTwibot
import numpy as np
import torch
from tqdm import tqdm
from torch import nn, svd
from utils import accuracy,init_weights
from sklearn.metrics import f1_score
from sklearn.metrics import matthews_corrcoef, precision_score, recall_score, roc_auc_score, precision_recall_curve, confusion_matrix, roc_curve, RocCurveDisplay
import argparse
# import matplotlib.pyplot as plt
import torch.nn.functional as F
import wandb
# dataset=Twibot20(device=device,process=True,save=True)
# dataset = TwibotSmallTruncatedSVD(device=device,process=True,save=True,dev=False, svdComponents=svdComponents)
# dataset = TwibotSmallAugmentedTSVDHomogeneous(device=device,process=True,save=True,dev=False, svdComponents=svdComponents)
# dataset = HeteroTwibot(dataset)
# model=BotRGCN(embedding_dimension=embedding_size, des_size=svdComponents, tweet_size=svdComponents).to(device)
def train(epoch, model, optimizer, loss, des_tensor,tweets_tensor,num_prop,category_prop,edge_index,edge_type,labels,train_idx):
model.train()
output = model(des_tensor,tweets_tensor,num_prop,category_prop,edge_index,edge_type)
loss_train = loss(output[train_idx], labels[train_idx])
acc_train = accuracy(output[train_idx], labels[train_idx])
optimizer.zero_grad()
loss_train.backward()
optimizer.step()
return acc_train,loss_train
def test(model, loss, des_tensor,tweets_tensor,num_prop,category_prop,edge_index,edge_type,labels,\
test_idx, **metrics):
model.eval()
output = model(des_tensor,tweets_tensor,num_prop,category_prop,edge_index,edge_type)
output_probs = torch.softmax(output, dim=1).detach().cpu().numpy()
loss_test = loss(output[test_idx], labels[test_idx]).detach()
acc_test = accuracy(output[test_idx], labels[test_idx]).detach()
output = output.max(1)[1].to('cpu').detach().numpy()
label = labels.to('cpu').detach().numpy()
results = {}
for metric in metrics:
if metric == 'roc_auc':
results[metric] = metrics[metric](label[test_idx], output_probs[test_idx,1])
results[metric] = metrics[metric](label[test_idx], output[test_idx])
# wandb.log()
roc_fpr, roc_tpr, roc_thresholds = roc_curve(label[test_idx], output_probs[test_idx,1])
# roc_display = RocCurveDisplay(fpr=roc_fpr, tpr=roc_tpr).plot()
results['roc_curve_fpr'] = roc_fpr
results['roc_curve_tpr'] = roc_tpr
results['roc_curve_thresholds'] = roc_thresholds
# np.save('../../Graphs/rocNumpys/roc_fpr_'+wandb.run.name+'.npy',roc_fpr)
# np.save('../../Graphs/rocNumpys/roc_tpr_'+wandb.run.name+'.npy',roc_tpr)
# np.save('../../Graphs/rocNumpys/roc_thresholds_'+wandb.run.name+'.npy',roc_thresholds)
# plt.show()
# targets = label[test_idx].reshape(-1)
# one_hot_targets = np.eye(2)[targets]
# roc = wandb.plot.roc_curve(one_hot_targets, output_probs[test_idx])
# plt.show()
# wandb.log({'roc_curve': roc_display})
results['loss'] = loss_test.item()
results['acc'] = acc_test.item()
# if val_set:
# print("Validation set results:",
# "val_loss= {:.4f}".format(loss_test.item()),
# "val_accuracy= {:.4f}".format(acc_test.item()),
# "val_f1_score= {:.4f}".format(results['f1_score'].item()),
# "val_mcc= {:.4f}".format(results['mcc'].item()),
# "val_precision= {:.4f}".format(results['prec'].item()),
# "val_recall= {:.4f}".format(results['recall'].item()),
# "val_roc_auc= {:.4f}".format(results['roc_auc'].item()))
# else:
# print("Test set results:",
# "test_loss= {:.4f}".format(loss_test.item()),
# "test_accuracy= {:.4f}".format(acc_test.item()),
# "f1_score= {:.4f}".format(results['f1_score'].item()),
# "mcc={:.4f}".format(results['mcc'].item()),
# "precision= {:.4f}".format(results['prec'].item()),
# "recall= {:.4f}".format(results['recall'].item()),
# "roc_auc= {:.4f}".format(results['roc_auc'].item()))
# Optional
return results
def crossValTrainTestBotRGCN(embedding_size = 128, dropout = 0.3, lr = 1e-3, weight_decay = 5e-3, svdComponents = 100, \
thirds = False, epochs = 100, testing_enabled = True, using_external_config = False, augmentedDataset = True, datasetVariant = 1, crossValFolds = 5, crossValIteration=0, dev=False):
device = torch.device('cpu')
if datasetVariant not in {0,1}:
raise ValueError("datasetVariant must be 1 or 0")
numRelations = 2
print("Importing the dataset...")
if augmentedDataset:
if datasetVariant == 0:
dataset = TwibotSmallAugmentedTSVDHomogeneous(device=device,process=True,save=True,dev=dev, svdComponents=svdComponents)
numRelations = 1
else:
dataset = TwibotSmallEdgeHetero(device=device,process=True,save=True,dev=False, svdComponents=svdComponents)
model = TweetAugmentedRGCN(embedding_dimension=embedding_size, des_size=svdComponents, tweet_size=svdComponents, \
dropout=dropout, thirds=thirds, numRelations=numRelations).to(device)
else:
if datasetVariant == 0:
numRelations = 1
dataset = TwibotSmallTruncatedSVD(device=device,process=True,save=True,dev=dev, svdComponents=svdComponents, edgeHetero=bool(datasetVariant))
model = BotRGCN(embedding_dimension=embedding_size, des_size=svdComponents, tweet_size=svdComponents, dropout=dropout, numRelations=numRelations).to(device)
des_tensor,tweets_tensor,num_prop,category_prop,edge_index,edge_type,labels,train_idx,val_idx,test_idx=dataset.dataloader()
assert crossValFolds > 1, "cross_val_folds must be greater than 1"
assert crossValIteration < crossValFolds, "cross_val_iteration must be less than cross_val_folds"
train_val_range = range(train_idx[0], val_idx[-1]+1)
val_start_index = int((crossValIteration/crossValFolds) * len(train_val_range))
val_end_index_exclusive = int(((crossValIteration+1)/crossValFolds) * len(train_val_range))
val_idx = train_val_range[val_start_index:val_end_index_exclusive]
train_idx = list(train_val_range[:val_start_index]) + list(train_val_range[val_end_index_exclusive:])
## IMPORTING THE MODEL
print("setting up the model...")
if not using_external_config:
wandb.config.update({
"model_name": model.__class__.__name__,
"dataset": dataset.__class__.__name__,
"embedding_size": embedding_size,
"dropout": dropout,
"lr": lr,
"weight_decay": weight_decay,
"svdComponents": svdComponents,
"thirds": thirds,
"epochs": epochs
})
wandb.watch(model)
loss=nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(),
lr=lr,weight_decay=weight_decay)
model.apply(init_weights)
print("beginning training...")
metrics = {'f1_score': f1_score, 'mcc': matthews_corrcoef, 'prec': precision_score, \
'recall': recall_score, 'roc_auc': roc_auc_score, 'conf_mat': confusion_matrix}
for epoch in tqdm(range(epochs), miniters=5):
acc_train,loss_train = train(epoch, model, optimizer, loss, des_tensor, tweets_tensor, \
num_prop, category_prop, edge_index, edge_type, labels, train_idx)
val_results = test(model, loss, des_tensor, tweets_tensor, \
num_prop, category_prop, edge_index, edge_type, labels, \
val_idx,**metrics)
val_results_named = {k+"_val":v for k,v in val_results.items()}
wandb.log({"acc_train": acc_train, "loss_train": loss_train, **val_results_named})
results = val_results_named
results['acc_train'] = acc_train.item()
results['loss_train'] = loss_train.item()
if testing_enabled:
results = test(model, loss, des_tensor,tweets_tensor,num_prop,category_prop,edge_index,edge_type,labels,test_idx, val_set=False)
return results
def train_all_then_test_BotRGCN(embedding_size = 128, dropout = 0.3, lr = 1e-3, weight_decay = 5e-3, svdComponents = 100, \
thirds = False, epochs = 100, testing_enabled = True, using_external_config = False, augmentedDataset = True, datasetVariant = 1, crossValFolds = 5, crossValIteration=0, dev=False):
device = torch.device('cpu')
if datasetVariant not in {0,1}:
raise ValueError("datasetVariant must be 1 or 0")
numRelations = 2
print("Importing the dataset...")
if augmentedDataset:
if datasetVariant == 0:
dataset = TwibotSmallAugmentedTSVDHomogeneous(device=device,process=True,save=True,dev=dev, svdComponents=svdComponents)
numRelations = 1
else:
dataset = TwibotSmallEdgeHetero(device=device,process=True,save=True,dev=False, svdComponents=svdComponents)
model = TweetAugmentedRGCN(embedding_dimension=embedding_size, des_size=svdComponents, tweet_size=svdComponents, \
dropout=dropout, thirds=thirds, numRelations=numRelations).to(device)
else:
if datasetVariant == 0:
numRelations = 1
dataset = TwibotSmallTruncatedSVD(device=device,process=True,save=True,dev=dev, svdComponents=svdComponents, edgeHetero=bool(datasetVariant))
model = BotRGCN(embedding_dimension=embedding_size, des_size=svdComponents, tweet_size=svdComponents, dropout=dropout, numRelations=numRelations).to(device)
des_tensor,tweets_tensor,num_prop,category_prop,edge_index,edge_type,labels,train_idx,val_idx,test_idx=dataset.dataloader()
assert crossValFolds > 1, "cross_val_folds must be greater than 1"
assert crossValIteration < crossValFolds, "cross_val_iteration must be less than cross_val_folds"
train_val_idx = list(train_idx) + list(val_idx)
## IMPORTING THE MODEL
print("setting up the model...")
if not using_external_config:
wandb.config.update({
"model_name": model.__class__.__name__,
"dataset": dataset.__class__.__name__,
"embedding_size": embedding_size,
"dropout": dropout,
"lr": lr,
"weight_decay": weight_decay,
"svdComponents": svdComponents,
"thirds": thirds,
"epochs": epochs
})
wandb.watch(model)
loss=nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(),
lr=lr,weight_decay=weight_decay)
model.apply(init_weights)
print("beginning training...")
metrics = {'f1_score': f1_score, 'mcc': matthews_corrcoef, 'prec': precision_score, \
'recall': recall_score, 'roc_auc': roc_auc_score, 'conf_mat': confusion_matrix}
for epoch in tqdm(range(epochs), miniters=5):
acc_train,loss_train = train(epoch, model, optimizer, loss, des_tensor, tweets_tensor, \
num_prop, category_prop, edge_index, edge_type, labels, train_val_idx)
wandb.log({"acc_train": acc_train, "loss_train": loss_train})
results = test(model, loss, des_tensor, tweets_tensor, \
num_prop, category_prop, edge_index, edge_type, labels, \
test_idx,**metrics)
results_named = {k+"_test":v for k,v in results.items()}
results_named['acc_train'] = acc_train.item()
results_named['loss_train'] = loss_train.item()
return results_named
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_variant', type=int, default=1, help='1 for edge heterogeneous, 0 for edge homogeneous')
parser.add_argument('--augment', dest='augmented_dataset', action='store_true')
parser.add_argument('--no_augment', dest='augmented_dataset', action='store_false')
parser.set_defaults(augmented_dataset=True)
parser.add_argument('--test_mode', dest='test_not_val', action='store_true')
parser.add_argument('--cross_val_mode', dest='test_not_val', action='store_false')
parser.set_defaults(test_not_val=True)
args = parser.parse_args()
#device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
device = torch.device('cpu')
## HYPERPARAMETERS
# TODO implement an arg_parser module for the hyperparameters
# Default values
# embedding_size,dropout,lr,weight_decay, svdComponents, thirds=128,0.3,1e-3,5e-3, 100, False
# # OLD Values from main.py
# embedding_size = 96
# dropout = 0.3
# lr = 1e-3
# weight_decay = 5e-3
# svdComponents = 100
# thirds = False
# epochs = 60
# Current Values
config_defaults = dict(
model_name="BotRGCN",
embedding_size = 96,
dropout = 0.3,
lr = 0.001,
weight_decay = 0.005,
svdComponents = 100,
thirds = False,
epochs = 60,
# neighboursPerNode = 10,
# batch_size=1,
testing_enabled = args.test_not_val,
crossValFolds = 5,
augmentedDataset = args.augmented_dataset,
datasetVariant = args.dataset_variant,
dev = False,
numRepeatsTest = 10,
numRepeatsPerFold = 3
)
wandb.init(project="test-project", entity="graphbois", config=config_defaults)
config = wandb.config
aggregate_results = {}
if config.testing_enabled:
numRepeats = config.numRepeatsTest
for i in range(numRepeats):
print("Starting repeat {}".format(i))
results = train_all_then_test_BotRGCN(config.embedding_size, config.dropout, config.lr, \
config.weight_decay, config.svdComponents, config.thirds, config.epochs, config.testing_enabled, \
using_external_config=True, augmentedDataset=config.augmentedDataset, datasetVariant=config.datasetVariant, \
crossValFolds=config.crossValFolds, crossValIteration=0, dev=config.dev)
wandb.log(results)
for key in results:
if key != 'conf_matrix_test':
aggregate_results[key] = aggregate_results.get(key, []) + [results[key]]
else:
aggregate_results[key] = aggregate_results.get(key, []) + [results[key].numpy()]
else:
numRepeats = config.numRepeatsPerFold
for i in range(config.crossValFolds):
for j in range(numRepeats):
val_results = crossValTrainTestBotRGCN(config.embedding_size, config.dropout, config.lr, \
config.weight_decay, config.svdComponents, config.thirds, config.epochs, config.testing_enabled, \
using_external_config=True, augmentedDataset=config.augmentedDataset, datasetVariant=config.datasetVariant, \
crossValFolds=config.crossValFolds, crossValIteration=i, dev=config.dev)
for key in val_results:
if key not in aggregate_results:
aggregate_results[key] = []
if key != 'conf_matrix_val':
aggregate_results[key].append(val_results[key])
else:
aggregate_results[key].append(val_results[key].numpy())
mean_results = {}
result_stdev = {}
# print(aggregate_results)
for key in aggregate_results:
if 'roc_curve' in key:
continue
mean_results["mean_" + key] = np.array(aggregate_results[key]).mean(axis=0)
result_stdev["stdev_" + key] = np.array(aggregate_results[key]).std(axis=0)
wandb.log(mean_results)
wandb.log(result_stdev)