Python分析信用卡反欺诈!骗我程序员,不存在的

开发 后端 大数据
本文试着从数据分析师的角度,设想“拿到数据该如何寻找规律、选哪种模型来构建反欺诈模型?”的角度来分析,以业务导向为主,不深究算法原理;

前言:

本文研究的是大数据量(284807条数据)下模型选择的问题,也参考了一些文献,但大多不够清晰,因此吐血整理本文,希望对大家有帮助;

本文试着从数据分析师的角度,设想“拿到数据该如何寻找规律、选哪种模型来构建反欺诈模型?”的角度来分析,以业务导向为主,不深究算法原理;

下一篇文章会说明数据结构极度不平衡的情况下,该如何修正数据集、如何调整参数。

数据来源及项目概况

数据是从kaggle上看到的项目,具体链接如下:

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

获取本例数据的,可在上述项目详情链接中下载数据。

数据集包含欧洲持卡人于2013年9月通过信用卡进行的交易。该数据集提供两天内发生的交易,其中在284,807笔交易中有492起欺诈行为。

数据集非常不平衡,负面类别(欺诈)占所有交易的0.172%。

它只包含数值输入变量,这是PCA变换的结果。不幸的是,由于保密问题,我们无法提供有关数据的原始特征和更多背景信息。特征V1,V2,... V28是用PCA获得的主要组件,唯一没有用PCA转换的特征是'Time'和'Amount'。

  • “时间”包含每个事务与数据集中第一个事务之间经过的秒数。
  • '金额'是交易金额,该特征可以用于依赖于例子的成本敏感性学习。
  • “Class”是响应变量,在欺诈的情况下其值为1,否则为0。

2、准备并初步查看数据集

  1. # 导入包 
  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. # 倒入并查看数据 
  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. # 统计下具体数据 
  61. count_classes.value_counts() 
  62. # 也可以用count_classes[0],count_classes[1]看分别数据 
  63. 284315 1 
  64. 492 1 
  65. Name: Class, dtype: int64 
  66. count_classes.plot(kind='bar'
  67. plt.show() 

 Python分析信用卡反欺诈!骗我程序员,不存在的

0代表正常,1代表欺诈,二者数量严重失衡,极度不平衡,根本不在一个数量级上。

3、欺诈与时间序列分布关系

  1. # 查看二者的描述性统计,与时间的序列分布关系 
  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分析信用卡反欺诈!骗我程序员,不存在的

欺诈与时间并没有必然联系,不存在周期性;

正常交易有明显的周期性,有类似双峰这样的趋势。

4、欺诈与金额的关系和分布情况

  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分析信用卡反欺诈!骗我程序员,不存在的

金额普遍较低,可见金额这一列的数据对分析的参考价值不大。

5、查看各个自变量(V1-V29)与因变量的关系

看看各个变量与正常、欺诈之间是否存在联系,为了更直观展示,通过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的关系.png',transparent=False,bbox_inches='tight'
  14. plt.show() 

 Python分析信用卡反欺诈!骗我程序员,不存在的

红色表示欺诈,绿色表示正常。

  • 两个分布的交叉面积越大,欺诈与正常的区分度最小,如V15;
  • 两个分布的交叉面积越小,则该变量对因变量的影响越大,如V14。

下面我们看看各个单变量与class的相关性分析,为更直观展示,直接作图,如下:

  1. # 各个变量的矩阵分布 
  2. crecreditcard_data.hist(figsize=(15,15),bins=50) 
  3. plt.show() 

 

Python分析信用卡反欺诈!骗我程序员,不存在的

6、三种方法建模并分析

本部分将应用逻辑回归、随机森林、支持向量SVM三种方法建模分析,分别展开如下:

准备数据:

  1. # 先把数据分为欺诈组和正常组,然后按比例生产训练和测试数据集 
  2. # 分组 
  3. Fraud=crecreditcard_data[crecreditcard_data.Class == 1] 
  4. Normal=crecreditcard_data[crecreditcard_data.Class == 0] 
  5. # 训练特征集 
  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. # 标签集 
  11. y_train=x_train.Class 
  12. y_test=x_test.Class 
  13. # 去掉特征集里的标签和时间列 
  14. x_train=x_train.drop(['Class','Time'],axis=1) 
  15. x_test=x_test.drop(['Class','Time'],axis=1) 
  16. # 查看数据结构 
  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. #查看预测精度与决策覆盖面 
  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. #查看预测精度与决策覆盖面 
  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. #查看预测精度与决策覆盖面 
  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、小结

  1. 通过三种模型的表现可知,随机森林的误杀率最低;
  2. 不应只盯着精度,有时候模型的精度高并不能说明模型就好,特别是像本项目中这样的数据严重不平衡的情况。举个例子,我们拿到有1000条病人的数据集,其中990人为健康,10个有癌症,我们要通过建模找出这10个癌症病人,如果一个模型预测到了全部健康的990人,而10个病人一个都没找到,此时其正确率仍然有99%,但这个模型是无用的,并没有达到我们寻找病人的目的;
  3. 建模分析时,遇到像本例这样的极度不平衡数据集,因采取下采样、过采样等办法,使数据平衡,这样的预测才有意义,下一篇文章将针对这个问题进行改进;
  4. 模型、算法并没有高低、好坏之分,只是在不同的情况下有不同的发挥罢了,这点应正确的看待。 

 

责任编辑:未丽燕 来源: 今日头条
相关推荐

2017-04-11 12:45:29

Python机器学习信用卡欺诈检测

2020-09-23 13:40:01

信用卡欺诈网络钓鱼攻击

2017-04-11 21:13:58

机器学习数据分析pandas

2020-09-23 11:26:40

人工智能技术网络犯罪

2015-10-10 15:37:50

2017-04-27 11:09:52

信用卡支付技术

2017-04-28 14:25:06

支付卡合规方案

2014-03-24 09:41:45

携程信息泄露信用卡

2018-07-05 14:20:48

信用卡

2010-07-15 15:20:09

2012-03-16 10:08:39

Geode指纹扫描器信用卡

2009-03-20 23:50:54

2021-04-15 07:43:34

信用卡勒索软件攻击

2018-07-19 06:14:09

2023-09-12 08:02:13

viewport断点

2021-01-25 07:21:24

GitHub 开源代码下载

2012-07-02 10:07:40

2014-09-22 10:32:34

2014-03-24 09:16:55

2014-06-24 13:33:34

点赞
收藏

51CTO技术栈公众号