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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
Created on Fri Mar 15 14:57:46 2019
|
| 5 |
+
|
| 6 |
+
@author: atavci
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
import seaborn as sns
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
|
| 15 |
+
from sklearn.model_selection import train_test_split
|
| 16 |
+
from sklearn.metrics import confusion_matrix, classification_report
|
| 17 |
+
from sklearn.metrics import roc_curve, auc
|
| 18 |
+
|
| 19 |
+
import xgboost as xgb
|
| 20 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 21 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 22 |
+
from sklearn.ensemble import VotingClassifier
|
| 23 |
+
|
| 24 |
+
# set seaborn style because it prettier
|
| 25 |
+
sns.set()
|
| 26 |
+
# %% read and plot
|
| 27 |
+
data = pd.read_csv("Data/synthetic-data-from-a-financial-payment-system/bs140513_032310.csv")
|
| 28 |
+
|
| 29 |
+
data.head(5)
|
| 30 |
+
|
| 31 |
+
# Create two dataframes with fraud and non-fraud data
|
| 32 |
+
df_fraud = data.loc[data.fraud == 1]
|
| 33 |
+
df_non_fraud = data.loc[data.fraud == 0]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
sns.countplot(x="fraud",data=data)
|
| 37 |
+
plt.title("Count of Fraudulent Payments")
|
| 38 |
+
plt.legend()
|
| 39 |
+
plt.show()
|
| 40 |
+
print("Number of normal examples: ",df_non_fraud.fraud.count())
|
| 41 |
+
print("Number of fradulent examples: ",df_fraud.fraud.count())
|
| 42 |
+
#print(data.fraud.value_counts()) # does the same thing above
|
| 43 |
+
|
| 44 |
+
print("Mean feature values per category",data.groupby('category')['amount','fraud'].mean())
|
| 45 |
+
|
| 46 |
+
print("Columns: ", data.columns)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# Plot histograms of the amounts in fraud and non-fraud data
|
| 51 |
+
plt.hist(df_fraud.amount, alpha=0.5, label='fraud',bins=100)
|
| 52 |
+
plt.hist(df_non_fraud.amount, alpha=0.5, label='nonfraud',bins=100)
|
| 53 |
+
plt.title("Histogram for fraud and nonfraud payments")
|
| 54 |
+
plt.ylim(0,10000)
|
| 55 |
+
plt.xlim(0,1000)
|
| 56 |
+
plt.legend()
|
| 57 |
+
plt.show()
|
| 58 |
+
|
| 59 |
+
# %% Preprocessing
|
| 60 |
+
print(data.zipcodeOri.nunique())
|
| 61 |
+
print(data.zipMerchant.nunique())
|
| 62 |
+
|
| 63 |
+
# dropping zipcodeori and zipMerchant since they have only one unique value
|
| 64 |
+
data_reduced = data.drop(['zipcodeOri','zipMerchant'],axis=1)
|
| 65 |
+
|
| 66 |
+
data_reduced.columns
|
| 67 |
+
|
| 68 |
+
# turning object columns type to categorical for later purposes
|
| 69 |
+
col_categorical = data_reduced.select_dtypes(include= ['object']).columns
|
| 70 |
+
for col in col_categorical:
|
| 71 |
+
data_reduced[col] = data_reduced[col].astype('category')
|
| 72 |
+
|
| 73 |
+
# it's usually better to turn the categorical values (customer, merchant, and category variables )
|
| 74 |
+
# into dummies because they have no relation in size(i.e. 5>4) but since they are too many (over 500k) the features will grow too many and
|
| 75 |
+
# it will take forever to train but here is the code below for turning categorical features into dummies
|
| 76 |
+
#data_reduced.loc[:,['customer','merchant','category']].astype('category')
|
| 77 |
+
#data_dum = pd.get_dummies(data_reduced.loc[:,['customer','merchant','category','gender']],drop_first=True) # dummies
|
| 78 |
+
#print(data_dum.info())
|
| 79 |
+
|
| 80 |
+
# categorical values ==> numeric values
|
| 81 |
+
data_reduced[col_categorical] = data_reduced[col_categorical].apply(lambda x: x.cat.codes)
|
| 82 |
+
|
| 83 |
+
# define X and y
|
| 84 |
+
X = data_reduced.drop(['fraud'],axis=1)
|
| 85 |
+
y = data['fraud']
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# I won't do cross validation since we have a lot of instances
|
| 89 |
+
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=42,shuffle=True,stratify=y)
|
| 90 |
+
|
| 91 |
+
# %% Function for plotting ROC_AUC curve
|
| 92 |
+
|
| 93 |
+
def plot_roc_auc(y_test, preds):
|
| 94 |
+
'''
|
| 95 |
+
Takes actual and predicted(probabilities) as input and plots the Receiver
|
| 96 |
+
Operating Characteristic (ROC) curve
|
| 97 |
+
'''
|
| 98 |
+
fpr, tpr, threshold = roc_curve(y_test, preds)
|
| 99 |
+
roc_auc = auc(fpr, tpr)
|
| 100 |
+
plt.title('Receiver Operating Characteristic')
|
| 101 |
+
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
|
| 102 |
+
plt.legend(loc = 'lower right')
|
| 103 |
+
plt.plot([0, 1], [0, 1],'r--')
|
| 104 |
+
plt.xlim([0, 1])
|
| 105 |
+
plt.ylim([0, 1])
|
| 106 |
+
plt.ylabel('True Positive Rate')
|
| 107 |
+
plt.xlabel('False Positive Rate')
|
| 108 |
+
plt.show()
|
| 109 |
+
|
| 110 |
+
# The base score should be better than predicting always non-fraduelent
|
| 111 |
+
print("Base score we must beat is: ",
|
| 112 |
+
df_non_fraud.fraud.count()/ np.add(df_non_fraud.fraud.count(),df_fraud.fraud.count()) * 100)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# %% K-ello Neigbors
|
| 116 |
+
|
| 117 |
+
knn = KNeighborsClassifier(n_neighbors=5,p=1)
|
| 118 |
+
|
| 119 |
+
knn.fit(X_train,y_train)
|
| 120 |
+
y_pred = knn.predict(X_test)
|
| 121 |
+
|
| 122 |
+
# High precision on fraudulent examples almost perfect score on non-fraudulent examples
|
| 123 |
+
print("Classification Report for K-Nearest Neighbours: \n", classification_report(y_test, y_pred))
|
| 124 |
+
print("Confusion Matrix of K-Nearest Neigbours: \n", confusion_matrix(y_test,y_pred))
|
| 125 |
+
plot_roc_auc(y_test, knn.predict_proba(X_test)[:,1])
|
| 126 |
+
|
| 127 |
+
# %% Random Forest Classifier
|
| 128 |
+
|
| 129 |
+
rf_clf = RandomForestClassifier(n_estimators=100,max_depth=8,random_state=42,
|
| 130 |
+
verbose=1,class_weight="balanced")
|
| 131 |
+
|
| 132 |
+
rf_clf.fit(X_train,y_train)
|
| 133 |
+
y_pred = rf_clf.predict(X_test)
|
| 134 |
+
|
| 135 |
+
# 98 % recall on fraudulent examples but low 24 % precision.
|
| 136 |
+
print("Classification Report for Random Forest Classifier: \n", classification_report(y_test, y_pred))
|
| 137 |
+
print("Confusion Matrix of Random Forest Classifier: \n", confusion_matrix(y_test,y_pred))
|
| 138 |
+
plot_roc_auc(y_test, rf_clf.predict_proba(X_test)[:,1])
|
| 139 |
+
|
| 140 |
+
# %% XG-Boost
|
| 141 |
+
XGBoost_CLF = xgb.XGBClassifier(max_depth=6, learning_rate=0.05, n_estimators=400,
|
| 142 |
+
objective="binary:hinge", booster='gbtree',
|
| 143 |
+
n_jobs=-1, nthread=None, gamma=0, min_child_weight=1, max_delta_step=0,
|
| 144 |
+
subsample=1, colsample_bytree=1, colsample_bylevel=1, reg_alpha=0, reg_lambda=1,
|
| 145 |
+
scale_pos_weight=1, base_score=0.5, random_state=42, verbosity=True)
|
| 146 |
+
|
| 147 |
+
XGBoost_CLF.fit(X_train,y_train)
|
| 148 |
+
|
| 149 |
+
y_pred = XGBoost_CLF.predict(X_test)
|
| 150 |
+
|
| 151 |
+
# reatively high precision and recall for fraudulent class
|
| 152 |
+
print("Classification Report for XGBoost: \n", classification_report(y_test, y_pred)) # Accuracy for XGBoost: 0.9963059088641371
|
| 153 |
+
print("Confusion Matrix of XGBoost: \n", confusion_matrix(y_test,y_pred))
|
| 154 |
+
plot_roc_auc(y_test, XGBoost_CLF.predict_proba(X_test)[:,1])
|
| 155 |
+
|
| 156 |
+
# %% Ensemble
|
| 157 |
+
|
| 158 |
+
estimators = [("KNN",knn),("rf",rf_clf),("xgb",XGBoost_CLF)]
|
| 159 |
+
ens = VotingClassifier(estimators=estimators, voting="soft",weights=[1,4,1])
|
| 160 |
+
|
| 161 |
+
ens.fit(X_train,y_train)
|
| 162 |
+
y_pred = ens.predict(X_test)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# Combined Random Forest model's recall and other models' precision thus this model
|
| 166 |
+
# ensures a higher recall with less false alarms (false positives)
|
| 167 |
+
print("Classification Report for Ensembled Models: \n", classification_report(y_test, y_pred)) # Accuracy for XGBoost: 0.9963059088641371
|
| 168 |
+
print("Confusion Matrix of Ensembled Models: \n", confusion_matrix(y_test,y_pred))
|
| 169 |
+
plot_roc_auc(y_test, ens.predict_proba(X_test)[:,1])
|