實(shí)戰(zhàn)項(xiàng)目:基于機(jī)器學(xué)習(xí)的 Python 信用卡欺詐檢測(cè)!
當(dāng)我們?cè)诰W(wǎng)上購(gòu)買(mǎi)產(chǎn)品時(shí),很多人喜歡使用信用卡,但信用卡欺詐常常會(huì)在身邊發(fā)生,網(wǎng)絡(luò)安全正成為我們生活中至關(guān)重要的一部分。
為了解決這個(gè)問(wèn)題,我們需要利用機(jī)器學(xué)習(xí)算法構(gòu)建一個(gè)異常行為的識(shí)別系統(tǒng),如果發(fā)現(xiàn)可疑,中止操作。
在本文中,我將分享一個(gè)端到端模型訓(xùn)練方法,從數(shù)據(jù)獲取方向到最后模型篩選對(duì)比,喜歡的小伙伴歡迎關(guān)注、點(diǎn)贊支持我。
關(guān)于數(shù)據(jù)
本文使用的為 kaggle 數(shù)據(jù):https://www.kaggle.com/mlg-ulb/creditcardfraud,該數(shù)據(jù)集為 2013 年歐洲持卡人的真實(shí)銀行交易。出于安全考慮,該數(shù)據(jù)已轉(zhuǎn)換為 PCA 版本,有 29 個(gè)特征列和 1 個(gè)類列。
導(dǎo)入必要的庫(kù)
在這里我將導(dǎo)入所有必要的庫(kù)。由于信用卡數(shù)據(jù)特征是 PCA 的轉(zhuǎn)換版本,因此我們不需要再次執(zhí)行特征選擇。否則,建議使用 RFE、RFECV、SelectKBest 和 VIF score 來(lái)查找適合模型的特征。
#Packages related to general operating system & warnings
import os
import warnings
warnings.filterwarnings('ignore')
#Packages related to data importing, manipulation, exploratory data #analysis, data understanding
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from termcolor import colored as cl # text customization
#Packages related to data visualizaiton
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
#Setting plot sizes and type of plot
plt.rc("font", size=14)
plt.rcParams['axes.grid'] = True
plt.figure(figsize=(6,3))
plt.gray()
from matplotlib.backends.backend_pdf import PdfPages
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn import metrics
from sklearn.impute import MissingIndicator, SimpleImputer
from sklearn.preprocessing import PolynomialFeatures, KBinsDiscretizer, FunctionTransformer
from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, LabelBinarizer, OrdinalEncoder
import statsmodels.formula.api as smf
import statsmodels.tsa as tsa
from sklearn.linear_model import LogisticRegression, LinearRegression, ElasticNet, Lasso, Ridge
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, export_graphviz, export
from sklearn.ensemble import BaggingClassifier, BaggingRegressor,RandomForestClassifier,RandomForestRegressor
from sklearn.ensemble import GradientBoostingClassifier,GradientBoostingRegressor, AdaBoostClassifier, AdaBoostRegressor
from sklearn.svm import LinearSVC, LinearSVR, SVC, SVR
from xgboost import XGBClassifier
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
導(dǎo)入數(shù)據(jù)集
導(dǎo)入數(shù)據(jù)集非常簡(jiǎn)單。你只需使用 python 中的 pandas 模塊導(dǎo)入它,運(yùn)行如下命令,「數(shù)據(jù)集可文末下載」。
data=pd.read_csv("creditcard.csv")
數(shù)據(jù)處理與理解
關(guān)于這些數(shù)據(jù),你可能會(huì)注意到一個(gè)問(wèn)題,數(shù)據(jù)集是不平衡的,因?yàn)閿?shù)據(jù)集中正常交易占絕大多數(shù),只有少數(shù)百分比的交易是欺詐的。
讓我們檢查一下數(shù)據(jù)分布。
Total_transactions = len(data)
normal = len(data[data.Class == 0])
fraudulent = len(data[data.Class == 1])
fraud_percentage = round(fraudulent/normal*100, 2)
print(cl('Total number of Trnsactions are {}'.format(Total_transactions), attrs = ['bold']))
print(cl('Number of Normal Transactions are {}'.format(normal), attrs = ['bold']))
print(cl('Number of fraudulent Transactions are {}'.format(fraudulent), attrs = ['bold']))
print(cl('Percentage of fraud Transactions is {}'.format(fraud_percentage), attrs = ['bold']))

我們還可以使用以下代碼檢查空值。
data.info()

