-
Notifications
You must be signed in to change notification settings - Fork 2
/
code_nn.py
219 lines (176 loc) · 6.25 KB
/
code_nn.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 16:27:49 2018
@author: adityapandey
"""
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import itertools
print("-"*30)
print("Neural Network Model")
print("-"*30)
print()
#PreProcessing
kdd_10 = pd.read_csv("Final3.csv")
kdd_10=kdd_10.drop('service',axis=1)
kdd_10=kdd_10.drop('flag',axis=1)
alength= len(kdd_10)
protocol_type={'udp': np.zeros(alength,dtype= int), 'tcp': np.zeros(alength,dtype= int), 'icmp': np.zeros(alength,dtype= int), 'other': np.zeros(alength,dtype= int)}
for i in range(alength):
protocol_type[kdd_10.iloc[i]["protocol_type"]][i]=1
kdd_10['tcp'] = pd.Series(protocol_type["tcp"], index=kdd_10.index)
kdd_10['udp'] = pd.Series(protocol_type["udp"], index=kdd_10.index)
kdd_10['icmp'] = pd.Series(protocol_type["icmp"], index=kdd_10.index)
kdd_10 = kdd_10.drop("protocol_type", axis=1)
kdd_10['new_result']=1
kdd_10.loc[kdd_10['result']=='normal.','new_result']=0
kdd_10.isnull().values.any()
kdd_10.fillna(0, inplace=True)
kdd_10.isnull().values.any()
#Basic Data Analysis
def dataSetAnalysis(df):
print("Dataset Head")
print(df.head(3))
print("=" * 30)
print("Dataset Features")
print(df.columns.values)
print("=" * 30)
print("Dataset Features Details")
print(df.info())
print("=" * 30)
print("Dataset Numerical Features")
print(df.describe())
print("=" * 30)
print("Dataset Categorical Features")
print(df.describe(include=['O']))
print("=" * 30)
dataSetAnalysis(kdd_10)
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import KFold
from sklearn.preprocessing import LabelEncoder
#Creating Matrix for input to Model
seed = 7
np.random.seed(seed)
dataset = kdd_10.values
result = kdd_10['result']
label = kdd_10['label']
kdd_10.drop(['label','result','new_result'], inplace=True, axis=1)
columns = kdd_10.columns
from sklearn import preprocessing
scaler = preprocessing.RobustScaler()
kdd_10_n = scaler.fit_transform(kdd_10)
kdd_10_n = pd.DataFrame(kdd_10_n, columns=columns)
kdd_10_n.head(5)
#Convert result variable to dummy variables (i.e. one hot encoded)
encoder = LabelEncoder()
encoder.fit(label)
encoded_lab = encoder.transform(label)
dummy_lab = np_utils.to_categorical(encoded_lab)
from ann_visualizer.visualize import ann_viz;
#Create model
def nn_model():
print("Model Running")
model = Sequential()
model.add(Dense(25, input_dim=41, activation='relu'))
model.add(Dense(18, activation='relu'))
model.add(Dense(12, activation='relu'))
model.add(Dense(5, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
ann_viz(model, title="Neural Network", filename="/Users/adityapandey/Desktop/5th Sem Project/Data Analytics/Nnet.gv")
return model
estimator = KerasClassifier(build_fn=nn_model, epochs=20, batch_size=5, verbose=0)
#K-Fold Cross Validation
kfold = KFold(n_splits=2, shuffle=True, random_state=seed)
pred_results = cross_val_predict(estimator, kdd_10_n, dummy_lab, cv=kfold)
#Evaluating Results
results_labels = pd.Series(encoder.inverse_transform(pred_results))
from sklearn.metrics import confusion_matrix
label = list(label)
results_labels = list(results_labels)
ans = confusion_matrix(list(label), list(results_labels), labels = ["normal","rtl","dos","u2r","probe"])
def perf_measure(ans, conf_list):
TP = []
FP = []
TN = []
FN = []
s=0
total=0
for i in range(len(conf_list)):
for j in range(len(conf_list)):
total+=ans[i][j]
for i in range(len(conf_list)):
TP.append(ans[i][i])
s=0
for j in range(len(conf_list)):
if(j!=i):
s+=ans[j][i]
FP.append(s)
FN.append(sum(ans[i])-TP[i])
TN.append(total-TP[i]-FP[i]-FN[i])
return(TP, FP, TN, FN)
final_accuracy =0.0
final_precision = 0.0
final_recall = 0.0
conf_list = ["normal","rtl","dos","u2r","probe"]
tp,fp,tn,fn=perf_measure(ans,conf_list)
for i in range(len(conf_list)):
accuracy=(tp[i]+tn[i])/(tp[i]+tn[i]+fp[i]+fn[i]) * 100
precision = tp[i] / (tp[i]+fp[i]) * 100
recall = tp[i] / (tp[i]+fn[i]) * 100
print("Precision of ",conf_list[i],": ",precision,sep="")
print("Recall of ",conf_list[i],": ",recall,sep="")
print("Accuracy of ",conf_list[i],": ",accuracy,sep="")
print()
final_precision+=precision
final_recall+=recall
final_accuracy+=accuracy
final_accuracy=final_accuracy/5
final_precision=final_precision/5
final_recall=final_recall/5
print()
print("Final Accuracy: %.3f%%" % (final_accuracy))
#Plotting Results
def plot_confusion_matrix(cm, classes,normalize=False,title='Confusion matrix',cmap=plt.cm.Blues):
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix:")
else:
print('Confusion matrix, without normalization:')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
time.sleep(1)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
plot_confusion_matrix(ans, conf_list)
time.sleep(4)
attack_label = ["normal" if x=="normal" else "attack" for x in label]
attack_results_label = ["normal" if x=='normal' else "attack" for x in results_labels]
ans_bin = confusion_matrix(attack_label, attack_results_label, labels = ["normal","attack"])
plot_confusion_matrix(ans_bin, ["normal","attack"])
kdd_10['result']=result
kdd_10['label']=label
kdd_10['predictions']=results_labels
print()
print("-"*30)
print("End of Neural Network Model")
print("-"*30)