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、准备并初步查看数据集
在学习过程中有什么不懂得可以加我的
python学习交流扣扣qun,784758214
群里有不错的学习视频教程、开发工具与电子书籍。
与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容
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()
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. Name: Time, 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. Name: Time, 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()
欺诈与时间并没有必然联系,不存在周期性;
正常交易有明显的周期性,有类似双峰这样的趋势。
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()
金额普遍较低,可见金额这一列的数据对分析的参考价值不大。
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()
红色表示欺诈,绿色表示正常。
- 两个分布的交叉面积越大,欺诈与正常的区分度最小,如V15;
- 两个分布的交叉面积越小,则该变量对因变量的影响越大,如V14。
下面我们看看各个单变量与class的相关性分析,为更直观展示,直接作图,如下:
1. # 各个变量的矩阵分布
2. crecreditcard_data.hist(figsize=(15,15),bins=50)
3. plt.show()
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
在学习过程中有什么不懂得可以加我的
python学习交流扣扣qun,784758214
群里有不错的学习视频教程、开发工具与电子书籍。
与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容
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、小结
- 通过三种模型的表现可知,随机森林的误杀率最低;
- 不应只盯着精度,有时候模型的精度高并不能说明模型就好,特别是像本项目中这样的数据严重不平衡的情况。举个例子,我们拿到有1000条病人的数据集,其中990人为健康,10个有癌症,我们要通过建模找出这10个癌症病人,如果一个模型预测到了全部健康的990人,而10个病人一个都没找到,此时其正确率仍然有99%,但这个模型是无用的,并没有达到我们寻找病人的目的;
- 建模分析时,遇到像本例这样的极度不平衡数据集,因采取下采样、过采样等办法,使数据平衡,这样的预测才有意义,下一篇文章将针对这个问题进行改进;
- 模型、算法并没有高低、好坏之分,只是在不同的情况下有不同的发挥罢了,这点应正确的看待。
Python分析信用卡反欺诈相关推荐
- 构建信用卡反欺诈预测模型——机器学习
本项目需解决的问题 本项目通过利用信用卡的历史交易数据,进行机器学习,构建信用卡反欺诈预测模型,提前发现客户信用卡被盗刷的事件. 建模思路 项目背景 数据集包含由欧洲持卡人于2013年9月使用信用卡进 ...
- 项目实例---金融---用机器学习构建模型,进行信用卡反欺诈预测
来源: 用机器学习构建模型,进行信用卡反欺诈预测 反欺诈中所用到的机器学习模型有哪些? Credit card fraud detection 构建信用卡反欺诈预测模型--机器学习 信用卡交易数据相关 ...
- 反欺诈概念库-信用卡反欺诈管理
原文:http://www.cnki.com.cn/Article/CJFDTotal-XYKZ200508004.htm 2005年6月,美国爆出4000万张信用卡资料外泄的特大新闻.消息传来,舆论 ...
- 兴业银行与第四范式开启AI平台加速模式 毫秒级信用卡反欺诈系统上线
近日,基于第四范式为兴业银行打造的低门槛.自动化的人工智能平台,兴业银行信用卡中心推出了毫秒级智能交易反欺诈系统,实现了对信用卡欺诈风险自动化.智能化.精确化的甄别与管控,为信用卡用户提供最安全.可信 ...
- python算法实现反欺诈案例完整建模流程!电信诈骗这么多?
近年来,国内的电信诈骗案件呈愈演愈烈之势,本文以某省电信公司简化版本的防诈骗模型为案例,利用python机器学习工具,使用随机森林算法,从数据处理.特征工程.到反诈骗模型的模型的构建及评估等完整流程进 ...
- 【勉强采用】反欺诈之血缘关系分析和犯罪传导监测
文前小故事:隔壁阿姨最近总是带个包鬼鬼祟祟地出去,妈妈好奇,今天跑过去串门,问她最近在忙什么,她一下就忍不住哭了起来:我被人骗了--好多人去要钱--我把我姐和我女儿也坑了--那是我姐夫的安葬费--还有 ...
- 【采用】反欺诈之血缘关系分析和犯罪传导监测 - 知识图谱
近期,一银行找到我,说他们现在有一个立项,题目是<数据血缘关系智能分析和犯罪风险传导监测>,希望听听我的建议.今天正好听到妈妈跟我说起这件事,就想,还是针对这个课题,好好整理下思路,讲一讲 ...
- 保险反欺诈行业发展现状分析:亚洲是主要消费地区,中国市场占据较大份额
保险反欺诈是指保险公司通过各种手段,防止和打击保险欺诈行为的一系列措施.保险欺诈是指保险申请人或受益人故意提供虚假信息或隐瞒真实情况,以获得不应得的保险赔偿或获得更高的保险赔偿金额的行为.保险反欺诈的 ...
- 别忘记了修正反欺诈中的这些内容
互金中做的较多的是贷前反欺诈相关内容,贷前反欺诈也是在整个风控环节中最关键和核心的部分. 反欺诈策略,跟所有的策略类似,都需要一套完整的反馈与修正机制,今天我们也稍微谈谈这套与反欺诈策略修正相关的内容 ...
最新文章
- 趋势 | 人工智能领域十大最具成长性技术展望
- 安装多个java后,java版本不对
- ngui 输入事件处理
- php服务docker化,docker化你的PHP应用环境Nginx PHP-FPM
- 【转】ABP源码分析九:后台工作任务
- 牙齿间隙变大怎么办_牙齿之间的间隙越来越大怎么办?
- Java笔记-编码方式创建kaptcha验证码
- python3导入模块原理_python模块导入原理
- WIndows10下 MySQL 5.7(社区版)安装
- 苹果修复老旧设备中的两个 iOS 0day
- 快速得到容器ID和veth bridge interface的关系
- GraphQL到底怎么用?看看这个例子就知道了
- Planetside.Software.Terragen.v0.9.43.WinALL 1CD(景观产生器)
- java jdbc 批处理_JDBC的批处理操作
- 美国学生债务数据 csv_我如何摆脱学生债务陷阱,为什么其他美国人不那么幸运...
- 计算机win键在哪,Windows键是哪个?电脑上的Win键在哪里? [图片和文字]
- 锐龙R3-3300X和i5-9400f哪个好?
- [游戏数据表]泰拉瑞亚Terraria 全物品属性表
- 2021年美赛B题目思路(仅供参考)——AHP
- Typecho Joe 主题 添加访目录
热门文章
- Linux中用户切换su怎么用的,linux用户切换su命令横杠的作用
- wordcloud词云图(python)
- GoAccess对Nginx日志分析完美分析
- 企业高效办公之选 8500WN全能上网一键式推荐
- java探针开发使用_Java探针技术-retransformclasses的介绍
- 十句中英文情感感言!
- 交换两个变量值的几种方法;
- 机器学习实战(七)02-线性回归提高篇之乐高玩具套件二手价预测
- [原创] Microsoft Word 2010 关闭不正常(提示:已停止工作,Windows正在检查该问题的解决方案。。) 问题的解决
- 智能家居——人脸识别 翔云平台(配置ssl和下载OpenSSL)