根據(jù)每列的計(jì)數(shù),我們沒(méi)有空值。此外,可以嘗試應(yīng)用特征選擇方法來(lái)檢查結(jié)果是否得到優(yōu)化。
我在數(shù)據(jù)中觀察到 28 個(gè)特征是 PCA 的轉(zhuǎn)換版本,但字段"Amount "是原始的。在檢查最小值和最大值時(shí),我發(fā)現(xiàn)差異很大,可能會(huì)偏離我們的結(jié)果。
在這種情況下,我按照如下方法整理。
sc = StandardScaler()
amount = data['Amount'].values
data['Amount'] = sc.fit_transform(amount.reshape(-1, 1))
我們還有一個(gè)變量,即 time,它可能是一個(gè)外部決定因素,在我們的建模過(guò)程中,舍棄它。
我們還可以檢查任何重復(fù)數(shù)據(jù)。在刪除任何重復(fù)數(shù)據(jù)之前,數(shù)據(jù)集中有 284807 行。
去重
data.drop_duplicates(inplace=True)

因此,我們有大約9000筆重復(fù)交易。
訓(xùn)練與測(cè)試分離
在拆分訓(xùn)練和測(cè)試之前,我們需要定義因變量和自變量。因變量也稱為 X,自變量稱為 y。
X = data.drop('Class', axis = 1).values
y = data['Class'].values
現(xiàn)在,讓我們拆分訓(xùn)練和測(cè)試數(shù)據(jù)。
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 1)
就這樣,我們現(xiàn)在有兩個(gè)不同的數(shù)據(jù)集。
構(gòu)建模型
我們將嘗試不同的機(jī)器學(xué)習(xí)模型。定義模型要容易得多。一行代碼就可以定義我們的模型。同樣,一行代碼可以在我們的數(shù)據(jù)上擬合模型。我們也可以通過(guò)選擇不同的優(yōu)化參數(shù)來(lái)調(diào)整這些模型。
1)決策樹(shù)
DT = DecisionTreeClassifier(max_depth = 4, criterion = 'entropy')
DT.fit(X_train, y_train)
dt_yhat = DT.predict(X_test)
讓我們查看一下決策樹(shù)模型的準(zhǔn)確性。
print('Accuracy score of the Decision Tree model is {}'.format(accuracy_score(y_test, tree_yhat)))
Accuracy score of the Decision Tree model is 0.999288989494457
查看決策樹(shù)模型的F1分?jǐn)?shù)。
print('F1 score of the Decision Tree model is {}'.format(f1_score(y_test, tree_yhat)))
F1 score of the Decision Tree model is 0.776255707762557
查看混淆矩陣:
confusion_matrix(y_test, tree_yhat, labels = [0, 1])

2)隨機(jī)森林
rf = RandomForestClassifier(max_depth = 4)
rf.fit(X_train, y_train)
rf_yhat = rf.predict(X_test)
讓我們看一下隨機(jī)森林模型的準(zhǔn)確性。
print('Accuracy score of the Random Forest model is {}'.format(accuracy_score(y_test, rf_yhat)))
Accuracy score of the Random Forest model is 0.9993615415868594
查看隨機(jī)森林模型的F1分?jǐn)?shù)。
print('F1 score of the Random Forest model is {}'.format(f1_score(y_test, rf_yhat)))
F1 score of the Random Forest model is 0.7843137254901961
3)XGBoost
xgb = XGBClassifier(max_depth = 4)
xgb.fit(X_train, y_train)
xgb_yhat = xgb.predict(X_test)
讓我們看一下 XGBoost 模型的準(zhǔn)確性。
print('Accuracy score of the XGBoost model is {}'.format(accuracy_score(y_test, xgb_yhat)))
Accuracy score of the XGBoost model is 0.9995211561901445
查看 XGBoost 模型的F1分?jǐn)?shù)。
print('F1 score of the XGBoost model is {}'.format(f1_score(y_test, xgb_yhat)))
F1 score of the XGBoost model is 0.8421052631578947
結(jié)論
我們剛剛獲得了 99.95% 的信用卡欺詐檢測(cè)準(zhǔn)確率。這一數(shù)字并不令人驚訝,因?yàn)槲覀兊臄?shù)據(jù)是針對(duì)一個(gè)類別的。
根據(jù)我們的 F1-Score 得分,XGBoost 是我們案例的贏家。這里唯一需要注意的是我們用于模型訓(xùn)練的數(shù)據(jù)。數(shù)據(jù)特征是PCA的變換版本。
福利時(shí)間
近日吳恩達(dá)新書(shū)《Machine Learning Yearning》中文版開(kāi)放下載!

《Machine Learning Yearning》是吳恩達(dá)歷時(shí)兩年,根據(jù)自己多年實(shí)踐經(jīng)驗(yàn)整理出來(lái)的一本機(jī)器學(xué)習(xí)、深度學(xué)習(xí)實(shí)踐經(jīng)驗(yàn)寶典。里面講的機(jī)器學(xué)習(xí)課程非常棒,很適合數(shù)學(xué)基礎(chǔ)不是很好的人自學(xué),最近中文版也開(kāi)放下載閱讀了!
如何下載?
1. 識(shí)別并關(guān)注下方公眾號(hào);
2. 在下面公眾號(hào)(非本號(hào))后臺(tái)回復(fù)關(guān)鍵字「吳恩達(dá)」。
