-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.py
194 lines (164 loc) · 5.71 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
from sklearn.metrics import classification_report, f1_score
import pandas as pd
import numpy as np
import argparse
import logging
import os
import torch
import torch.optim as optim
from logger import setup_logging
from utils import (
dataset,
models,
test,
train,
utils,
visualisation,
)
LOG_CONFIG_PATH = os.path.join(os.path.abspath("."), "logger", "logger_config.json")
LOG_DIR = os.path.join(os.path.abspath("."), "logs")
DATA_DIR = os.path.join(os.path.abspath('.'), "data")
IMAGE_DIR = os.path.join(os.path.abspath("."), "images")
MODEL_DIR = os.path.join(os.path.abspath("."), "checkpoints")
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Ensure that all operations are deterministic for reproducibility, even on GPU (if used)
utils.set_seed(42)
torch.backends.cudnn.determinstic = True
torch.backends.cudnn.benchmark = False
def main(config):
"""Centralised"""
# Configure logging module
utils.mkdir(LOG_DIR)
setup_logging(save_dir=LOG_DIR, log_config=LOG_CONFIG_PATH)
logging.info(f'######## Training the {config["name"]} model ########')
model = models.load_model(model_name=config["model"]["type"], params=config["model"]["args"])
model.to(DEVICE)
logging.info("Loading dataset...")
train_loader, valid_loader, test_loader = dataset.load_data(
data_path=DATA_DIR,
balanced=config["data_loader"]["args"]["balanced"],
batch_size=config["data_loader"]["args"]["batch_size"],
)
logging.info("Dataset loaded!")
criterion = getattr(torch.nn, config["loss"]["type"])(**config["loss"]["args"])
if config["model"]["type"] == "DBN":
optimizer = [
getattr(torch.optim, config["optimizer"]["type"])(params=m.parameters(), **config["optimizer"]["args"])
for m in model.models
]
# Pre-train the DBN model
logging.info("Start pre-training the model...")
model.fit(train_loader)
else:
optimizer = [getattr(torch.optim, config["optimizer"]["type"])(params=model.parameters(), **config["optimizer"]["args"])]
logging.info("Start training the model...")
train_history = train(
model=model,
criterion=criterion,
optimizer=optimizer,
train_loader=train_loader,
valid_loader=valid_loader,
num_epochs=config["trainer"]["num_epochs"],
device=DEVICE
)
logging.info(f'{config["name"]} model trained!')
train_output_true = train_history["train"]["output_true"]
train_output_pred = train_history["train"]["output_pred"]
valid_output_true = train_history["valid"]["output_true"]
valid_output_pred = train_history["valid"]["output_pred"]
labels = ["Benign", "Botnet ARES", "Brute Force", "DoS/DDoS", "PortScan", "Web Attack"]
## Training Set results
logging.info('Training Set -- Classification Report')
logging.info(classification_report(
y_true=train_output_true,
y_pred=train_output_pred,
target_names=labels
))
visualisation.plot_confusion_matrix(
y_true=train_output_true,
y_pred=train_output_pred,
labels=labels,
save=True,
save_dir=IMAGE_DIR,
filename=f'{config["name"]}_train_confusion_matrix.pdf'
)
## Validation Set results
logging.info('Validation Set -- Classification Report')
logging.info(classification_report(
y_true=valid_output_true,
y_pred=valid_output_pred,
target_names=labels
))
visualisation.plot_confusion_matrix(
y_true=valid_output_true,
y_pred=valid_output_pred,
labels=labels,
save=True,
save_dir=IMAGE_DIR,
filename=f'{config["name"]}_train_confusion_matrix.pdf'
)
logging.info(f'Evaluate {config["name"]} model')
test_history = test(
model=model,
criterion=criterion,
test_loader=test_loader,
device=DEVICE
)
test_output_true = test_history["test"]["output_true"]
test_output_pred = test_history["test"]["output_pred"]
test_output_pred_prob = test_history["test"]["output_pred_prob"]
## Testing Set results
logging.info(f'Testing Set -- Classification Report {config["name"]}\n')
logging.info(classification_report(
y_true=test_output_true,
y_pred=test_output_pred,
target_names=labels
))
utils.mkdir(IMAGE_DIR)
visualisation.plot_confusion_matrix(
y_true=test_output_true,
y_pred=test_output_pred,
labels=labels,
save=True,
save_dir=IMAGE_DIR,
filename=f'{config["name"]}_test_confusion_matrix.pdf'
)
y_test = pd.get_dummies(test_output_true).values
y_score = np.array(test_output_pred_prob)
# Plot ROC curve
visualisation.plot_roc_curve(
y_test=y_test,
y_score=y_score,
labels=labels,
save=True,
save_dir=IMAGE_DIR,
filename=f'{config["name"]}_roc_curve.pdf'
)
# Plot Precision vs. Recall curve
visualisation.plot_precision_recall_curve(
y_test=y_test,
y_score=y_score,
labels=labels,
save=True,
save_dir=IMAGE_DIR,
filename=f'{config["name"]}_prec_recall_curve.pdf'
)
path = os.path.join(MODEL_DIR, f'{config["name"]}.pt')
utils.mkdir(MODEL_DIR)
torch.save({
'epoch': config["trainer"]["num_epochs"],
'model_state_dict': model.state_dict(),
}, path)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--config",
type=str,
default=None,
required=True,
help="Config file path. (default: None)"
)
args = parser.parse_args()
config = utils.read_json(args.config)
main(config)