python 机器学习实战:信用卡欺诈异常值检测

本文介绍了使用Python进行信用卡欺诈检测的方法,包括数据预处理、解决样本不平衡问题、交叉验证以及模型评估。通过对不同C参数的实验,得出最佳模型选择,并展示了在测试集上的召回率结果。
摘要由CSDN通过智能技术生成

    今晚又实战了一个小案例,把它总结出来:有些人利用信用卡进行诈骗等活动,如何根据用户的行为,来判断该用户的信用卡账单涉嫌欺诈呢?数据集见及链接:  在这个数据集中,由于原始数据有一定的隐私,因此,每一列(即特征)的名称并没有给出。

    一开始,还是导入库:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv('creditcard.csv')
#data.head(10)
print (data.shape)

我们发现,最后一列"Class"要么是 0 ,要么是 1,而且是 0 的样本很多,1 的样本很少。这也符合正常情况:利用信用卡欺诈的情况毕竟是少数,大多数人都是守法的公民。由于样本太多了,我们不可能去数 0 和 1 的个数到底是多少。因此,需要做一下统计:

count_class = pd.value_counts(data['Class'],sort = True).sort_index()
print (count_class)

输出结果为:

0 284315
1 492
Name: Class, dtype: int64

结果也显示了,0的个数远远多于1的个数。那么,这样就会使正负样本的个数严重失衡。为了解决这个问题,我们需要针对样本不均衡,提出两种解决方案:过采样和下采样。

      在对样本处理之前,我们需要对样本中的数据先进行处理。我们发现,有一列为 Time ,这一列显然与咱们的训练结果没有直接或间接关系,因此需要把这一列去掉。我们还发现,在 v1 ~v28特征中,取值范围大致在 -1 ~ +1 之间,而Amount 这一类数值非常大,如果我们不对这一列进行处理,这一列对结果的影响,可能非常巨大。因此,要对这一列做标准化:使均值为0,方差为1。 此部分代码如下:

from sklearn.preprocessing import StandardScaler    #导入数据预处理模块
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1,1))   # -1表示系统自动计算得到的行,1表示1列
data = data.drop(['Time','Amount'],axis = 1)  # 删除两列,axis =1表示按照列删除,即删除特征。而axis=0是按行删除,是删除样本
#print (data.head(3))
#print (data['normAmount'])

     解决样本不均衡:两种方法可以采用——过采样和下采样。过采样是对少的样本(此例中是类别为 1 的样本)再多生成些,使 类别为 1 的样本和 0 的样本一样多。而下采样是指,随机选取类别为 0 的样本,是类别为 0 的样本和类别为 1 的样本一样少。下采样的代码如下:

X = data.ix[:,data.columns != 'Class'] #ix 是通过行号和行标签进行取值
y = data.ix[:,data.columns == 'Class']    # y 为标签,即类别
number_records_fraud = len(data[data.Class==1])  #统计异常值的个数
#print (number_records_fraud)  # 492 个
#print (data[data.Class == 1].index)
fraud_indices = np.array(data[data.Class == 1].index)   #统计欺诈样本的下标,并变成矩阵的格式
#print (fraud_indices)
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)
#print (len(random_normal_indices))  #492 个

under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])  # 将正负样本的索引进行组合
#print (under_sample_indices)   # 984个
under_sample_data = data.iloc[under_sample_indices,:]  # 按照索引进行取值
X_undersample = under_sample_data.iloc[:,under_sample_data.columns != 'Class']  #下采样后的训练集
y_undersample = under_sample_data.iloc[:,under_sample_data.columns == 'Class']   #下采样后的标签

print (len(under_sample_data[under_sample_data.Class==1])/len(under_sample_data)) # 正负样本的比例都是 0.5

      下一步:交叉验证。交叉验证可以辅助调参,使模型的评估效果更好。举个例子,对于一个数据集,我们需要拿出一部分作为训练集(比如 80%),计算我们需要的参数。需要拿出剩下的样本,作为测试集,评估我们的模型的好坏。但是,对于训练集,我们也并不是一股脑地拿去训练。比如把训练集又分成三部分:1,2,3.第 1 部分和第 2 部分作为训练集,第 3 部分作为验证集。然后,再把第 2 部分和第 3 部分作为训练集,第 1 部分作为验证集,然后,再把第 1部分和第 3 部分作为训练集,第 2 部分作为验证集。

from sklearn.cross_validation import train_test_split   # 导入交叉验证模块的数据切分
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state = 0) # 返回 4 个值
#print (len(X_train)+len(X_test))
#print (len(X))

X_undersample_train,X_undersample_test,y_undersample_train,y_undersample_train = train_test_split(X_undersample,y_undersample,test_size = 0.3,random_state = 0)
print (len(X_undersample_train)+len(X_undersample_test))
print (len(X_undersample))

      我们需要注意,对数据进行切分,既要对原始数据进行一定比例的切分,测试时能用到;又要对下采样后的样本进行切分,训练的时候用。而且,切分之前,每次都要进行洗牌。

      下一步:模型评估。利用交叉验证,选择较好的参数

#Recall = TP/(TP+FN)
from sklearn.linear_model import LogisticRegression  #
from sklearn.cros
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值