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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dian1pei2xiao3/article/details/83744179

面对非平衡数据集时,有两种解决方案:过采样和下采样。 
下采样: 让数量多的样本减少到和数量少的样本数量一样多。 
过采样:生成数量少的样本,以平衡数据

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)

##过采样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()

参考:https://blog.csdn.net/ruosiliu_123/article/details/149

猜你喜欢

转载自blog.csdn.net/Dian1pei2xiao3/article/details/83744179