异常数据检测(信用卡欺诈)逻辑回归实战案例

1. 读取数据

import numpy as np  # 矩阵计算
import pandas as pd # 数据处理和数据分析
import matplotlib.pyplot as plt  # 数据可视化展示
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline  # 画图可以镶嵌到当前页面,不指定画图要指定一些东西,比较麻烦

Amount数据需要标准化的原因,因为Amount和v1-v28的数值差异太大

# 数据读取
import os
os.chdir('C:/Users/Liu/Desktop')
data = pd.read_csv('creditcard.csv')
data.head()
count_class = pd.value_counts(data['Class'],sort = True)
#count_class.plot(kind = 'bar') # 画图观察一下
 
# 数据标准化
from sklearn.preprocessing import StandardScaler
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1,1)) # values将ndarry转换成数值
data = data.drop(['Time','Amount'],axis = 1)
data.head()

2. 针对问题给出解决方案

解决方案:将标签0和1的数据的数目转化为一致然后再模型训练
第一种方案:标签0数据和标签1数据一样少,数据多的一方降到和数据少的一方一致(降采样 under sample)
第二种方案:标签1数据和标签0数据一样多,数据少的一方增到和数据多的一方一致(过采样 over sample)

#       所有样本     找到指定的列
x = data.iloc[:,data.columns !='Class']
y = data.iloc[:,data.columns == 'Class']


#得到所有异常样本的索引
number_records_fraud = len(data[data.Class ==1])
#fraud_indices = np.array(data[data.Class == 1].index)
fraud_indices = data[data.Class == 1].index


# 得到所有异常样本的索引
#number_records_normal = len(data[data.Class == 0])
#normal_indices = np.array(data[data.Class == 0].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 = np.concatenate([fraud_indices,random_normal_indices])

# 根据索引得到下采样所有样本点
under_sample_data = data.iloc[under_sample_indices,:]
print(len(under_sample_data))
X_undersample = under_sample_data.iloc[:,under_sample_data.columns !='Class']
Y_undersample = under_sample_data.iloc[:,under_sample_data.columns =='Class']


3.数据集切分

注意是train_test_split针对测试集和非测试集的划分(也叫留出法,按照一定比例切分数据,交叉验证在此之后进行),特别留意由于是随机的切分,要进行降采样和过采样的对比分析,这里指定切分的方式和随机种子两个参数,需要确保数据输入是一样的,这样才能将两种方案的结果进行对比,否则就没有可比性

#数据集划分
from sklearn.model_selection import train_test_split
# 整个数据集进行划分
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,random_state = 0)

print(len(x_train))
print(len(y_train))
print(x_train.head())

4.评估方法对比(交叉验证)

交叉验证的过程是都是训练集的数据,不涉及到测试集的

# 逻辑回归模型
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import confusion_matrix,recall_score,classification_report 
from sklearn.model_selection import cross_val_predict

def printing_Kfold_scores(x_train_data,y_train_data):
    fold = KFold(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

    # k-fold 表示K折的交叉验证,这里会得到两个索引集合: 训练集 = indices[0], 验证集 = indices[1]
    j = 0
    #循环遍历不同的参数
    for c_param in c_param_range:
        print('-------------------------------------------')
        print('正则化惩罚力度: ', c_param)
        print('-------------------------------------------')
        print('')

        recall_accs = []
        
        #一步步分解来执行交叉验证
        for iteration, indices in enumerate(fold.split(x_train_data)): 

            # 指定算法模型,并且给定参数
            lr = LogisticRegression(C = c_param, penalty = 'l2')

            # 训练模型,注意索引不要给错了,训练的时候一定传入的是训练集,所以XY的索引都是0
            lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())

            # 建立好模型后,预测模型结果,这里用的就是验证集,索引为1
            y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)

            # 有了预测结果之后就可以来进行评估了,这里recall_score需要传入预测值和真实值。
            recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample)
            # 一会还要算平均,所以把每一步的结果都先保存起来。
            recall_accs.append(recall_acc)
            print('Iteration ', iteration,': 召回率 = ', recall_acc)

        # 当执行完所有的交叉验证后,计算平均结果
        results_table.loc[j,'Mean recall score'] = np.mean(recall_accs)
        j += 1
        print('')
        print('平均召回率 ', np.mean(recall_accs))
        print('')
        
    #找到最好的参数,哪一个Recall高,自然就是最好的了。
    best_c = results_table.loc[results_table['Mean recall score'].astype('float32').idxmax()]['C_parameter']
    
    # 打印最好的结果
    print('*********************************************************************************')
    print('效果最好的模型所选参数 = ', best_c)
    print('*********************************************************************************')
    
    return best_c

函数调用

best_c = printing_Kfold_scores(x_train_undersample,y_train_undersample)

5.混淆矩阵的可视化

为了方便查看召回率的数值,可以进行混淆矩阵中各类数据的可视化,这里还是直接封装函数,后续使用到时直接调用(这块的绘图问题直接换数据套模板即可)

def plot_confusion_matrix(cm, classes,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    绘制混淆矩阵
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=0)
    plt.yticks(tick_marks, classes)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(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')

接着调用函数,进行可视化展示,需要传递两个参数(混合矩阵的值,和分类的名称,这预测的是测试值test

import itertools
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("召回率: ", 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) #指定保留2位小数点

print("召回率: ", 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()

图表结果显示还是不行,误杀率太高,考虑调整阈值来改善结果

6. 阈值对结果的影响

逻辑回归中使到的激活函数,一般是sigmoid函数,根据输出一个范围在0-1之间的值,结果大于0.5的样本归入1类,小于0.5的样本归入0类,那么这个0.5就是一个阈值,并非说是指定的,只能是0.5,是可以进行改变的,下面直接先给代码,然后再进行分析解释

# 用之前最好的参数来进行建模
lr = LogisticRegression(C = 0.01, penalty = 'l1')

# 训练模型,还是用下采样的数据集
lr.fit(X_train_undersample,y_train_undersample.values.ravel())

# 得到预测结果的概率值
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)

#指定不同的阈值
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]

plt.figure(figsize=(10,10))

j = 1

# 用混淆矩阵来进行展示
for i in thresholds:
    y_test_predictions_high_recall = y_pred_undersample_proba[:,1] > i
    
    plt.subplot(3,3,j)
    j += 1
    
    cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
    np.set_printoptions(precision=2)

    print("给定阈值为:",i,"时测试集召回率: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))

    class_names = [0,1]
    plot_confusion_matrix(cnf_matrix
                          , classes=class_names
                          , title='Threshold >= %s'%i)

7. SMOTE过采样方案

SMOTE样本生成策略

import pandas as pd
from imblearn.over_sampling import SMOTE
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
# 在特征中去除掉标签
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.3,                                                                             random_state=0)
#基于SMOTE算法来进行样本生成,这样正例和负例样本数量就是一致的了
oversampler=SMOTE(random_state=0)
os_features,os_labels=oversampler.fit_sample(features_train,labels_train)
len(os_labels[os_labels==1]) #训练集样本数量

#使用之前,注意数据格式要转化为一致
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)

# 计算混淆矩阵
cnf_matrix = confusion_matrix(labels_test,y_pred)
np.set_printoptions(precision=2)

print("召回率: ", 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()
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值