回归算法的应用——信用卡欺诈检测案例

如下图是该数据集正负样本的分布情况,异常情况相比正常情况极少。
这里写图片描述
面对非平衡数据集时,有两种解决方案:过采样和下采样。
下采样: 让数量多的样本减少到和数量少的样本数量一样多。
过采样:生成数量少的样本,以平衡数据。

下采样

下采样代码:

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

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

data=pd.read_csv("creditcard.csv")
data.head()

#可以看到正负样本分布极不平衡,异常样本很少
count_classes=pd.value_counts(data["Class"],sort=True).sort_index()
count_classes.plot(kind='bar')
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")

#sklearn库提供机器学习操作和预处理操作
#fit_transform将Amount特征变换为一列数据
from sklearn.preprocessing import StandardScaler
data["normAmount"]=StandardScaler().fit_transform(data["Amount"].reshape(-1,1))
#删除Time和Amount两列
data=data.drop(["Time","Amount"],axis=1)

#下采样
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == '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模块,随机选择和异常事件一样多的正常数据
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices)
#合并异常和正常的数据集
under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])
under_sample_data = data.iloc[under_sample_indices,:]
X_undersample = under_sample_data.ix[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.ix[:, under_sample_data.columns == 'Class']
print("Percentage of normal transactions: ", len(under_sample_data[under_sample_data.Class == 0])/len(under_sample_data))
print("Percentage of fraud transactions: ", len(under_sample_data[under_sample_data.Class == 1])/len(under_sample_data))
print("Total number of transactions in resampled data: ", len(under_sample_data))

下采样导致数据量变少。虽然召回率能达到要求,但是将正常类错分为异常类的几率很高。如下图混淆矩阵所示,误分的有9895个,这就是下采样的劣势。
这里写图片描述

交叉验证:

切分数据为两部分。80%训练,20%测试。平均切分训练集为三份1、2、3,分别用1、2来训练,3来验证;用1、3训练,2来验证;用2、3训练、1来验证。利用交叉验证找到合适的模型参数。
本案例采用逻辑斯特回归模型,在skleaarn库中有。

#Recall=TP/(TP+FN)
#cross_val_score表示交叉验证的结果
#混淆矩阵 confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold, cross_val_score
from sklearn.metrics import confusion_matrix,recall_score,classification_report 

#5折交叉验证
def printing_Kfold_scores(x_train_data,y_train_data):
    fold=KFold(len(y_train_data),5,shuffle=False)
    #C就是正则化惩罚项中的λ
    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:
        print('-----------------')
        print('C parameter:',c_param)
        print('-----------------')
        print('')

        recall_accs=[]
        #enumerate枚举类型,代表从1开始,在fold中迭代
        for iteration,indices in enumerate(fold,start=1):
            lr=LogisticRegression(C=c_param,penalty='l1')#选择了L1惩罚,L1、L2均可以
            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)    
        # The mean value of those recall scores is the metric we want to save and get hold of.
        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()]['C_parameter']

    # Finally, we can check which C parameter is the best amongst the chosen.
    print('*********************************************************************************')
    print('Best model to choose from cross validation is with C parameter = ', best_c)
    print('*********************************************************************************')

    return best_c

best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)

模型评估标准

模型有时候很容易就建立出来,但是如何确定模型的有效性和适用性就需要一个评估标准。
TP(true positives):将正类预测为正类数,true代表判断正确,positives为正类
FN(false negatives):将正类预测为负类数
FP(false positives):将负类预测为正类数
TN(true negatives):将负类预测为负类数
精确率: p=TPTP+FP
召回率: R=TPTP+FN
通常使用召回率作为评估模型标准。

正则化惩罚

L2正则化, 1/2w2 ,前面通常乘参数λ
L1正则化, |w|

过采样—SMOTE样本生成策略

1.针对少数类中的每一个样本,找到其k个近邻(k值可选);
2.针对每一个样本,根据少数类需要扩大的情况,从近邻中随机挑选出需要的近邻;
例如,需要少数类增加200%,即原来有100个,希望扩到到300个,就从k个近邻中随机挑选出两个近邻。
3.针对一个样本a和它的近邻b:
3.1.计算两者在各个特征空间中值的差值;
3.2.并将这个差值乘以一个(0,1)的随机数后,与当前样本的特征值相加,作为新的合成样本。

首先需要人为地安装imblearn库,打开anaconda prompt输入指令:

pip install imblearn

SMOTE生成样本代码如下:

##过采样SMOTE策略
import pandas as pd
from imblearn.over_sampling import SMOTE
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split

credit_cards=pd.read_csv('creditcard.csv')

columns=credit_cards.columns
# The labels are in the last column ('Class'). Simply remove it to obtain features columns
features_columns=columns.delete(len(columns)-1)

features=credit_cards[features_columns]
labels=credit_cards['Class']

features_train, features_test, labels_train, labels_test = train_test_split(features, 
                                                                            labels, 
                                                                            test_size=0.2, 
                                                                            random_state=0)
#只对训练进行样本生成,另外的测试集不需要生成
oversampler=SMOTE(random_state=0)
os_features,os_labels=oversampler.fit_sample(features_train,labels_train)
os_features = pd.DataFrame(os_features)
os_labels = pd.DataFrame(os_labels)
best_c = printing_Kfold_scores(os_features,os_labels)

lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(os_features,os_labels.values.ravel())
y_pred = lr.predict(features_test.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(labels_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]))

# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
                      , classes=class_names
                      , title='Confusion matrix')
plt.show()

过采样的混淆矩阵如图:
相比下采样效果更好,误分的数据较少。
这里写图片描述
一般来说数据越多,模型会越好,因此一般会采用过采样方法解决非平衡数据问题。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值