您好,登錄后才能下訂單哦!
這篇文章主要介紹“怎么用Python分析信用卡反欺詐”,在日常操作中,相信很多人在怎么用Python分析信用卡反欺詐問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么用Python分析信用卡反欺詐”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
數(shù)據(jù)來源及項(xiàng)目概況
數(shù)據(jù)集包含歐洲持卡人于2013年9月通過信用卡進(jìn)行的交易。該數(shù)據(jù)集提供兩天內(nèi)發(fā)生的交易,其中在284,807筆交易中有492起欺詐行為。
數(shù)據(jù)集非常不平衡,負(fù)面類別(欺詐)占所有交易的0.172%。
它只包含數(shù)值輸入變量,這是PCA變換的結(jié)果。不幸的是,由于保密問題,我們無法提供有關(guān)數(shù)據(jù)的原始特征和更多背景信息。特征V1,V2,... V28是用PCA獲得的主要組件,唯一沒有用PCA轉(zhuǎn)換的特征是'Time'和'Amount'。
“時(shí)間”包含每個(gè)事務(wù)與數(shù)據(jù)集中第一個(gè)事務(wù)之間經(jīng)過的秒數(shù)。
'金額'是交易金額,該特征可以用于依賴于例子的成本敏感性學(xué)習(xí)。
“Class”是響應(yīng)變量,在欺詐的情況下其值為1,否則為0。
2、準(zhǔn)備并初步查看數(shù)據(jù)集
# 導(dǎo)入包 import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import seaborn as sns; plt.style.use('ggplot') import sklearn from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.utils import shuffle from sklearn.metrics import confusion_matrix from sklearn.manifold import TSNE pass # 倒入并查看數(shù)據(jù) crecreditcard_data=pd.read_csv('./creditcard.csv') crecreditcard_data.shape,crecreditcard_data.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 284807 entries, 0 to 284806 Data columns (total 31 columns): Time 284807 non-null float64 V1 284807 non-null float64 V2 284807 non-null float64 V3 284807 non-null float64 V4 284807 non-null float64 V5 284807 non-null float64 V6 284807 non-null float64 V7 284807 non-null float64 V8 284807 non-null float64 V9 284807 non-null float64 V10 284807 non-null float64 V11 284807 non-null float64 V12 284807 non-null float64 V13 284807 non-null float64 V14 284807 non-null float64 V15 284807 non-null float64 V16 284807 non-null float64 V17 284807 non-null float64 V18 284807 non-null float64 V19 284807 non-null float64 V20 284807 non-null float64 V21 284807 non-null float64 V22 284807 non-null float64 V23 284807 non-null float64 V24 284807 non-null float64 V25 284807 non-null float64 V26 284807 non-null float64 V27 284807 non-null float64 V28 284807 non-null float64 Amount 284807 non-null float64 Class 284807 non-null int64 dtypes: float64(30), int64(1) memory usage: 67.4 MB ((284807, 31), None) crecreditcard_data.describe() pass crecreditcard_data.head() pass # 看看欺詐與非欺詐的比例如何 count_classes=pd.value_counts(crecreditcard_data['Class'],sort=True).sort_index() # 統(tǒng)計(jì)下具體數(shù)據(jù) count_classes.value_counts() # 也可以用count_classes[0],count_classes[1]看分別數(shù)據(jù) 284315 1 492 1 Name: Class, dtype: int64 count_classes.plot(kind='bar') plt.show()
0代表正常,1代表欺詐,二者數(shù)量嚴(yán)重失衡,極度不平衡,根本不在一個(gè)數(shù)量級上。
3、欺詐與時(shí)間序列分布關(guān)系
# 查看二者的描述性統(tǒng)計(jì),與時(shí)間的序列分布關(guān)系 print('Normal') print(crecreditcard_data. Time[crecreditcard_data.Class == 0].describe()) print('-'*25) print('Fraud') print(crecreditcard_data. Time[crecreditcard_data.Class == 1].describe()) Normal count 284315.000000 mean 94838.202258 std 47484.015786 min 0.000000 25% 54230.000000 50% 84711.000000 75% 139333.000000 max 172792.000000 Name: Time, dtype: float64 ------------------------- Fraud count 492.000000 mean 80746.806911 std 47835.365138 min 406.000000 25% 41241.500000 50% 75568.500000 75% 128483.000000 max 170348.000000 Name: Time, dtype: float64 f,(ax1,ax2)=plt.subplots(2,1,sharex=True,figsize=(12,6)) bins=50 ax1.hist(crecreditcard_data.Time[crecreditcard_data.Class == 1],bins=bins) ax1.set_title('欺詐(Fraud))',fontsize=22) ax1.set_ylabel('交易量',fontsize=15) ax2.hist(crecreditcard_data.Time[crecreditcard_data.Class == 0],bins=bins) ax2.set_title('正常(Normal',fontsize=22) plt.xlabel('時(shí)間(單位:秒)',fontsize=15) plt.xticks(fontsize=15) plt.ylabel('交易量',fontsize=15) # plt.yticks(fontsize=22) plt.show()
欺詐與時(shí)間并沒有必然聯(lián)系,不存在周期性;
正常交易有明顯的周期性,有類似雙峰這樣的趨勢。
4、欺詐與金額的關(guān)系和分布情況
print('欺詐') print(crecreditcard_data.Amount[crecreditcard_data.Class ==1].describe()) print('-'*25) print('正常交易') print(crecreditcard_data.Amount[crecreditcard_data.Class==0].describe()) 欺詐 count 492.000000 mean 122.211321 std 256.683288 min 0.000000 25% 1.000000 50% 9.250000 75% 105.890000 max 2125.870000 Name: Amount, dtype: float64 ------------------------- 正常交易 count 284315.000000 mean 88.291022 std 250.105092 min 0.000000 25% 5.650000 50% 22.000000 75% 77.050000 max 25691.160000 Name: Amount, dtype: float64 f,(ax1,ax2)=plt.subplots(2,1,sharex=True,figsize=(12,6)) bins=30 ax1.hist(crecreditcard_data.Amount[crecreditcard_data.Class == 1],bins=bins) ax1.set_title('欺詐(Fraud)',fontsize=22) ax1.set_ylabel('交易量',fontsize=15) ax2.hist(crecreditcard_data.Amount[crecreditcard_data.Class == 0],bins=bins) ax2.set_title('正常(Normal)',fontsize=22) plt.xlabel('金額($)',fontsize=15) plt.xticks(fontsize=15) plt.ylabel('交易量',fontsize=15) plt.yscale('log') plt.show()
金額普遍較低,可見金額這一列的數(shù)據(jù)對分析的參考價(jià)值不大。
5、查看各個(gè)自變量(V1-V29)與因變量的關(guān)系
看看各個(gè)變量與正常、欺詐之間是否存在聯(lián)系,為了更直觀展示,通過distplot圖來逐個(gè)判斷,如下:
features=[x for x in crecreditcard_data.columns if x not in ['Time','Amount','Class']] plt.figure(figsize=(12,28*4)) gs =gridspec.GridSpec(28,1) import warnings warnings.filterwarnings('ignore') for i,cn in enumerate(crecreditcard_data[v_features]): ax=plt.subplot(gs[i]) sns.distplot(crecreditcard_data[cn][crecreditcard_data.Class==1],bins=50,color='red') sns.distplot(crecreditcard_data[cn][crecreditcard_data.Class==0],bins=50,color='green') ax.set_xlabel('') ax.set_title('直方圖:'+str(cn)) plt.savefig('各個(gè)變量與class的關(guān)系.png',transparent=False,bbox_inches='tight') plt.show()
紅色表示欺詐,綠色表示正常。
兩個(gè)分布的交叉面積越大,欺詐與正常的區(qū)分度最小,如V15;
兩個(gè)分布的交叉面積越小,則該變量對因變量的影響越大,如V14。
下面我們看看各個(gè)單變量與class的相關(guān)性分析,為更直觀展示,直接作圖,如下:
# 各個(gè)變量的矩陣分布 crecreditcard_data.hist(figsize=(15,15),bins=50) plt.show()
6、三種方法建模并分析
本部分將應(yīng)用邏輯回歸、隨機(jī)森林、支持向量SVM三種方法建模分析,分別展開如下:
準(zhǔn)備數(shù)據(jù):
# 先把數(shù)據(jù)分為欺詐組和正常組,然后按比例生產(chǎn)訓(xùn)練和測試數(shù)據(jù)集 # 分組 Fraud=crecreditcard_data[crecreditcard_data.Class == 1] Normal=crecreditcard_data[crecreditcard_data.Class == 0] # 訓(xùn)練特征集 x_train=Fraud.sample(frac=0.7) x_train=pd.concat([x_train,Normal.sample(frac=0.7)],axis=0) # 測試特征集 x_test=crecreditcard_data.loc[~crecreditcard_data.index.isin(x_train.index)] # 標(biāo)簽集 y_train=x_train.Class y_test=x_test.Class # 去掉特征集里的標(biāo)簽和時(shí)間列 x_train=x_train.drop(['Class','Time'],axis=1) x_test=x_test.drop(['Class','Time'],axis=1) # 查看數(shù)據(jù)結(jié)構(gòu) print(x_train.shape,y_train.shape, '\n',x_test.shape,y_test.shape) (199364, 29) (199364,) (85443, 29) (85443,)
6.1 邏輯回歸方法
from sklearn import metrics import scipy.optimize as op from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import KFold,cross_val_score from sklearn.metrics import (precision_recall_curve, auc,roc_auc_score, roc_curve,recall_score, classification_report) lrmodel = LogisticRegression(penalty='l2') lrmodel.fit(x_train, y_train) #查看模型 print('lrmodel') print(lrmodel) lrmodel LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False) #查看混淆矩陣 ypred_lr=lrmodel.predict(x_test) print('confusion_matrix') print(metrics.confusion_matrix(y_test,ypred_lr)) confusion_matrix [[85284 11] [ 56 92]] #查看分類報(bào)告 print('classification_report') print(metrics.classification_report(y_test,ypred_lr)) classification_report precision recall f1-score support 0 1.00 1.00 1.00 85295 1 0.89 0.62 0.73 148 avg / total 1.00 1.00 1.00 85443 #查看預(yù)測精度與決策覆蓋面 print('Accuracy:%f'%(metrics.accuracy_score(y_test,ypred_lr))) print('Area under the curve:%f'%(metrics.roc_auc_score(y_test,ypred_lr))) Accuracy:0.999216 Area under the curve:0.810746
6.2 隨機(jī)森林模型
from sklearn.ensemble import RandomForestClassifier rfmodel=RandomForestClassifier() rfmodel.fit(x_train,y_train) #查看模型 print('rfmodel') rfmodel rfmodel RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, oob_score=False, random_state=None, verbose=0, warm_start=False) #查看混淆矩陣 ypred_rf=rfmodel.predict(x_test) print('confusion_matrix') print(metrics.confusion_matrix(y_test,ypred_rf)) confusion_matrix [[85291 4] [ 34 114]] #查看分類報(bào)告 print('classification_report') print(metrics.classification_report(y_test,ypred_rf)) classification_report precision recall f1-score support 0 1.00 1.00 1.00 85295 1 0.97 0.77 0.86 148 avg / total 1.00 1.00 1.00 85443 #查看預(yù)測精度與決策覆蓋面 print('Accuracy:%f'%(metrics.accuracy_score(y_test,ypred_rf))) print('Area under the curve:%f'%(metrics.roc_auc_score(y_test,ypred_rf))) Accuracy:0.999625 Area under the curve:0.902009
6.3支持向量機(jī)SVM
# SVM分類 from sklearn.svm import SVC svcmodel=SVC(kernel='sigmoid') svcmodel.fit(x_train,y_train) #查看模型 print('svcmodel') svcmodel SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='auto', kernel='sigmoid', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False) #查看混淆矩陣 ypred_svc=svcmodel.predict(x_test) print('confusion_matrix') print(metrics.confusion_matrix(y_test,ypred_svc)) confusion_matrix [[85197 98] [ 142 6]] #查看分類報(bào)告 print('classification_report') print(metrics.classification_report(y_test,ypred_svc)) classification_report precision recall f1-score support 0 1.00 1.00 1.00 85295 1 0.06 0.04 0.05 148 avg / total 1.00 1.00 1.00 85443 #查看預(yù)測精度與決策覆蓋面 print('Accuracy:%f'%(metrics.accuracy_score(y_test,ypred_svc))) print('Area under the curve:%f'%(metrics.roc_auc_score(y_test,ypred_svc))) Accuracy:0.997191 Area under the curve:0.519696
到此,關(guān)于“怎么用Python分析信用卡反欺詐”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。