-
Notifications
You must be signed in to change notification settings - Fork 3
/
training_rnn_ddos_attack.py
157 lines (118 loc) · 4.68 KB
/
training_rnn_ddos_attack.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
# -*- coding: utf-8 -*-
"""Training RNN DDOS Attack.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1L-_CNjZo4v7-e2_K9zBgPWgt_sVPBlb2
"""
!pip install chainer
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
import time
import copy
import numpy as np
import pandas as pd
import chainer
import chainer.functions as F
import chainer.links as L
from plotly import tools
from plotly.graph_objs import *
from plotly.offline import init_notebook_mode, iplot, iplot_mpl
import csv
from google.colab import drive
veri= pd.read_csv("/content/drive/MyDrive/DDos.pcap_ISCX.csv", delimiter=',', skiprows=0, low_memory=False)
veri.head()
!pip install cupy-cuda101>=7.7.0
veri[' Label'].replace(['BENIGN','DDoS'],[0,1],inplace=True)
moddf= veri.dropna()
moddf.shape
moddf.isna().any()[lambda x:x]
del moddf[' Flow Packets/s']
moddf.shape
features=[" Destination Port" , "Bwd Packet Length Max", " Bwd Packet Length Mean" , " Bwd Packet Length Std", " Packet Length Mean", " URG Flag Count", " Average Packet Size", " Avg Bwd Segment Size"," Flow Duration"," Total Fwd Packets"," Subflow Bwd Packets"," Label"]
len(features)
X=moddf[features].copy()
X.head()
giris = X.iloc[:,0:10]
cikis = X.iloc[:,-1]
print(cikis)
from sklearn.model_selection import train_test_split as tts
xtrain, xtest, ytrain, ytest = tts(giris, cikis, test_size=0.2)
xtrain
import tensorflow as tf
from keras.layers import Dense, BatchNormalization, Dropout, LSTM, Bidirectional
from keras.models import Sequential
from tensorflow.keras.utils import to_categorical
from keras.optimizers import Adam
from tensorflow.keras import regularizers
from sklearn.metrics import precision_score, recall_score, confusion_matrix, classification_report, accuracy_score, f1_score
from keras import callbacks
from tensorflow.keras.callbacks import EarlyStopping
#Early stopping
early_stopping = callbacks.EarlyStopping(
min_delta=0.001, # minimium amount of change to count as an improvement
patience=20, # how many epochs to wait before stopping
restore_best_weights=True,
)
x_train , y_train = np.array(xtrain), np.array(ytrain)
x_train = np.reshape(x_train, (xtrain.shape[0] , xtrain.shape[1], 1) )
regressor = Sequential()
regressor.add(Bidirectional(LSTM(units=10, return_sequences=True, input_shape = (x_train.shape[1],1) ) )) #çıktı uzayının boyutu
regressor.add(Dropout(0.2))
regressor.add(LSTM(units= 10 , return_sequences=True))
regressor.add(Dropout(0.2))
regressor.add(LSTM(units= 10 , return_sequences=True))
regressor.add(Dropout(0.2))
regressor.add(LSTM(units= 10))
regressor.add(Dropout(0.2))
regressor.add(Dense(units = 1,activation='sigmoid'))
regressor.compile(optimizer='adam', loss='binary_crossentropy',metrics=['acc'])
regressor.fit(x_train, y_train, epochs=10,batch_size=128 )
trainloss=regressor.evaluate(x_train,y_train,verbose=0)
x_test , y_test = np.array(xtest), np.array(ytest)
x_test = np.reshape(x_test, (xtest.shape[0] , xtest.shape[1], 1) )
testloss=regressor.evaluate(x_test,y_test,verbose=0)
predict = regressor.predict(x_test)
xtest.shape[1]
predict
predDf = pd.DataFrame(y_test,columns=["Real predictions:"])
predDf
predDf2 = pd.Series(predict.reshape(45149,))
predDf2
pred_results=pd.concat([predDf,predDf2],axis=1)
pred_results
pred_results.columns=['Real_Values', 'Predicted_Values']
pred_results
from sklearn.metrics import mean_absolute_error,mean_squared_error
errorAb=mean_absolute_error(pred_results["Real_Values"], pred_results["Predicted_Values"])
errorSQ=mean_squared_error(pred_results["Real_Values"], pred_results["Predicted_Values"])
errorAb
errorSQ
predict
regressor = Sequential()
regressor.add(Bidirectional(LSTM(units=10, return_sequences=True, input_shape = (x_train.shape[1],1) ) )) #çıktı uzayının boyutu
regressor.add(Dropout(0.2))
regressor.add(LSTM(units= 10 , return_sequences=True))
regressor.add(Dropout(0.2))
regressor.add(LSTM(units= 10 , return_sequences=True))
regressor.add(Dropout(0.2))
regressor.add(LSTM(units= 10))
regressor.add(Dropout(0.2))
regressor.add(Dense(units = 1,activation='sigmoid'))
regressor.compile(optimizer='adam', loss='binary_crossentropy',metrics=['acc'])
history=regressor.fit(x_train, y_train, epochs=3,batch_size=64 )
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()