-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMTH_IDS_IoTJ.py
1539 lines (1080 loc) · 38 KB
/
MTH_IDS_IoTJ.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# # MTH-IDS: A Multi-Tiered Hybrid Intrusion Detection System for Internet of Vehicles
# This is the code for the paper entitled "[**MTH-IDS: A Multi-Tiered Hybrid Intrusion Detection System for Internet of Vehicles**](https://arxiv.org/pdf/2105.13289.pdf)" accepted in IEEE Internet of Things Journal.
# Authors: Li Yang ([email protected]), Abdallah Moubayed, and Abdallah Shami
# Organization: The Optimized Computing and Communications (OC2) Lab, ECE Department, Western University
#
# If you find this repository useful in your research, please cite:
# L. Yang, A. Moubayed, and A. Shami, “MTH-IDS: A Multi-Tiered Hybrid Intrusion Detection System for Internet of Vehicles,” IEEE Internet of Things Journal, vol. 9, no. 1, pp. 616-632, Jan.1, 2022.
# ## Import libraries
# In[1]:
import warnings
warnings.filterwarnings("ignore")
# In[2]:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score,precision_recall_fscore_support
from sklearn.metrics import f1_score,roc_auc_score
from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier
from sklearn.tree import DecisionTreeClassifier
import xgboost as xgb
from xgboost import plot_importance
import requests # for get requests
import json # to handle json requests from api endpoint
def getinputs():
try:
# Make a GET request to the endpoint
response = requests.get('http://127.0.0.1:5000/fetch-data/mth')
# Check if the request was successful (status code 200)
if response.status_code == 200:
# If successful, return the JSON data
return response.json()
else:
# If not successful, print an error message
print("Error:", response.status_code)
return {'model':{'input_list': None}}
except requests.exceptions.RequestException as e:
# Handle any exceptions that occur during the request
print("Exception:", e)
return {'model':{'input_list': None}}
# print('RESPONSES ON HERE: ' + json.dumps(getinputs()))
test = json.dumps(getinputs())
algorithm_data = json.loads(test)
print(f'Algorithm Data: {algorithm_data}')
ds = algorithm_data['dataset']
if ds == "":
ds = "CICIDS2017_sample_km.csv"
if algorithm_data['random_state'] == '':
rs = 0
else:
rs = int(algorithm_data['random_state'])
if algorithm_data['learning_rate'] == '':
lr_empty = True
else:
lr_empty = False
lr = float(algorithm_data['learning_rate'])
if algorithm_data['n_estimator'] == '':
ne_empty = True
else:
ne_empty = False
ne = int(algorithm_data['n_estimator'])
if algorithm_data['max_depth'] == '':
md_empty = True
else :
md_empty = False
md = int(algorithm_data['max_depth'])
if algorithm_data['max_feature'] == '':
mf_empty = True
else :
mf_empty = False
mf = int(algorithm_data['max_feature'])
if algorithm_data['min_samples_split'] == '':
mss_empty = True
else :
mss_empty = False
mss = float(algorithm_data['min_samples_split'])
if mss >= 2:
mss = int(mss)
if algorithm_data['min_samples_leaf'] == '':
msl_empty = True
else :
msl_empty = False
msl = float(algorithm_data['min_samples_leaf'])
if msl >= 2:
msl = int(msl)
print(f'Algorithm Data: {algorithm_data}')
# print(f'random_state: {rs}')
# print(f'learning_rate: {lr}')
# print(f'n_estimator: {ne}')
# print(f'max_depth: {lr}')
# print(f'max_feature: {mf}')
# print(f'min_samples_split: {mss}')
# print(f'min_samples_leaf: {msl}')
# Read the sampled CICIDS2017 dataset
# The CICIDS2017 dataset is publicly available at: https://www.unb.ca/cic/datasets/ids-2017.html
# Due to the large size of this dataset, the sampled subsets of CICIDS2017 is used. The subsets are in the "data" folder.
# If you want to use this code on other datasets (e.g., CAN-intrusion dataset), just change the dataset name and follow the same steps. The models in this code are generic models that can be used in any intrusion detection/network traffic datasets.
# # In[3]:
#Read dataset
#df = pd.read_csv('./data/CICIDS2017.csv')
# df = pd.read_csv('./data/CICIDS2017_sample.csv')
# dataset = './data/CICIDS2017_sample_km.csv'
dataset = "./data/" + ds
df = pd.read_csv(dataset)
# The results in this code is based on the original CICIDS2017 dataset. Please go to cell [21] if you work on the sampled dataset.
# In[4]:
df
# In[5]:
df.Label.value_counts()
# ### Preprocessing (normalization and padding values)
# In[6]:
# Z-score normalization
features = df.dtypes[(df.dtypes != 'object') & (df.columns != 'Destination Port')].index
df[features] = df[features].apply(
lambda x: (x - x.mean()) / (x.std()))
# Fill empty values by 0
df = df.fillna(0)
# ### Data sampling
# Due to the space limit of GitHub files and the large size of network traffic data, we sample a small-sized subset for model learning using **k-means cluster sampling**
# In[7]:
labelencoder = LabelEncoder()
df.iloc[:, -1] = labelencoder.fit_transform(df.iloc[:, -1])
# In[8]:
df.Label.value_counts()
# In[9]:
# retain the minority class instances and sample the majority class instances
df_minor = df[(df['Label']==6)|(df['Label']==1)|(df['Label']==4)]
df_major = df.drop(df_minor.index)
# In[10]:
from sklearn.impute import SimpleImputer
# # Impute NaN values with mean
# imputer = SimpleImputer(strategy='mean')
# X = imputer.fit_transform(df_major.drop(['Label'],axis=1))
X = df_major.drop(['Label'],axis=1)
y = df_major.iloc[:, -1].values.reshape(-1,1)
y=np.ravel(y)
# In[11]:
# use k-means to cluster the data samples and select a proportion of data from each cluster
from sklearn.cluster import MiniBatchKMeans
kmeans = MiniBatchKMeans(n_clusters=1000, random_state=0).fit(X)
# In[12]:
klabel=kmeans.labels_
df_major['klabel']=klabel
# In[13]:
df_major['klabel'].value_counts()
# In[14]:
cols = list(df_major)
cols.insert(78, cols.pop(cols.index('Label')))
df_major = df_major.loc[:, cols]
# In[15]:
df_major
# In[16]:
def typicalSampling(group):
name = group.name
frac = 0.008
return group.sample(frac=frac)
result = df_major.groupby(
'klabel', group_keys=False
).apply(typicalSampling)
# In[17]:
result['Label'].value_counts()
# In[18]:
result
# In[19]:
result = result.drop(['klabel'],axis=1)
# result = result.append(df_minor)
# # In[20]:
# result.to_csv('./data/CICIDS2017_sample_km.csv',index=0)
### split train set and test set
# In[21]:
# Read the sampled dataset
# df=pd.read_csv('./data/CICIDS2017_sample.csv')
df = pd.read_csv(dataset)
# In[22]:
from sklearn.preprocessing import StandardScaler
if dataset == "./data/CICIDS2017_sample_km.csv":
X = df.drop(['Label'],axis=1).values
else:
df['Label'] = df['Label'].map({
'BENIGN': 0,
'DoS': 3,
'WebAttack': 6,
'Bot': 1,
'PortScan': 5,
'BruteForce': 2,
'Infiltration': 4
})
df.fillna(0)
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df.fillna(1e9, inplace=True)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(df.drop(['Label'],axis=1).values)
imputer = SimpleImputer(strategy='mean')
X = imputer.fit_transform(X_scaled)
y = df.iloc[:, -1].values.reshape(-1,1)
y=np.ravel(y)
# In[23]:
X_train, X_test, y_train, y_test = train_test_split(X,y, train_size = 0.8, test_size = 0.2, random_state = 0,stratify = y)
# ## Feature engineering
# ### Feature selection by information gain
# In[24]:
from sklearn.feature_selection import mutual_info_classif
importances = mutual_info_classif(X_train, y_train)
# In[25]:
# calculate the sum of importance scores
f_list = sorted(zip(map(lambda x: round(x, 4), importances), features), reverse=True)
Sum = 0
fs = []
for i in range(0, len(f_list)):
Sum = Sum + f_list[i][0]
fs.append(f_list[i][1])
# In[26]:
# select the important features from top to bottom until the accumulated importance reaches 90%
f_list2 = sorted(zip(map(lambda x: round(x, 4), importances/Sum), features), reverse=True)
Sum2 = 0
fs = []
for i in range(0, len(f_list2)):
Sum2 = Sum2 + f_list2[i][0]
fs.append(f_list2[i][1])
if Sum2>=0.9:
break
# In[27]:
X_fs = df[fs].values
# In[28]:
X_fs.shape
# ### Feature selection by Fast Correlation Based Filter (FCBF)
#
# The module is imported from the GitHub repo: https://github.com/SantiagoEG/FCBF_module
# In[29]:
from FCBF_module import FCBF, FCBFK, FCBFiP, get_i
fcbf = FCBFK(k = 20)
#fcbf.fit(X_fs, y)
# In[30]:
X_fss = fcbf.fit_transform(X_fs,y)
# In[31]:
X_fss.shape
# ### Re-split train & test sets after feature selection
# In[32]:
X_train, X_test, y_train, y_test = train_test_split(X_fss,y, train_size = 0.8, test_size = 0.2, random_state = 0,stratify = y)
# In[33]:
X_train.shape
# In[34]:
pd.Series(y_train).value_counts()
# ### SMOTE to solve class-imbalance
# In[35]:
from imblearn.over_sampling import SMOTE
if dataset == './data/CICIDS2017_sample.csv':
smote=SMOTE(n_jobs=-1,sampling_strategy={4:1000})
else:
smote=SMOTE(n_jobs=-1,sampling_strategy={2:1000,4:1000})
# In[36]:
X_train, y_train = smote.fit_resample(X_train, y_train)
# In[37]:
pd.Series(y_train).value_counts()
# ## Machine learning model training
# ### Training four base learners: decision tree, random forest, extra trees, XGBoost
# #### Apply XGBoost
# In[58]:
if ne_empty:
ne = 10
xg = xgb.XGBClassifier(n_estimators = ne)
xg.fit(X_train,y_train)
xg_score=xg.score(X_test,y_test)
y_predict=xg.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of XGBoost: '+ str(xg_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of XGBoost: '+(str(precision)))
print('Recall of XGBoost: '+(str(recall)))
print('F1-score of XGBoost: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_XGBoost.png")
print("STOP")
# plt.show()
# #### Hyperparameter optimization (HPO) of XGBoost using Bayesian optimization with tree-based Parzen estimator (BO-TPE)
# Based on the GitHub repo for HPO: https://github.com/LiYangHart/Hyperparameter-Optimization-of-Machine-Learning-Algorithms
# In[113]:
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from sklearn.model_selection import cross_val_score, StratifiedKFold
def objective(params):
params = {
'n_estimators': int(params['n_estimators']),
'max_depth': int(params['max_depth']),
'learning_rate': abs(float(params['learning_rate'])),
}
clf = xgb.XGBClassifier( **params)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
score = accuracy_score(y_test, y_pred)
return {'loss':-score, 'status': STATUS_OK }
space = {
'n_estimators': hp.quniform('n_estimators', 10, 100, 5),
'max_depth': hp.quniform('max_depth', 4, 100, 1),
'learning_rate': hp.normal('learning_rate', 0.01, 0.9),
}
best = fmin(fn=objective,
space=space,
algo=tpe.suggest,
max_evals=20)
print("XGBoost: Hyperopt estimated optimum {}".format(best))
# In[114]:
if lr_empty:
lr = 0.7340229699980686
if ne_empty:
ne = 70
if md_empty:
md = 14
xg = xgb.XGBClassifier(learning_rate= lr, n_estimators = ne, max_depth = md)
xg.fit(X_train,y_train)
xg_score=xg.score(X_test,y_test)
y_predict=xg.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of XGBoost: '+ str(xg_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of XGBoost: '+(str(precision)))
print('Recall of XGBoost: '+(str(recall)))
print('F1-score of XGBoost: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_hyperopt_xgb.png")
print("STOP")
# plt.show()
# In[115]:
xg_train=xg.predict(X_train)
xg_test=xg.predict(X_test)
# #### Apply RF
# In[103]:
rf = RandomForestClassifier(random_state = rs)
rf.fit(X_train,y_train)
rf_score=rf.score(X_test,y_test)
y_predict=rf.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of RF: '+ str(rf_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of RF: '+(str(precision)))
print('Recall of RF: '+(str(recall)))
print('F1-score of RF: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_RandomForest.png")
print("STOP")
# plt.show()
# #### Hyperparameter optimization (HPO) of random forest using Bayesian optimization with tree-based Parzen estimator (BO-TPE)
# Based on the GitHub repo for HPO: https://github.com/LiYangHart/Hyperparameter-Optimization-of-Machine-Learning-Algorithms
# In[90]:
# Hyperparameter optimization of random forest
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from sklearn.model_selection import cross_val_score, StratifiedKFold
# Define the objective function
def objective(params):
params = {
'n_estimators': int(params['n_estimators']),
'max_depth': int(params['max_depth']),
'max_features': int(params['max_features']),
"min_samples_split":int(params['min_samples_split']),
"min_samples_leaf":int(params['min_samples_leaf']),
"criterion":str(params['criterion'])
}
clf = RandomForestClassifier( **params)
clf.fit(X_train,y_train)
score=clf.score(X_test,y_test)
return {'loss':-score, 'status': STATUS_OK }
# Define the hyperparameter configuration space
space = {
'n_estimators': hp.quniform('n_estimators', 10, 200, 1),
'max_depth': hp.quniform('max_depth', 5, 50, 1),
"max_features":hp.quniform('max_features', 1, 20, 1),
"min_samples_split":hp.quniform('min_samples_split',2,11,1),
"min_samples_leaf":hp.quniform('min_samples_leaf',1,11,1),
"criterion":hp.choice('criterion',['gini','entropy'])
}
best = fmin(fn=objective,
space=space,
algo=tpe.suggest,
max_evals=20)
print("Random Forest: Hyperopt estimated optimum {}".format(best))
# In[104]:
if ne_empty:
ne = 71
if msl_empty:
msl = 1
if md_empty:
md = 46
if mss_empty:
mss = 9
if mf_empty:
mf = 20
rf_hpo = RandomForestClassifier(n_estimators = ne, min_samples_leaf = msl, max_depth = md, min_samples_split = mss, max_features = mf, criterion = 'entropy')
rf_hpo.fit(X_train,y_train)
rf_score=rf_hpo.score(X_test,y_test)
y_predict=rf_hpo.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of RF: '+ str(rf_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of RF: '+(str(precision)))
print('Recall of RF: '+(str(recall)))
print('F1-score of RF: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_hyperopt_rf.png")
print("STOP")
# plt.show()
# In[105]:
rf_train=rf_hpo.predict(X_train)
rf_test=rf_hpo.predict(X_test)
# #### Apply DT
# In[100]:
dt = DecisionTreeClassifier(random_state = rs)
dt.fit(X_train,y_train)
dt_score=dt.score(X_test,y_test)
y_predict=dt.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of DT: '+ str(dt_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of DT: '+(str(precision)))
print('Recall of DT: '+(str(recall)))
print('F1-score of DT: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_DecisionTree.png")
print("STOP")
# plt.show()
# #### Hyperparameter optimization (HPO) of decision tree using Bayesian optimization with tree-based Parzen estimator (BO-TPE)
# Based on the GitHub repo for HPO: https://github.com/LiYangHart/Hyperparameter-Optimization-of-Machine-Learning-Algorithms
# In[95]:
# Hyperparameter optimization of decision tree
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from sklearn.model_selection import cross_val_score, StratifiedKFold
# Define the objective function
def objective(params):
params = {
'max_depth': int(params['max_depth']),
'max_features': int(params['max_features']),
"min_samples_split":int(params['min_samples_split']),
"min_samples_leaf":int(params['min_samples_leaf']),
"criterion":str(params['criterion'])
}
clf = DecisionTreeClassifier( **params)
clf.fit(X_train,y_train)
score=clf.score(X_test,y_test)
return {'loss':-score, 'status': STATUS_OK }
# Define the hyperparameter configuration space
space = {
'max_depth': hp.quniform('max_depth', 5, 50, 1),
"max_features":hp.quniform('max_features', 1, 20, 1),
"min_samples_split":hp.quniform('min_samples_split',2,11,1),
"min_samples_leaf":hp.quniform('min_samples_leaf',1,11,1),
"criterion":hp.choice('criterion',['gini','entropy'])
}
best = fmin(fn=objective,
space=space,
algo=tpe.suggest,
max_evals=50)
print("Decision tree: Hyperopt estimated optimum {}".format(best))
# In[101]:
if msl_empty:
msl = 2
if md_empty:
md = 47
if mss_empty:
mss = 3
if mf_empty:
mf = 19
dt_hpo = DecisionTreeClassifier(min_samples_leaf = msl, max_depth = md, min_samples_split = mss, max_features = mf, criterion = 'gini')
dt_hpo.fit(X_train,y_train)
dt_score=dt_hpo.score(X_test,y_test)
y_predict=dt_hpo.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of DT: '+ str(dt_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of DT: '+(str(precision)))
print('Recall of DT: '+(str(recall)))
print('F1-score of DT: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_hyperopt_dt.png")
print("STOP")
# plt.show()
# In[102]:
dt_train=dt_hpo.predict(X_train)
dt_test=dt_hpo.predict(X_test)
# #### Apply ET
# In[106]:
et = ExtraTreesClassifier(random_state = rs)
et.fit(X_train,y_train)
et_score=et.score(X_test,y_test)
y_predict=et.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of ET: '+ str(et_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of ET: '+(str(precision)))
print('Recall of ET: '+(str(recall)))
print('F1-score of ET: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_ExtraTree.png")
print("STOP")
# plt.show()
# #### Hyperparameter optimization (HPO) of extra trees using Bayesian optimization with tree-based Parzen estimator (BO-TPE)
# Based on the GitHub repo for HPO: https://github.com/LiYangHart/Hyperparameter-Optimization-of-Machine-Learning-Algorithms
# In[107]:
# Hyperparameter optimization of extra trees
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from sklearn.model_selection import cross_val_score, StratifiedKFold
# Define the objective function
def objective(params):
params = {
'n_estimators': int(params['n_estimators']),
'max_depth': int(params['max_depth']),
'max_features': int(params['max_features']),
"min_samples_split":int(params['min_samples_split']),
"min_samples_leaf":int(params['min_samples_leaf']),
"criterion":str(params['criterion'])
}
clf = ExtraTreesClassifier( **params)
clf.fit(X_train,y_train)
score=clf.score(X_test,y_test)
return {'loss':-score, 'status': STATUS_OK }
# Define the hyperparameter configuration space
space = {
'n_estimators': hp.quniform('n_estimators', 10, 200, 1),
'max_depth': hp.quniform('max_depth', 5, 50, 1),
"max_features":hp.quniform('max_features', 1, 20, 1),
"min_samples_split":hp.quniform('min_samples_split',2,11,1),
"min_samples_leaf":hp.quniform('min_samples_leaf',1,11,1),
"criterion":hp.choice('criterion',['gini','entropy'])
}
best = fmin(fn=objective,
space=space,
algo=tpe.suggest,
max_evals=20)
print("Random Forest: Hyperopt estimated optimum {}".format(best))
# In[108]:
if ne_empty:
ne = 53
if msl_empty:
msl = 1
if md_empty:
md = 31
if mss_empty:
mss = 5
if mf_empty:
mf = 20
et_hpo = ExtraTreesClassifier(n_estimators = ne, min_samples_leaf = msl, max_depth = md, min_samples_split = mss, max_features = mf, criterion = 'entropy')
et_hpo.fit(X_train,y_train)
et_score=et_hpo.score(X_test,y_test)
y_predict=et_hpo.predict(X_test)
y_true=y_test
print("START")
print('Accuracy of ET: '+ str(et_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of ET: '+(str(precision)))
print('Recall of ET: '+(str(recall)))
print('F1-score of ET: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_hyperopt_et.png")
print("STOP")
# plt.show()
# In[109]:
et_train=et_hpo.predict(X_train)
et_test=et_hpo.predict(X_test)
# ### Apply Stacking
# The ensemble model that combines the four ML models (DT, RF, ET, XGBoost)
# In[116]:
base_predictions_train = pd.DataFrame( {
'DecisionTree': dt_train.ravel(),
'RandomForest': rf_train.ravel(),
'ExtraTrees': et_train.ravel(),
'XgBoost': xg_train.ravel(),
})
base_predictions_train.head(5)
# In[117]:
dt_train=dt_train.reshape(-1, 1)
et_train=et_train.reshape(-1, 1)
rf_train=rf_train.reshape(-1, 1)
xg_train=xg_train.reshape(-1, 1)
dt_test=dt_test.reshape(-1, 1)
et_test=et_test.reshape(-1, 1)
rf_test=rf_test.reshape(-1, 1)
xg_test=xg_test.reshape(-1, 1)
# In[118]:
dt_train.shape
# In[119]:
x_train = np.concatenate(( dt_train, et_train, rf_train, xg_train), axis=1)
x_test = np.concatenate(( dt_test, et_test, rf_test, xg_test), axis=1)
# In[120]:
stk = xgb.XGBClassifier().fit(x_train, y_train)
y_predict=stk.predict(x_test)
y_true=y_test
stk_score=accuracy_score(y_true,y_predict)
print("START")
print('Accuracy of Stacking: '+ str(stk_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of Stacking: '+(str(precision)))
print('Recall of Stacking: '+(str(recall)))
print('F1-score of Stacking: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_stacking_xgb.png")
print("STOP")
# plt.show()
# #### Hyperparameter optimization (HPO) of the stacking ensemble model (XGBoost) using Bayesian optimization with tree-based Parzen estimator (BO-TPE)
# Based on the GitHub repo for HPO: https://github.com/LiYangHart/Hyperparameter-Optimization-of-Machine-Learning-Algorithms
# In[123]:
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from sklearn.model_selection import cross_val_score, StratifiedKFold
def objective(params):
params = {
'n_estimators': int(params['n_estimators']),
'max_depth': int(params['max_depth']),
'learning_rate': abs(float(params['learning_rate'])),
}
clf = xgb.XGBClassifier( **params)
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
score = accuracy_score(y_test, y_pred)
return {'loss':-score, 'status': STATUS_OK }
space = {
'n_estimators': hp.quniform('n_estimators', 10, 100, 5),
'max_depth': hp.quniform('max_depth', 4, 100, 1),
'learning_rate': hp.normal('learning_rate', 0.01, 0.9),
}
best = fmin(fn=objective,
space=space,
algo=tpe.suggest,
max_evals=20)
print("XGBoost: Hyperopt estimated optimum {}".format(best))
# In[124]:
if lr_empty:
lr = 0.19229249758051492
if ne_empty:
ne = 30
if md_empty:
md = 36
xg = xgb.XGBClassifier(learning_rate= lr, n_estimators = ne, max_depth = md)
xg.fit(x_train,y_train)
xg_score=xg.score(x_test,y_test)
y_predict=xg.predict(x_test)
y_true=y_test
print("START")
print('Accuracy of XGBoost: '+ str(xg_score))
precision,recall,fscore,none= precision_recall_fscore_support(y_true, y_predict, average='weighted')
print('Precision of XGBoost: '+(str(precision)))
print('Recall of XGBoost: '+(str(recall)))
print('F1-score of XGBoost: '+(str(fscore)))
print(classification_report(y_true,y_predict))
cm=confusion_matrix(y_true,y_predict)
f,ax=plt.subplots(figsize=(5,5))
sns.heatmap(cm,annot=True,linewidth=0.5,linecolor="red",fmt=".0f",ax=ax)
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.savefig("heatmaps/MTH_stacking_hyperopt_xgb.png")
print("STOP")
# plt.show()
# # ## Anomaly-based IDS
# # ### Generate the port-scan datasets for unknown attack detection
# # In[131]:
# df=pd.read_csv('./data/CICIDS2017_sample_km.csv')
# # In[132]: