自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python分析信用卡反欺詐!騙我程序員,不存在的

開發(fā) 后端 大數(shù)據(jù)
本文試著從數(shù)據(jù)分析師的角度,設(shè)想“拿到數(shù)據(jù)該如何尋找規(guī)律、選哪種模型來構(gòu)建反欺詐模型?”的角度來分析,以業(yè)務(wù)導(dǎo)向為主,不深究算法原理;

前言:

本文研究的是大數(shù)據(jù)量(284807條數(shù)據(jù))下模型選擇的問題,也參考了一些文獻,但大多不夠清晰,因此吐血整理本文,希望對大家有幫助;

本文試著從數(shù)據(jù)分析師的角度,設(shè)想“拿到數(shù)據(jù)該如何尋找規(guī)律、選哪種模型來構(gòu)建反欺詐模型?”的角度來分析,以業(yè)務(wù)導(dǎo)向為主,不深究算法原理;

下一篇文章會說明數(shù)據(jù)結(jié)構(gòu)極度不平衡的情況下,該如何修正數(shù)據(jù)集、如何調(diào)整參數(shù)。

數(shù)據(jù)來源及項目概況

數(shù)據(jù)是從kaggle上看到的項目,具體鏈接如下:

https://www.kaggle.com/mlg-ulb/creditcardfraud

獲取本例數(shù)據(jù)的,可在上述項目詳情鏈接中下載數(shù)據(jù)。

數(shù)據(jù)集包含歐洲持卡人于2013年9月通過信用卡進行的交易。該數(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'。

  • “時間”包含每個事務(wù)與數(shù)據(jù)集中第一個事務(wù)之間經(jīng)過的秒數(shù)。
  • '金額'是交易金額,該特征可以用于依賴于例子的成本敏感性學(xué)習(xí)。
  • “Class”是響應(yīng)變量,在欺詐的情況下其值為1,否則為0。

2、準(zhǔn)備并初步查看數(shù)據(jù)集

  1. # 導(dǎo)入包 
  2. import numpy as np 
  3. import pandas as pd 
  4. import matplotlib.pyplot as plt 
  5. import matplotlib.gridspec as gridspec 
  6. import seaborn as sns; plt.style.use('ggplot'
  7. import sklearn 
  8. from sklearn.preprocessing import StandardScaler 
  9. from sklearn.model_selection import train_test_split 
  10. from sklearn.utils import shuffle 
  11. from sklearn.metrics import confusion_matrix 
  12. from sklearn.manifold import TSNE 
  13. pass 
  14. # 倒入并查看數(shù)據(jù) 
  15. crecreditcard_data=pd.read_csv('./creditcard.csv'
  16. crecreditcard_data.shape,crecreditcard_data.info() 
  17. <class 'pandas.core.frame.DataFrame'
  18. RangeIndex: 284807 entries, 0 to 284806 
  19. Data columns (total 31 columns): 
  20. Time 284807 non-null float64 
  21. V1 284807 non-null float64 
  22. V2 284807 non-null float64 
  23. V3 284807 non-null float64 
  24. V4 284807 non-null float64 
  25. V5 284807 non-null float64 
  26. V6 284807 non-null float64 
  27. V7 284807 non-null float64 
  28. V8 284807 non-null float64 
  29. V9 284807 non-null float64 
  30. V10 284807 non-null float64 
  31. V11 284807 non-null float64 
  32. V12 284807 non-null float64 
  33. V13 284807 non-null float64 
  34. V14 284807 non-null float64 
  35. V15 284807 non-null float64 
  36. V16 284807 non-null float64 
  37. V17 284807 non-null float64 
  38. V18 284807 non-null float64 
  39. V19 284807 non-null float64 
  40. V20 284807 non-null float64 
  41. V21 284807 non-null float64 
  42. V22 284807 non-null float64 
  43. V23 284807 non-null float64 
  44. V24 284807 non-null float64 
  45. V25 284807 non-null float64 
  46. V26 284807 non-null float64 
  47. V27 284807 non-null float64 
  48. V28 284807 non-null float64 
  49. Amount 284807 non-null float64 
  50. Class 284807 non-null int64 
  51. dtypes: float64(30), int64(1) 
  52. memory usage: 67.4 MB 
  53. ((284807, 31), None) 
  54. crecreditcard_data.describe() 
  55. pass 
  56. crecreditcard_data.head() 
  57. pass 
  58. # 看看欺詐與非欺詐的比例如何 
  59. count_classes=pd.value_counts(crecreditcard_data['Class'],sort=True).sort_index() 
  60. # 統(tǒng)計下具體數(shù)據(jù) 
  61. count_classes.value_counts() 
  62. # 也可以用count_classes[0],count_classes[1]看分別數(shù)據(jù) 
  63. 284315 1 
  64. 492 1 
  65. Name: Class, dtype: int64 
  66. count_classes.plot(kind='bar'
  67. plt.show() 

 Python分析信用卡反欺詐!騙我程序員,不存在的

0代表正常,1代表欺詐,二者數(shù)量嚴(yán)重失衡,極度不平衡,根本不在一個數(shù)量級上。

3、欺詐與時間序列分布關(guān)系

  1. # 查看二者的描述性統(tǒng)計,與時間的序列分布關(guān)系 
  2. print('Normal'
  3. print(crecreditcard_data. 
  4.  Time[crecreditcard_data.Class == 0].describe()) 
  5. print('-'*25) 
  6. print('Fraud'
  7. print(crecreditcard_data. 
  8.  Time[crecreditcard_data.Class == 1].describe()) 
  9. Normal 
  10. count 284315.000000 
  11. mean 94838.202258 
  12. std 47484.015786 
  13. min 0.000000 
  14. 25% 54230.000000 
  15. 50% 84711.000000 
  16. 75% 139333.000000 
  17. max 172792.000000 
  18. NameTime, dtype: float64 
  19. ------------------------- 
  20. Fraud 
  21. count 492.000000 
  22. mean 80746.806911 
  23. std 47835.365138 
  24. min 406.000000 
  25. 25% 41241.500000 
  26. 50% 75568.500000 
  27. 75% 128483.000000 
  28. max 170348.000000 
  29. NameTime, dtype: float64 
  30. f,(ax1,ax2)=plt.subplots(2,1,sharex=True,figsize=(12,6)) 
  31. bins=50 
  32. ax1.hist(crecreditcard_data.Time[crecreditcard_data.Class == 1],bins=bins) 
  33. ax1.set_title('欺詐(Fraud))',fontsize=22) 
  34. ax1.set_ylabel('交易量',fontsize=15) 
  35. ax2.hist(crecreditcard_data.Time[crecreditcard_data.Class == 0],bins=bins) 
  36. ax2.set_title('正常(Normal',fontsize=22) 
  37. plt.xlabel('時間(單位:秒)',fontsize=15) 
  38. plt.xticks(fontsize=15) 
  39. plt.ylabel('交易量',fontsize=15) 
  40. # plt.yticks(fontsize=22) 
  41. plt.show() 

 Python分析信用卡反欺詐!騙我程序員,不存在的

欺詐與時間并沒有必然聯(lián)系,不存在周期性;

正常交易有明顯的周期性,有類似雙峰這樣的趨勢。

4、欺詐與金額的關(guān)系和分布情況

  1. print('欺詐'
  2. print(crecreditcard_data.Amount[crecreditcard_data.Class ==1].describe()) 
  3. print('-'*25) 
  4. print('正常交易'
  5. print(crecreditcard_data.Amount[crecreditcard_data.Class==0].describe()) 
  6. 欺詐 
  7. count 492.000000 
  8. mean 122.211321 
  9. std 256.683288 
  10. min 0.000000 
  11. 25% 1.000000 
  12. 50% 9.250000 
  13. 75% 105.890000 
  14. max 2125.870000 
  15. Name: Amount, dtype: float64 
  16. ------------------------- 
  17. 正常交易 
  18. count 284315.000000 
  19. mean 88.291022 
  20. std 250.105092 
  21. min 0.000000 
  22. 25% 5.650000 
  23. 50% 22.000000 
  24. 75% 77.050000 
  25. max 25691.160000 
  26. Name: Amount, dtype: float64 
  27. f,(ax1,ax2)=plt.subplots(2,1,sharex=True,figsize=(12,6)) 
  28. bins=30 
  29. ax1.hist(crecreditcard_data.Amount[crecreditcard_data.Class == 1],bins=bins) 
  30. ax1.set_title('欺詐(Fraud)',fontsize=22) 
  31. ax1.set_ylabel('交易量',fontsize=15) 
  32. ax2.hist(crecreditcard_data.Amount[crecreditcard_data.Class == 0],bins=bins) 
  33. ax2.set_title('正常(Normal)',fontsize=22) 
  34. plt.xlabel('金額($)',fontsize=15) 
  35. plt.xticks(fontsize=15) 
  36. plt.ylabel('交易量',fontsize=15) 
  37. plt.yscale('log'
  38. plt.show() 

 Python分析信用卡反欺詐!騙我程序員,不存在的

金額普遍較低,可見金額這一列的數(shù)據(jù)對分析的參考價值不大。

5、查看各個自變量(V1-V29)與因變量的關(guān)系

看看各個變量與正常、欺詐之間是否存在聯(lián)系,為了更直觀展示,通過distplot圖來逐個判斷,如下:

  1. features=[x for x in crecreditcard_data.columns  
  2.  if x not in ['Time','Amount','Class']] 
  3. plt.figure(figsize=(12,28*4)) 
  4. gs =gridspec.GridSpec(28,1) 
  5. import warnings 
  6. warnings.filterwarnings('ignore'
  7. for i,cn in enumerate(crecreditcard_data[v_features]): 
  8.  ax=plt.subplot(gs[i]) 
  9.  sns.distplot(crecreditcard_data[cn][crecreditcard_data.Class==1],bins=50,color='red'
  10.  sns.distplot(crecreditcard_data[cn][crecreditcard_data.Class==0],bins=50,color='green'
  11.  ax.set_xlabel(''
  12.  ax.set_title('直方圖:'+str(cn)) 
  13. plt.savefig('各個變量與class的關(guān)系.png',transparent=False,bbox_inches='tight'
  14. plt.show() 

 Python分析信用卡反欺詐!騙我程序員,不存在的

紅色表示欺詐,綠色表示正常。

  • 兩個分布的交叉面積越大,欺詐與正常的區(qū)分度最小,如V15;
  • 兩個分布的交叉面積越小,則該變量對因變量的影響越大,如V14。

下面我們看看各個單變量與class的相關(guān)性分析,為更直觀展示,直接作圖,如下:

  1. # 各個變量的矩陣分布 
  2. crecreditcard_data.hist(figsize=(15,15),bins=50) 
  3. plt.show() 

 

Python分析信用卡反欺詐!騙我程序員,不存在的

6、三種方法建模并分析

本部分將應(yīng)用邏輯回歸、隨機森林、支持向量SVM三種方法建模分析,分別展開如下:

準(zhǔn)備數(shù)據(jù):

  1. # 先把數(shù)據(jù)分為欺詐組和正常組,然后按比例生產(chǎn)訓(xùn)練和測試數(shù)據(jù)集 
  2. # 分組 
  3. Fraud=crecreditcard_data[crecreditcard_data.Class == 1] 
  4. Normal=crecreditcard_data[crecreditcard_data.Class == 0] 
  5. # 訓(xùn)練特征集 
  6. x_train=Fraud.sample(frac=0.7) 
  7. x_train=pd.concat([x_train,Normal.sample(frac=0.7)],axis=0) 
  8. # 測試特征集 
  9. x_test=crecreditcard_data.loc[~crecreditcard_data.index.isin(x_train.index)] 
  10. # 標(biāo)簽集 
  11. y_train=x_train.Class 
  12. y_test=x_test.Class 
  13. # 去掉特征集里的標(biāo)簽和時間列 
  14. x_train=x_train.drop(['Class','Time'],axis=1) 
  15. x_test=x_test.drop(['Class','Time'],axis=1) 
  16. # 查看數(shù)據(jù)結(jié)構(gòu) 
  17. print(x_train.shape,y_train.shape, 
  18.  '\n',x_test.shape,y_test.shape) 
  19. (199364, 29) (199364,)  
  20.  (85443, 29) (85443,) 

6.1 邏輯回歸方法

  1. from sklearn import metrics 
  2. import scipy.optimize as op 
  3. from sklearn.linear_model import LogisticRegression 
  4. from sklearn.cross_validation import KFold,cross_val_score 
  5. from sklearn.metrics import (precision_recall_curve, 
  6.  auc,roc_auc_score, 
  7.  roc_curve,recall_score, 
  8.  classification_report) 
  9. lrmodel = LogisticRegression(penalty='l2'
  10. lrmodel.fit(x_train, y_train) 
  11. #查看模型 
  12. print('lrmodel'
  13. print(lrmodel) 
  14. lrmodel 
  15. LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True
  16.  intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, 
  17.  penalty='l2', random_state=None, solver='liblinear', tol=0.0001, 
  18.  verbose=0, warm_start=False
  19. #查看混淆矩陣 
  20. ypred_lr=lrmodel.predict(x_test) 
  21. print('confusion_matrix'
  22. print(metrics.confusion_matrix(y_test,ypred_lr)) 
  23. confusion_matrix 
  24. [[85284 11] 
  25.  [ 56 92]] 
  26. #查看分類報告 
  27. print('classification_report'
  28. print(metrics.classification_report(y_test,ypred_lr)) 
  29. classification_report 
  30.  precision recall f1-score support 
  31.  0 1.00 1.00 1.00 85295 
  32.  1 0.89 0.62 0.73 148 
  33. avg / total 1.00 1.00 1.00 85443 
  34. #查看預(yù)測精度與決策覆蓋面 
  35. print('Accuracy:%f'%(metrics.accuracy_score(y_test,ypred_lr))) 
  36. print('Area under the curve:%f'%(metrics.roc_auc_score(y_test,ypred_lr))) 
  37. Accuracy:0.999216 
  38. Area under the curve:0.810746 

6.2 隨機森林模型

  1. from sklearn.ensemble import RandomForestClassifier 
  2. rfmodel=RandomForestClassifier() 
  3. rfmodel.fit(x_train,y_train) 
  4. #查看模型 
  5. print('rfmodel'
  6. rfmodel 
  7. rfmodel 
  8. RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini'
  9.  max_depth=None, max_features='auto', max_leaf_nodes=None, 
  10.  min_impurity_decrease=0.0, min_impurity_split=None, 
  11.  min_samples_leaf=1, min_samples_split=2, 
  12.  min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, 
  13.  oob_score=False, random_state=None, verbose=0, 
  14.  warm_start=False
  15. #查看混淆矩陣 
  16. ypred_rf=rfmodel.predict(x_test) 
  17. print('confusion_matrix'
  18. print(metrics.confusion_matrix(y_test,ypred_rf)) 
  19. confusion_matrix 
  20. [[85291 4] 
  21.  [ 34 114]] 
  22. #查看分類報告 
  23. print('classification_report'
  24. print(metrics.classification_report(y_test,ypred_rf)) 
  25. classification_report 
  26.  precision recall f1-score support 
  27.  0 1.00 1.00 1.00 85295 
  28.  1 0.97 0.77 0.86 148 
  29. avg / total 1.00 1.00 1.00 85443 
  30. #查看預(yù)測精度與決策覆蓋面 
  31. print('Accuracy:%f'%(metrics.accuracy_score(y_test,ypred_rf))) 
  32. print('Area under the curve:%f'%(metrics.roc_auc_score(y_test,ypred_rf))) 
  33. Accuracy:0.999625 
  34. Area under the curve:0.902009 

6.3支持向量機SVM

  1. # SVM分類 
  2. from sklearn.svm import SVC 
  3. svcmodel=SVC(kernel='sigmoid'
  4. svcmodel.fit(x_train,y_train) 
  5. #查看模型 
  6. print('svcmodel'
  7. svcmodel 
  8. SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, 
  9.  decision_function_shape='ovr', degree=3, gamma='auto', kernel='sigmoid'
  10.  max_iter=-1, probability=False, random_state=None, shrinking=True
  11.  tol=0.001, verbose=False
  12. #查看混淆矩陣 
  13. ypred_svc=svcmodel.predict(x_test) 
  14. print('confusion_matrix'
  15. print(metrics.confusion_matrix(y_test,ypred_svc)) 
  16. confusion_matrix 
  17. [[85197 98] 
  18.  [ 142 6]] 
  19. #查看分類報告 
  20. print('classification_report'
  21. print(metrics.classification_report(y_test,ypred_svc)) 
  22. classification_report 
  23.  precision recall f1-score support 
  24.  0 1.00 1.00 1.00 85295 
  25.  1 0.06 0.04 0.05 148 
  26. avg / total 1.00 1.00 1.00 85443 
  27. #查看預(yù)測精度與決策覆蓋面 
  28. print('Accuracy:%f'%(metrics.accuracy_score(y_test,ypred_svc))) 
  29. print('Area under the curve:%f'%(metrics.roc_auc_score(y_test,ypred_svc))) 
  30. Accuracy:0.997191 
  31. Area under the curve:0.519696 

7、小結(jié)

  1. 通過三種模型的表現(xiàn)可知,隨機森林的誤殺率最低;
  2. 不應(yīng)只盯著精度,有時候模型的精度高并不能說明模型就好,特別是像本項目中這樣的數(shù)據(jù)嚴(yán)重不平衡的情況。舉個例子,我們拿到有1000條病人的數(shù)據(jù)集,其中990人為健康,10個有癌癥,我們要通過建模找出這10個癌癥病人,如果一個模型預(yù)測到了全部健康的990人,而10個病人一個都沒找到,此時其正確率仍然有99%,但這個模型是無用的,并沒有達到我們尋找病人的目的;
  3. 建模分析時,遇到像本例這樣的極度不平衡數(shù)據(jù)集,因采取下采樣、過采樣等辦法,使數(shù)據(jù)平衡,這樣的預(yù)測才有意義,下一篇文章將針對這個問題進行改進;
  4. 模型、算法并沒有高低、好壞之分,只是在不同的情況下有不同的發(fā)揮罷了,這點應(yīng)正確的看待。 

 

責(zé)任編輯:未麗燕 來源: 今日頭條
相關(guān)推薦

2017-04-11 12:45:29

Python機器學(xué)習(xí)信用卡欺詐檢測

2020-09-23 13:40:01

信用卡欺詐網(wǎng)絡(luò)釣魚攻擊

2017-04-11 21:13:58

機器學(xué)習(xí)數(shù)據(jù)分析pandas

2015-10-10 15:37:50

2020-09-23 11:26:40

人工智能技術(shù)網(wǎng)絡(luò)犯罪

2017-04-28 14:25:06

支付卡合規(guī)方案

2017-04-27 11:09:52

信用卡支付技術(shù)

2014-03-24 09:41:45

攜程信息泄露信用卡

2012-03-16 10:08:39

Geode指紋掃描器信用卡

2018-07-05 14:20:48

信用卡

2010-07-15 15:20:09

2009-03-20 23:50:54

2012-07-02 10:07:40

2014-09-22 10:32:34

2021-04-15 07:43:34

信用卡勒索軟件攻擊

2024-12-13 08:25:59

DML操作SQL

2020-04-17 09:20:19

數(shù)據(jù)泄露漏洞信息安全

2017-04-06 09:20:10

機器學(xué)習(xí)模型信用卡詐騙

2020-09-21 09:02:56

AI機器學(xué)習(xí)類不平衡

2014-06-24 13:33:34

點贊
收藏

51CTO技術(shù)棧公眾號