构建信用卡反欺诈预测模型——机器学习

构建信⽤卡反欺诈预测模型——机器学习
本项⽬需解决的问题 本项⽬通过利⽤信⽤卡的历史交易数据,进⾏,构建信⽤卡反欺诈预测模型,提前发现客户信⽤卡被盗刷的事件。 建模思路 项⽬背景 数据集包含由欧洲持卡⼈于2013年9⽉使⽤信⽤卡进⾏交的数据。此数据集显⽰两天内发⽣的交易,其中284,807笔交易中有492笔被盗刷。数据集⾮常不平衡,积极的类(被盗刷)占所有交易的0.172%。 它只包含作为PCA转换结果的数字输⼊变量。不幸的是,由于保密问题,我们⽆法提供有关数据的原始功能和更多背景信息。特征V1,V2,... V28是使⽤PCA获得的主要组件,没有⽤PCA转换的唯⼀特征是“时间”和“量”。特征'时间'包含数据集中每个事务和第⼀个事务之间经过的秒数。特征“⾦额”是交易⾦额,此特征可⽤于实例依赖的成本认知学习。特征'类'是响应变量,如果发⽣被盗刷,则取值1,否则为0。 1 场景解析(算法选择) 1)⾸先,我们拿到的数据是持卡⼈两天内的信⽤卡交易数据,这份数据包含很多维度,要解决的问题是预测持卡⼈是否会发⽣信⽤卡被盗刷。信⽤卡持卡⼈是否会发⽣被盗刷只有两种可能,发⽣被盗刷或不发⽣被盗刷。⼜因为这份数据是打标好的(字段Class是⽬标列),也就是说它是⼀个监督学习的场景。于是,我们判定信⽤卡持卡⼈是否会发⽣被盗刷是⼀个⼆分类问题,意味着可以通过⼆分类相关的算法来到具体的解决办法,本项⽬选⽤的算法是逻辑回归(Logistic Regression)。 2)分析数据:数据是结构化数据 ,不需要做特征抽象。特征V1⾄
V28是经过处理,⽽特征Time和Amount的数据规格与其他特征差别较⼤,需要对其做特征缩放,将特征
缩放⾄同⼀个规格。在数据质量⽅⾯ ,没有出现乱码或空字符的数据,可以确定字段Class为⽬标列,其他列为特征列。 3)这份数据是全部打标好的数据,可以通过交叉验证的⽅法对训练集⽣成的模型进⾏评估。70%的数据进⾏训练,30%的数据进⾏预测和评估。 现对该业务场景进⾏总结如下: 1)根据历史记录数据学习并对信⽤卡持卡⼈是否会发⽣被盗刷进⾏预测,⼆分类监督学习场景,选择逻辑斯蒂回归(Logistic Regression)算法。 2)数据为结构化数据,不需要做特征抽象,是否需要做特征缩放有待后续观察 2 数据预处理(Pre-processing Data)前期准备import numpy as npimport pandas as pdimport matplotlib.pyplot as ss_validation import
train_test_splitfrom sklearn.linear_model import ss_validation import KFold,
cross_val_ics import
confusion_matrix,precision_recall_curve,auc,roc_auc_score,roc_curve,recall_score,classification_report import
相对标准偏差itertoolsimport seaborn as sns读取数据以及数据初步探查 data =
数据共有284807⾏,31列,其中V1-V28为结构化数据;特征Time和Amount的数据规格和其他特征不⼀样,数量级较⼤。 msno.matrix(data) 数据初步探索对⽬标特征进⾏初步探索 count_classes.plot(kind='bar')plt.title('Fraud class histogram')plt.xlabel('Class')plt.ylabel('Frequency') 可以看出数据很不均衡:数据不均衡很可能导致我们模型预测结果‘0’时很准确,⽽预测‘1’时并不准确。 数据不均衡是机器学习中很常见的情况,解决⽅案有如下⼏种: 1)扩⼤数据样本 2)改变评价标准,以下标准可以更加深⼊地洞察模型的准确率 混淆矩阵:将要预测的数据分到表⾥来显⽰正确的预测(对⾓线),并了解其不正确的预测的类型(哪些类被分配了不正确的预测);精度:⼀种分类准确性的处理⽅法;召回率:⼀种分类完整性的处理⽅法;F1分数(或F-分):精度和召回率的加权平均。 3)对数据重新采样 过抽样:可以从代表性不⾜的类添加实例的副本 抽样不⾜:您可以从过度代表类⾥删除实例 4)⽣成⼈⼯样本(SMOTE) 5)使⽤不同的算法 6)尝试名义变量 3 特征⼯程(Feature Engineering) 1)查看盗刷与正常刷卡的刷卡⾦额分布图 f,(ax1,ax2) = plt.subplots(2, 1, sharex=True, figsize=(12,4))bins=30ax1.hist(data[data.Class ==1]['Amount'],bins=bins)ax1.set_title('Fraud')ax2.hist(data[data.Class == 0] ['Amount'], bins=bins)ax2.set_title('Normal')plt.xlabel('Amount ($)')plt.ylabel('Number of
Transactions')plt.yscale('log')plt.show() 信⽤卡被盗刷发⽣的⾦额与信⽤卡正常⽤户发⽣的⾦额相⽐,⽐较⼩。这说明信⽤卡盗刷者为了不引起信⽤卡卡主的注意,更偏向选择⼩⾦额消费。 2)正常刷卡与盗刷时间分布 plt.figure(figsize=
[16,4])sns.distplot(data[data['Class']==1]['Hour'],bins=50)sns.distplot(data[data['Class']==0]['Hour'],bins=100) 信⽤正常刷卡与盗刷时间分布从⼤体上看并没有太⼤差别,由此推测盗刷者为了减⼩被识别的风险,将盗刷时间放在正常刷卡时间集中区域。因此建⽴模型预测时,可以将该特征过滤。 3)查看其它特征分布 plt.figure(figsize=(12,28*4))v_features = data.ix[:,1:29].columnsgs = gridspec.GridSpec(28, 1)for i, cn in enumerate(data[v_features]): ax = plt.subplot(gs[i]) sns.distplot(data[data.Class == 1] [cn], bins=50) sns.distplot(data[data.Class == 0][cn], bins=50) ax.set_xlabel('') ax.set_title('histogram of feature:' +
str(cn))plt.show() 上图是不同变量在信⽤卡被盗刷和信⽤卡正常的不同分布情况,我们将选择在不同信⽤卡状态下的分布有明显区别的变量。因此剔除变量V8、V13 、V15 、V20 、V21 、V22、 V23 、V24 、V25 、V26 、V27 和V28变量这也与我们开始⽤相关性图谱观察得出结论⼀致,同时剔除变量Time。 4 模型训练 1)处理不平衡样本 X = data.ix[:, lumns != 'Class']y = data.ix[:, lumns == 'Class']# 盗刷样本数量number_records_fraud = len(data[data.Class == 1])fraud_indices =
np.array(data[data.Class == 1].index)# 获取正常刷卡样本的索引normal_indices = data[data.Class == 0].index# 从正常刷卡样本的索引中随机选择与盗刷样本数量相同的量random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)random_normal_indices
= np.array(random_normal_indices)# 合并under_sample_indices =
X_undersample = under_sample_data.ix[:, under_lumns != 'Class']y_undersample = under_sample_data.ix[:, under_lumns == 'Class'] X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample = train_test_split(X_undersample
,y_undersample ,test_size = 0.3) 进⾏数据重新抽样,使样本集⽐例为1:1;同时获取⼀个原⽐例的训练集,⽤于做模型的对⽐。 2)训练模型 在这个模型中,我们可以使⽤召回率来进⾏模型评价,该指标能准确的表达我们捕获盗刷交易的准确度。 精度:Accuracy =
(TP+TN)/total 准确率:precision=TP/(TP+FP) 召回率:recall=TP/(TP+FN) 更多详情查看 a.对模型进⾏迭代,获取训练结果较好的正则化参数 def printing_Kfold_scores(x_train_data,y_train_data): fold = KFold(len(y_train_data),5,shuffle=False) c_param_range = [0.01,0.1,1,10,100] results_table = pd.DataFrame(index=range(len(c_param_range),2), columns=['C_parameter','Mean recall score']) results_table['C_parameter'] = c_param_range j = 0 for c_param in c_param_range: recall_accs = [] f
or
iteration, indices in enumerate(fold,start=1): lr = LogisticRegression(C=c_param,penalty='l1')
lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel()) y_pred_undersample =
lr.predict(x_train_data.iloc[indices[1],:].values) recall_acc =
recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample) recall_accs.append(recall_acc) print('Iteration ', iteration,': recall score = ', recall_acc) results_table.ix[j,'Mean recall score'] = np.mean(recall_accs) j += 1 print('') print('Mean recall score ', np.mean(recall_accs)) print('') best_c = results_table.loc[results_table['Mean recall score'].idxmax()]
a356铝合金['C_parameter'] return best_c Iteration 1 : recall score = 0.952380952381 Iteration 2 : recall score = 0.986111111111 Iteration 3 : recall score = 0.984848484848 Iteration 4 : recall score = 1.0 Iteration 5 : recall score = 0.942857142857 Mean recall score 0.97323953824 Iteration 1 : recall score = 0.904761904762 Iteration 2 : recall score =
0.902777777778 Iteration 3 : recall score = 0.878787878788 Iteration 4 : recall score = 0.9375 Iteration 5 : recall score = 0.871428571429 Mean recall score 0.899051226551 Iteration 1 : recall sc
ore = 0.920634920635 Iteration 2 : recall score = 0.902777777778 Iteration 3 : recall score = 0.893939393939 Iteration 4 : recall score = 0.9375 Iteration 5 : recall score = 0.871428571429 Mean recall score 0.905256132756 Iteration 1 : recall score = 0.920634920635基督教圣歌
Iteration 2 : recall score = 0.902777777778 Iteration 3 : recall score = 0.893939393939 Iteration 4 : recall score =
0.9375 Iteration 5 : recall score = 0.9 Mean recall score 0.91097041847 Iteration 1 : recall score = 0.920634920635 Iteration 2 : recall score = 0.902777777778 Iteration 3 : recall score = 0.909090909091 Iteration 4 : recall score =
0.9375 Iteration 5 : recall score = 0.914285714286 Mean recall score 0.916857864358 b)选择C=0.01进⾏建模,并画出混淆矩阵 def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', Blues):
plt.imshow(cm, interpolation='nearest',cmap=cmap) plt.title(title) lorbar() tick_marks = np.arange(len(classes))
loat')/cm.sum(axis=1) [:,np.newaxis] else: print('Confusion matrix, without normalization') thresh = cm.max() / 2. for i, j in
itertools.product(range(cm.shape[0]), range(cm.shape[1])): (j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') #画出重取样数据的混淆矩阵lr = LogisticRegression(C = best_c, penalty =
'l1')lr.fit(X_train_undersample,y_train_undersample.values.ravel())y_pred_undersample =
lr.predict(X_test_undersample.values)cnf_matrix =
多媒体网络教学系统
confusion_matrix(y_test_undersample,y_pred_undersample)np.set_printoptions(precision=2)print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))class_names =
[0,1]plt.figure()plot_confusion_matrix(cnf_matrix , classes=class_names , title='Confusion matrix')plt.show()#画出原数据的混淆矩阵lr = LogisticRegression(C = best_c, penalty = 'l1')lr.fit(X_train_undersample,y_train_undersample.values.ravel())y_pred = lr.predict(X_test.values)cnf_matrix = confusion_matrix(y_test,y_pred)np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))class_names =
cnf
[0,1]plt.figure()plot_confusion_matrix(cnf_matrix , classes=class_names , title='Confusion matrix')plt.show() 该模型在重采样数据上获得了0.9554的召回率,在原数据上获得了 0.9319的召回率。总体来说,这是⼀个不错的数字 c.画出ROC曲线,对模型进⾏评估lr = LogisticRegression(C = best_c, penalty = 'l1')y_pred_undersample_score =
lr.fit(X_train_undersample,y_train_undersample.values.ravel()).decision_function(X_test_undersample.values)fpr, tpr, thresholds = roc_curve(y_test_undersample.values.ravel(),y_pred_undersample_score)roc_auc = auc(fpr,tpr)# Plot
ROCplt.title('Receiver Operating Characteristic')plt.plot(fpr, tpr, 'b',label='AUC = %0.2f'% roc_auc)plt.legend(loc='lower
right')plt.plot([0,1],[0,1],'r--')plt.xlim([-0.1,1.0])plt.ylim([-0.1,1.01])plt.ylabel('True Positive Rate')plt.xlabel('False Positive
Rate')plt.show() ⼀般来说,如果ROC是光滑的,那么基本可以判断没有太⼤的overfitting,但是由于
边缘父子数据不均衡,只⽤ROC曲线来进⾏评估并不准确。 d.直接使⽤原数据进⾏模型训练并进⾏评估 best_c = printing_Kfold_scores(X_train,y_train)lr =
LogisticRegression(C = best_c, penalty = 'l1')lr.fit(X_train,y_train.values.ravel())y_pred_undersample =
lr.predict(X_test.values)cnf_matrix =
confusion_matrix(y_test,y_pred_undersample)np.set_printoptions(precision=2)print("Recall metric in the testing dataset: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1])) class_names = [0,1]plt.figure()plot_confusion_matrix(cnf_matrix , classes=class_names , title='Confusion matrix')plt.show()lr = LogisticRegression(C = best_c, penalty = 'l1')y_pred_score = lr.fit(X_train,y_train.values.ravel()).decision_function(X_test.values)fpr, tpr, thresholds =
roc_curve(y_test.values.ravel(),y_pred_score)roc_auc = auc(fpr,tpr) plt.title('Receiver Operating Characteristic')plt.plot(fpr, tpr, 'b',label='AUC = %0.2f'% roc_auc)plt.legend(loc='lower right')plt.plot([0,1],[0,1],'r--')plt.xlim([-0.1,1.0])plt.ylim([-
0.1,1.01])plt.ylabel('True Positive Rate')plt.xlabel('False Positive Rate')plt.show() 可以看直接使⽤模型
训练并不能获得很好的召回率,也就是说并不能很好的辨别盗刷交易。然后该模型在ROC曲线仍然有很好的表现,因此应更好的评估⽅法来评估模型。 总结: 1.在数据不均衡的机器学习模型中,应根据具体情况选择是否重新调整数据集⽐例。⼀般说来precision与recall是评价模型两个不同⾓度。例如:对于地震的预测,我们希望的是RECALL⾮常⾼,也就是说每次地震我们都希望预测出来。这个时候我们可以牺牲PRECISION。情愿发出1000次警报,把10次地震都预测正确了;也不要预测100次对了8次漏了两次。在嫌疑⼈定罪⽅⾯,基于不错怪⼀个好⼈的原则,对于嫌疑⼈的定罪我们希望是⾮常准确的。及时有时候放过了⼀些罪犯(recall低),但也是值得的。但是有时候错判是有成本的,应根据具体情况具体选择。 2.原始数据集剥离了业务场景,因此在进⾏数据分析时,并不能看到盗刷交易的具体特征。在具体场景中,每个信⽤卡⽤户都具有⾃⼰的消费特性,如常⽤消费地点,消费时间,消费⾦额,可以根据这些特征俩进⾏建模

本文发布于:2024-09-20 17:45:36,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/718740.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数据   特征   预测
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议