-
Notifications
You must be signed in to change notification settings - Fork 0
/
svm.py
256 lines (224 loc) · 10.3 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
# Data Processing
from pathlib import Path
import json
import pandas as pd
import numpy as np
# Modelling
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay
from sklearn.model_selection import RandomizedSearchCV, train_test_split
from sklearn.svm import SVC
from scipy.stats import randint
import matplotlib.pyplot as plt
import joblib
import warnings
warnings.filterwarnings("ignore")
# # Tree Visualisation
# from sklearn.tree import export_graphviz
# import graphviz
preprocess_dir = Path('./preprocess/')
output_dir = Path('./svm/')
output_dir.mkdir(parents=True, exist_ok=True)
mode = 'multiclass' # mode = ['binary', 'multiclass']
feature_selection = False
weighted = False
tuning = False
tuning_adv = False
tuning_retrain = False
# Data
attack2idx_path = preprocess_dir / 'attack2idx.json'
attack2idx = json.loads(attack2idx_path.read_text())
attack_name = list(attack2idx.keys())
label = 'label' if mode[0] == 'b' else 'attack_cat'
def load_data(split):
data = pd.read_csv(preprocess_dir / f'{split}.csv')
X = data.drop(['id', 'label', 'attack_cat'], axis=1)
y = data[label]
return data, X, y
data_train, X_train, y_train = load_data('train')
data_test, X_test, y_test = load_data('test')
# Feature selection
if feature_selection:
correlation = data_train.corr()
correlation_target = abs(correlation[label])
relevant_features = correlation_target[correlation_target > 0.3]
relevant_features = relevant_features.drop(['id', 'label', 'attack_cat']).index.tolist()
X_train = X_train[relevant_features]
X_test = X_test[relevant_features]
# Split validation dataset
# X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, train_size=0.7, random_state=1)
# Training
def hyperparameter_tuning(X_train, y_train):
param_dist = {'n_estimators': randint(10,100),
'max_depth': randint(5,20)}
svm = SVC(C=100, kernel="linear")
# RandomForestClassifier(random_state=1, class_weight='balanced' if weighted else None)
rand_search = RandomizedSearchCV(
svm,
param_distributions = param_dist,
n_iter=10,
cv=5,
random_state=1,
return_train_score=True
)
rand_search.fit(X_train, y_train)
results_all = pd.DataFrame.from_dict(rand_search.cv_results_)
results = results_all[['params', 'mean_train_score', 'mean_test_score']]
results = results.sort_values(by=['mean_test_score'], ascending=False)
results = results.round(decimals=4)
return rand_search, results
if tuning:
rand_search, results = hyperparameter_tuning(X_train, y_train)
results.to_csv(output_dir / f'rf_results_{mode}.csv')
best_svm = rand_search.best_estimator_
print('Best hyperparameters:', rand_search.best_params_)
print('Best score:', rand_search.best_score_)
else:
best_svm = SVC(C=100, kernel="linear")
best_svm.fit(X_train, y_train)
joblib.dump(best_svm, './svm/best_svm.model')
# Evaluation
# Model performance
def evaluate(y_test, y_pred, cm_title='Confusion matrix', display_labels=attack_name, return_fool_ratio=True, count = 0):
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average=None)
precision_avg = precision_score(y_test, y_pred, average='weighted')
recall = recall_score(y_test, y_pred, average=None)
recall_avg = recall_score(y_test, y_pred, average='weighted')
f1 = f1_score(y_test, y_pred, average=None)
fl_avg = f1_score(y_test, y_pred, average='weighted')
# print("Accuracy:", accuracy)
# print("Precision:", precision)
# print("Precision (weighted):", precision_avg)
# print("Recall:", recall)
# print("Recall (weighted):", recall_avg)
# print("F1 Score:", f1)
# print("F1 Score (weighted):", fl_avg)
cm = confusion_matrix(y_test, y_pred)
# ConfusionMatrixDisplay(confusion_matrix=cm).plot()
fig, ax = plt.subplots(figsize=(8, 8))
ConfusionMatrixDisplay.from_predictions(
y_test, y_pred,
display_labels=display_labels,
xticks_rotation=45 if len(display_labels) > 2 else 0,
values_format='d',
cmap=plt.cm.Blues,
ax=ax
)
plt.xlabel('Predicted label', fontsize=15)
plt.ylabel('True label', fontsize=15)
plt.title(cm_title, fontsize=15)
plt.tight_layout()
# plt.show()
# plt.savefig(f"./svm/fig{count}.png")
evaluation = {
'accuracy': accuracy,
'precision': precision,
'precision_avg': precision_avg,
'recall': recall,
'recall_avg': recall_avg,
'f1': f1,
'fl_avg': fl_avg,
'cm': cm
}
# Fooling ratio
if return_fool_ratio:
evaluation['fool_ratio'] = np.array([sum(np.logical_and(y_pred == 0, y_test == attack_cat)) / (sum(y_test == attack_cat) + 1e-5)
for attack_cat in range(1, 10)])
evaluation['fool_ratio_avg'] = np.array(sum(np.logical_and(y_pred == 0, y_test != 0)) / len(y_test))
print("========================================================================")
print(evaluation['fool_ratio_avg'])
print(evaluation['fool_ratio'])
print("========================================================================")
return evaluation
# y_pred = best_svm.predict(X_test)
# print('Test evaluation:')
# evaluation_test = evaluate(y_test, y_pred, 'Testing set')
# data_correct = data_test[np.logical_and(y_test != 0, y_pred == y_test)]
# data_fool = data_test[np.logical_and(y_pred == 0, y_test != 0)]
# data_correct.to_csv(output_dir / f'rf_correct_{mode}.csv', index=False)
# data_fool.to_csv(output_dir / f'rf_fool_{mode}.csv', index=False)
# Fooling case analysis
# Split testing set
X_test1, X_test2, y_test1, y_test2 = train_test_split(X_test, y_test, train_size=0.5, random_state=1)
# Adversarial attack
# Label: fooled or not
X_test1_attack = X_test1[y_test1 != 0]
y_test1_attack = y_test1[y_test1 != 0]
y_pred1_attack = best_svm.predict(X_test1_attack)
y_fool1 = np.logical_and(y_pred1_attack == 0, y_test1_attack != 0)
# Training
if tuning_adv:
rand_search_adv, results_adv = hyperparameter_tuning(X_test1_attack, y_fool1)
results_adv.to_csv(output_dir / f'rf_results_adv_{mode}.csv')
best_svm_adv = rand_search_adv.best_estimator_
print('Best hyperparameters:', rand_search_adv.best_params_)
print('Best score:', rand_search_adv.best_score_)
else:
best_svm_adv = SVC(C=100, kernel="linear")
# RandomForestClassifier(n_estimators=38, max_depth=17, random_state=1, class_weight='balanced' if weighted else None)
best_svm_adv.fit(X_test1_attack, y_fool1)
joblib.dump(best_svm_adv, './svm/best_svm_adv.model')
def attack_efficiency(X_test1, y_test1, X_test2, y_test2, best_svm, tag='', count = 0):
# Model performance
y_pred1 = best_svm.predict(X_test1)
print('test1 evaluation:')
evaluation_test1 = evaluate(y_test1, y_pred1, f'Test1{tag}', count=1+count)
# Attack efficiency: model performance reduction
# Model performance before attack
# y_pred2 = best_svm.predict(X_test2)
# print('Evaluation before attack:')
# evaluation_test2 = evaluate(y_test2, y_pred2, f'Test2{tag}')
X_test2_attack = X_test2[y_test2 != 0]
y_test2_attack = y_test2[y_test2 != 0]
y_pred2_attack = best_svm.predict(X_test2_attack)
print('Evaluation before attack (attack only):')
evaluation_test2_attack = evaluate(y_test2_attack, y_pred2_attack, f'Test2{tag}', count = 2+count)
# Model performance after attack
# y_fool2_pred = best_svm_adv.predict(X_test2)
# X_test2_adv = X_test2[y_fool2_pred]
# y_test2_adv = y_test2[y_fool2_pred]
# y_pred2_adv = best_svm.predict(X_test2_adv)
# print('Evaluation after attack:')
# evaluation_test2_adv = evaluate(y_test2_adv, y_pred2_adv, f'Adversarial test2{tag}')
y_fool2_attack_pred = best_svm_adv.predict(X_test2_attack)
X_test2_attack_adv = X_test2_attack[y_fool2_attack_pred]
y_test2_attack_adv = y_test2_attack[y_fool2_attack_pred]
y_pred2_attack_adv = best_svm.predict(X_test2_attack_adv)
print('Evaluation after attack (attack only):')
evaluation_test2_adv_attack = evaluate(y_test2_attack_adv, y_pred2_attack_adv, f'Adversarial test2{tag}', count = 3+count)
# Fooling case prediction performance
# y_fool2 = np.logical_and(y_pred2 == 0, y_test2 != 0)
# print('Fooling case evaluation:')
# evaluation_fool2 = evaluate(y_fool2, y_fool2_pred, f'Fooling case{tag}', ['Not fool', 'Fool'], return_fool_ratio=False)
y_fool2_attack = np.logical_and(y_pred2_attack == 0, y_test2_attack != 0)
print('Fooling case evaluation (attack only):')
evaluation_fool2_attack = evaluate(y_fool2_attack, y_fool2_attack_pred, f'Fooling case{tag}', ['Not fool', 'Fool'], return_fool_ratio=False, count = 4+count)
evaluation = {
'evaluation_test1': evaluation_test1,
# 'evaluation_test2': evaluation_test2,
'evaluation_test2_attack': evaluation_test2_attack,
# 'evaluation_test2_adv': evaluation_test2_adv,
'evaluation_test2_adv_attack': evaluation_test2_adv_attack,
# 'evaluation_fool2': evaluation_fool2,
'evaluation_fool2_attack': evaluation_fool2_attack
}
return evaluation
print('Attack without retraining:')
evaluation_attack = attack_efficiency(X_test1, y_test1, X_test2, y_test2, best_svm, count = 0)
# Model retraining
X_retrain = pd.concat([X_train, X_test1], ignore_index=True)
y_retrain = pd.concat([y_train, y_test1], ignore_index=True)
if tuning_retrain:
rand_search_retrain, results_retrain = hyperparameter_tuning(X_retrain, y_retrain)
results_retrain.to_csv(output_dir / f'rf_results_retrain_{mode}.csv')
best_svm_retrain = rand_search_retrain.best_estimator_
print('Best hyperparameters:', rand_search_retrain.best_params_)
print('Best score:', rand_search_retrain.best_score_)
else:
best_svm_retrain = SVC(C=100, kernel="linear")
# RandomForestClassifier(n_estimators=38, max_depth=17, random_state=1, class_weight='balanced' if weighted else None)
best_svm_retrain.fit(X_retrain, y_retrain)
joblib.dump(best_svm_retrain, './svm/best_svm_retrain.model')
print('Attack with retraining:')
evaluation_attack_retrain = attack_efficiency(X_test1, y_test1, X_test2, y_test2, best_svm_retrain, tag=' after retraining', count = 4)