-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
executable file
·364 lines (288 loc) · 12.2 KB
/
test.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
import numpy as np
import pandas as pd
import csv
import sys
import os
from sys import platform as sys_pf
if sys_pf == 'darwin':
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support as score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_curve
from sklearn.utils.fixes import signature
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.svm import SVC
from sklearn.ensemble import BaggingClassifier
import warnings
import pickle
transfer_weights = [70,39,16]
cash_out_weights = [145,132,128]
lr_prc = [0]*2
svm_prc = [0]*2
kernel_svm_prc = [0]*2
def plot_pr_curve(filename,type = 'validation'):
from sklearn.metrics import f1_score
from sklearn.metrics import auc
from sklearn.metrics import average_precision_score
print('************* Precision Recall metrics on ' + type + ' data *************')
plt.clf()
# Logistic Regression
pre_lr , rec_lr, thresh_lr = precision_recall_curve(lr_prc[0], lr_prc[1],pos_label = 1)
area = auc(rec_lr, pre_lr)
area = round(area,4)
print('Logistic Regression - Area under PRC' , area)
plt.plot(rec_lr, pre_lr, linestyle='--' , color = 'r',label = 'Logistic Regression - AUPRC - ' + str(area))
# Linear SVM
pre_svm , rec_svm, thresh_svm = precision_recall_curve(svm_prc[0], svm_prc[1],pos_label = 1)
area = auc(rec_svm, pre_svm)
area = round(area,4)
print('Linear SVM - Area under PRC' , area)
plt.plot(rec_svm, pre_svm, linestyle='--' , color = 'b',label = 'Linear SVM - AUPRC - ' + str(area))
# RBF SVM
pre_kernel_svm , rec_kernel_svm, thresh_kernel_svm = precision_recall_curve(kernel_svm_prc[0], kernel_svm_prc[1],pos_label = 1 )
area = auc(rec_kernel_svm, pre_kernel_svm)
area = round(area,4)
print('RBF Precision ' , pre_kernel_svm)
print('RBF Recall ' , rec_kernel_svm)
print('SVM with RBF kernel - Area under PRC' , area)
plt.plot(rec_kernel_svm, pre_kernel_svm, linestyle='--' , color = 'g',label = 'SVM RBF kernel - AUPRC - ' + str(area))
if "transfer" in filename:
plt.title('TRANSFER - Precision-Recall curve')
elif "cash" in filename:
plt.title('CASH OUT - Precision-Recall curve')
# plot the precision recall curve for the model
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.legend()
# show the plot
plt.savefig('./test-results/'+filename)
print('*********************************************************************')
def print_confusion_matrix(cm,mode = 'validation' , dataset = 'Transfer', algo = 'lr'):
return
def lr_test(x,y,filename,mode = 'validation'):
# Stratified sampling based on Y
X_train, X_test, y_train, y_test = train_test_split(x, y,stratify=y , test_size=0.30, random_state=42)
# Create 15% validation set and 15% test set split
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test,stratify=y_test , test_size=0.50, random_state=42)
# Load trained model from saved models
dataset = ''
model_file = ''
if "transfer" in filename:
model_file = './models/lr_transfer/' + str(transfer_weights[0]) +'.sav'
dataset = 'Transfer'
if "cash_out" in filename:
model_file = './models/lr_cash_out/' + str(cash_out_weights[0]) +'.sav'
dataset = 'Cash Out'
lr = pickle.load(open(model_file, 'rb'))
print('Class weights ', lr.class_weight)
print('Feature importance ', lr.coef_)
# Predict on train data
if mode == 'train':
y_train_pred_prob = lr.decision_function(X_train)
lr_prc[0] = y_train
lr_prc[1] = y_train_pred_prob
y_train_pred = lr.predict(X_train)
print('Performance on train data - Confusion matrix')
cm = confusion_matrix(y_train,y_train_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset,'lr')
precision,recall,fscore,support=score(y_train,y_train_pred,average=None)
print('Precision, Recall, F-score, Support on Train data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
# Predict on validation data
if mode == 'validation':
y_val_pred_prob = lr.decision_function(X_val)
lr_prc[0] = y_val
lr_prc[1] = y_val_pred_prob
y_val_pred = lr.predict(X_val)
print('Performance on validation data - Confusion matrix')
cm = confusion_matrix(y_val,y_val_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset,'lr')
precision,recall,fscore,support=score(y_val,y_val_pred,average=None)
print('Precision, Recall, F-score, Support on validation data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
# Predict on test data
if mode == 'test':
y_test_pred_prob = lr.decision_function(X_test)
lr_prc[0] = y_test
lr_prc[1] = y_test_pred_prob
y_test_pred = lr.predict(X_test)
print('Performance on test data - Confusion matrix')
cm = confusion_matrix(y_test,y_test_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset)
precision,recall,fscore,support=score(y_test,y_test_pred,average=None)
print('Precision, Recall, F-score, Support on test data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
def svm_test(x,y,filename,mode = 'validation'):
# Stratified sampling based on Y
X_train, X_test, y_train, y_test = train_test_split(x, y,stratify=y , test_size=0.30, random_state=42)
# Create 15% validation set and 15% test set split
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test,stratify=y_test , test_size=0.50, random_state=42)
# Load trained model from saved models
dataset = ''
model_file = ''
if "transfer" in filename:
model_file = './models/svm_transfer/' + str(transfer_weights[1]) +'.sav'
dataset = 'Transfer'
if "cash_out" in filename:
model_file = './models/svm_cash_out/' + str(cash_out_weights[1]) +'.sav'
dataset = 'Cash Out'
svm = pickle.load(open(model_file, 'rb'))
print('Class weights ', svm.class_weight)
print('Feature importance ', svm.coef_)
# Predict on train data
if mode == 'train':
y_train_pred_prob = svm.decision_function(X_train)
svm_prc[0] = y_train
svm_prc[1] = y_train_pred_prob
y_train_pred = svm.predict(X_train)
print('Performance on train data - Confusion matrix')
cm = confusion_matrix(y_train,y_train_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset,'svm')
precision,recall,fscore,support=score(y_train,y_train_pred,average=None)
print('Precision, Recall, F-score, Support on Train data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
# Predict on validation data
if mode == 'validation':
y_val_pred_prob = svm.decision_function(X_val)
svm_prc[0] = y_val
svm_prc[1] = y_val_pred_prob
y_val_pred = svm.predict(X_val)
print('Performance on validation data - Confusion matrix')
cm = confusion_matrix(y_val,y_val_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset,'svm')
precision,recall,fscore,support=score(y_val,y_val_pred,average=None)
print('Precision, Recall, F-score, Support on validation data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
# Predict on test data
if mode == 'test':
y_test_pred_prob = svm.decision_function(X_test)
svm_prc[0] = y_test
svm_prc[1] = y_test_pred_prob
y_test_pred = svm.predict(X_test)
print('Performance on test data - Confusion matrix')
cm = confusion_matrix(y_test,y_test_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset)
precision,recall,fscore,support=score(y_test,y_test_pred,average=None)
print('Precision, Recall, F-score, Support on test data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
def kernel_svm_test(x,y,filename,mode = 'validation'):
# Stratified sampling based on Y
X_train, X_test, y_train, y_test = train_test_split(x, y,stratify=y , test_size=0.30, random_state=42)
# Create 15% validation set and 15% test set split
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test,stratify=y_test , test_size=0.50, random_state=42)
# Load trained model from saved models
dataset = ''
model_file = ''
if "transfer" in filename:
model_file = './models/kernel_svm_transfer/' + str(transfer_weights[2]) +'.sav'
dataset = 'Transfer'
if "cash_out" in filename:
model_file = './models/kernel_svm_cash_out/' + str(cash_out_weights[2]) +'.sav'
dataset = 'Cash Out'
svm = pickle.load(open(model_file, 'rb'))
print('Class weights ', svm.class_weight)
# Predict on train data
if mode == 'train':
y_train_pred_prob = svm.decision_function(X_train)
kernel_svm_prc[0] = y_train
kernel_svm_prc[1] = y_train_pred_prob
y_train_pred = svm.predict(X_train)
print('Performance on train data - Confusion matrix')
cm = confusion_matrix(y_train,y_train_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset,'kernel_svm')
precision,recall,fscore,support=score(y_train,y_train_pred,average=None)
print('Precision, Recall, F-score, Support on Train data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
# Predict on validation data
if mode == 'validation':
y_val_pred_prob = svm.decision_function(X_val)
kernel_svm_prc[0] = y_val
kernel_svm_prc[1] = y_val_pred_prob
y_val_pred = svm.predict(X_val)
print('Performance on validation data - Confusion matrix')
cm = confusion_matrix(y_val,y_val_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset,'kernel_svm')
precision,recall,fscore,support=score(y_val,y_val_pred,average=None)
print('Precision, Recall, F-score, Support on validation data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
# Predict on test data
if mode == 'test':
y_test_pred_prob = svm.decision_function(X_test)
kernel_svm_prc[0] = y_test
kernel_svm_prc[1] = y_test_pred_prob
y_test_pred = svm.predict(X_test)
print('Performance on test data - Confusion matrix')
cm = confusion_matrix(y_test,y_test_pred)
print(cm)
print_confusion_matrix(cm,mode,dataset)
precision,recall,fscore,support=score(y_test,y_test_pred,average=None)
print('Precision, Recall, F-score, Support on test data' )
print("Precision" , precision)
print("Recall" , recall)
print("F-score" , fscore)
print("Support" , support)
def run():
filename = sys.argv[1]
df = pd.read_csv(filename, usecols = [2,4,5,7,8,9] , header = 0,
names = ['Amount','Source-OB','Source-NB','Dest-OB','Dest-NB','target'])
results = list(map(int, df['target']))
print('Number of fraudulent transactions ' , sum(results))
features = ['Amount', 'Source-OB', 'Source-NB', 'Dest-OB' , 'Dest-NB']
targets = ['target']
# Separating out the features and target variables
x = df.loc[:, features].values
y = df.loc[:, targets].values
y = [i for j in y for i in j]
#Ignore warnings
warnings.filterwarnings("ignore", category=FutureWarning)
mode = sys.argv[2]
print("**************** Logistic Regression Test *******************")
lr_test(x,y,filename,mode)
print("**************** SVM Test *******************")
svm_test(x,y,filename,mode)
print("**************** Kernel SVM Test *******************")
kernel_svm_test(x,y,filename,mode)
if "transfer" in filename:
plot_pr_curve('transfer'+'_'+mode+'.png' , mode)
elif "cash" in filename:
plot_pr_curve('cash_out'+'_'+mode+'.png' , mode)
run()