forked from Maddi97/kmlmm_kdd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
svm.py
305 lines (227 loc) · 10.5 KB
/
svm.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
import matplotlib.pyplot as plt
import numpy as np
from numpy.random.mtrand import seed
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, f1_score, recall_score, precision_score
import pandas as pd
import time
from sklearn.preprocessing import MinMaxScaler
from sklearn.utils import validation
from preprocess import preprocess
import pickle
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier, BaggingClassifier
### DATA ###
df = pd.read_csv('dataset/kdd_train.csv')
d_train = np.array(df)
d_train_X = d_train[:, 0:-1]
d_train_y = d_train[:, -1]
X_train, X_validation, y_train, y_validation = train_test_split(d_train_X, d_train_y, test_size=0.2)
train_data = np.concatenate((X_train, np.array(y_train).reshape(len(y_train), 1)), axis=1)
validation_data = np.concatenate((X_validation, np.array(y_validation).reshape(len(y_validation), 1)), axis=1)
#pd.DataFrame(validation_data).to_csv('dataset/validation_data.csv')
#validation_data =pd.read_csv("dataset/validation_data.csv")
test = np.array(pd.read_csv('dataset/kdd_test.csv'))
sum_class = len(d_train_y)
class_weights = [int(((1 - (list(d_train_y).count(i) / sum_class))/4)*1000) for i in range(5)]
#############
def prepare_data(data, n):
check = False
while(not check):
#shuffle data on every run
#split in N chunks
new_data = np.array_split(data, n)
check = True
for arr in new_data:
if len(np.unique(np.array(arr)[:,-1])) < 5:
check = False
return np.array(new_data)
def prepare_data_overlapping(data, n):
new_data = []
check=False
while(not check):
#np.random.shuffle(data)
temp_buckets = np.array_split(data, n)
np.random.seed(42)
np.random.shuffle(data)
new_random_bucks = np.array_split(data, n)
new_data = [np.concatenate((np.array(temp_buckets[i]).squeeze(), np.array(new_random_bucks[i]).squeeze()), axis=0) for i in range(len(temp_buckets))]
check = True
for arr in new_data:
if len(np.unique(np.array(arr)[:,-1])) < 5:
check = False
return np.array(new_data)
#create multiple svms and store in array
def get_mult_svm(c_parameters, kernel, n):
weights = {0: class_weights[0], 1: class_weights[1], 2: class_weights[2], 3: class_weights[3], 4: class_weights[4]}
SVMs = [SVC(C=c_parameters[i], kernel=kernel, class_weight=weights) for i in range(n)]
return SVMs
#train every svm on the subset
#cnt is number of rounds
def train(svms, data):
# shuffle data random for every new training round
start_time = time.time()
for i in range(len(svms)):
d = data[i]
X = d[:, 0:-1]
y = d[:,-1]
svm = svms[i]
print("Training of SVM nr " + str(i) + " started at ... " + str(time.time()))
svm.fit(X,y)
print("--- %s seconds ---" % (time.time() - start_time))
t = (time.time() - start_time)
return svms, t
def predict(svms, test):
test_X = test[:, 0:-1]
test_y = test[:,-1]
y_pred = []
for elem in range(len(test_X)):
pred = []
for i in range(len(svms)):
# prediction of svm nr i
p = svms[i].predict(test_X[elem].reshape(1, -1))
pred.append(int(p.squeeze()))
# vote which is the actual predition
pred = np.bincount(pred).argmax()
y_pred.append(pred)
y_pred = np.asarray(y_pred)
acc = accuracy_score(test_y, y_pred)
f1 = f1_score(test_y, y_pred, average='weighted')
rec = recall_score(test_y, y_pred, average='weighted')
prec = precision_score(test_y, y_pred, average='weighted')
print("Accuracy:", acc)
print("F1:", f1)
print("Recall:", rec)
print("Precision:", prec)
return acc, f1, rec, prec
# report
# cr_matrix = classification_report(test_y, y_pred)
# print(cr_matrix)
### confusion matrix
# cm = confusion_matrix(test_y, y_pred)
# fig, ax = plt.subplots(figsize=(8, 8))
# ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=["normal", "DoS", "Probe", "U2R", "R2L"]
# ).plot(ax=ax)
# plt.title('Confusion Marix of majority voting SVM')
# plt.show()
#### Saving and Loading the SVMs
def save_models(models, d, n, c):
for i in range(len(models)):
filename = 'models/svm_{}_data_{}_n_{}_c_{}.sav'.format(i, d, n, c)
pickle.dump(models[i], open(filename, 'wb'))
def load_models(n, c, data):
svms = []
for i in range(n):
filename = 'models/svm_{}_data_{}_n_{}_c_{}.sav'.format(i, data, n, c)
svms.append(pickle.load(open(filename, 'rb')))
return svms
### Random Forest Implementation
def train_tree(X, y):
clf = RandomForestClassifier(max_depth=40, random_state=10, verbose=1)
clf.fit(X, y)
return clf
def pred_tree(X, y, clf):
y_pred = clf.predict(X)
print("Accuracy:", accuracy_score(y, y_pred))
def pred_bag(X, y, clf):
print("predict")
y_pred = clf.predict(X)
print("Accuracy:", accuracy_score(y, y_pred))
#create N svms and return them in list
def parameter_eval():
ns = [ 7, 10]
cs = [10**(-5), 10**(-4), 10**(-3), 10**(-2), 10**(-1), 1, 10, 100, 1000]
kernel = 'linear'
# data = prepare_data_overlapping(train_data, n)
column_names = ['num_svms', 'c', 'acc', 'f1', 'time']
df = pd.DataFrame(columns = column_names)
# np.random.shuffle(train_data)
# print(np.array(train_data).shape)
# pd.DataFrame(np.array(train_data)).to_csv('random_train_data.csv')
train_data = np.asarray(pd.read_csv('random_train_data.csv'))
train_data = np.delete(train_data, 0, axis=1)
for n in ns:
data = prepare_data_overlapping(train_data, n)
for c in cs:
c_parameters = [c for i in range(n)]
print(str(n) + " machines, c-parameter: " + str(c) )
svms = get_mult_svm(c_parameters=c_parameters, kernel=kernel, n=n)
#data = prepare_data_overlapping(train_data, n)
#print(len(d_train))
#train N svms in cnt rounds
svms, t = train(svms, data)
#save_models(svms)
#svms = load_models()
#save_models(svms)
acc, f1, rec, prec = predict(svms, test=validation_data)
df = df.append({'num_svms': n, 'c': c, 'acc': acc, 'f1': f1, 'recall': rec, 'precision':prec ,'time': t}, ignore_index=True)
df.to_csv('results/overlap_params_results.csv')
def experimentation_and_training():
n = 7
data = ['overlap']
cs = [
[10,10,10,10,10, 10,10], [100,100,100,100,100,100, 100], [1000,1000,1000,1000,1000,1000,1000],
[10,10,10,10,10,10,100], [10,10,10,10,10,10,1000], [100, 100, 100, 100,100,100, 10], [100, 100, 100, 100,100,100, 1000], [1000, 1000, 1000, 1000,1000,1000, 10], [1000, 1000, 1000, 1000,1000,1000, 100],
[10, 10, 10,10,10, 100, 100], [10, 10, 10,10,10, 1000, 1000], [100, 100, 100,100,100, 10, 10], [100, 100, 100,100,100, 1000, 1000], [1000, 1000, 1000,1000,1000, 10, 10], [1000, 1000, 1000, 1000,1000, 100, 100],
[10, 10, 10,10,100, 100, 100], [10, 10, 10,10,1000, 1000, 1000], [100, 100, 100,100,10, 10, 10], [100, 100, 100,100,1000, 1000, 1000], [1000, 1000, 1000,1000,10, 10, 10], [1000, 1000, 1000, 1000,100, 100, 100],
[10,10,10,10,10,100,1000], [100,100,100,100,100,10,1000], [1000,1000,1000,1000,1000,10,100],
[10,10,10,10,100,100,1000], [10,10,10,10,100,1000,1000],[100,100,100,100,10,10,1000], [100,100,100,100,10,1000,1000], [1000,1000,1000,1000,10,10,100], [1000,1000,1000,1000,10,100,100],
[10,10,10,100,100,100,1000],[10,10,10,100,100,1000,1000],[10,10,10,100,1000,1000,1000], [100,100,100,10,10,10,1000],[100,100,100,10,10,1000,1000],[100,100,100,10,1000,1000,1000], [100,100,10,10,1000,1000,1000],
]
kernel = 'linear'
# data = prepare_data_overlapping(train_data, n)
column_names = ['data','num_svms', 'c', 'acc', 'f1', 'time']
df = pd.DataFrame(columns = column_names)
# np.random.shuffle(train_data)
# print(np.array(train_data).shape)
# pd.DataFrame(np.array(train_data)).to_csv('random_train_data.csv')
train_data = np.asarray(pd.read_csv('random_train_data.csv'))
train_data = np.delete(train_data, 0, axis=1)
for d in data:
if d == 'non': data = prepare_data(train_data, n)
else: data = prepare_data_overlapping(train_data, n)
for c in cs:
print(str(n) + " machines, c-parameter: " + str(c) + 'data: ' + d)
svms = get_mult_svm(c_parameters=c, kernel=kernel, n=n)
#data = prepare_data_overlapping(train_data, n)
#print(len(d_train))
#train N svms in cnt rounds
svms, t = train(svms, data)
save_models(svms, d, n, c)
print("... models saved ...")
#svms = load_models()
#save_models(svms)
acc, f1, rec, prec = predict(svms, test=test)
print('time: {} f1: {}'.format(t,f1))
df = df.append({'data':d, 'num_svms': n, 'c': c, 'acc': acc, 'f1': f1, 'recall': rec, 'precision':prec ,'time': t}, ignore_index=True)
df.to_csv('results/experiment_overlap_results.csv')
def run_single_experiment():
column_names = ['data','num_svms', 'c', 'acc', 'f1', 'time']
df = pd.DataFrame(columns = column_names)
cs = [10,100,1000]
for c in cs:
svms = get_mult_svm(c_parameters=[c], kernel='linear', n=1)
train_data = np.asarray(pd.read_csv('random_train_data.csv'))
train_data = np.delete(train_data, 0, axis=1)
X = train_data[:, 0:-1]
y = train_data[:,-1]
start_time = time.time()
svms[0].fit(X,y)
t = (time.time() - start_time)
acc, f1, rec, prec = predict(svms, test=test)
print('time: {} f1: {}'.format(t,f1))
df = df.append({'data': 'non', 'num_svms': 1, 'c': c, 'acc': acc, 'f1': f1, 'recall': rec, 'precision':prec ,'time': t}, ignore_index=True)
df.to_csv('results/results_single_svm.csv')
# runs the final model which turned out to be the best (u can also change parameters to load other svms into the ensemble)
def run_final_model():
n = 5
c = [100 for i in range(5)]
data = 'non'
svms = load_models(n, c, data)
#save_models(svms)
acc, f1, rec, prec = predict(svms, test=test)
print('Acc: {} f1: {} recall: {} precision: {} '.format(acc, f1, rec, prec))
run_final_model()