逻辑回归实战--信用卡欺诈检测(二)

接上文:

https://blog.csdn.net/weixin_42410915/article/details/108529869

下面用混淆矩阵图更直观的表现结果

'''
绘制混淆矩阵
'''
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')

 

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("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()

print(cnf_matrix)

 输出结果为:

 接下来画出原始数据的混淆矩阵图

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 = [0,1]

plt.figure()
plot_confusion_matrix(cnf_matrix,
                      classes=class_names,
                      title='Confusion matrix')

plt.show()

 结果如下:

分类阈值对结果的影响:如果阈值设定的比较大,模型非常的严格,只有明显异常的值才被当做异常;如果设定的比较小,模型就变得‘宁可错杀一万,不肯放过一个’,只要有一点点异常就会被抓到。

下面讲一下predict()和predict_proba()的区别

predict():训练后返回预测结果,是标签值

predict_proba():返回的是一个n行k列的数组,第i行第j列的数值是模型预测第i个预测样本为某标签的概率,并且每一行的概率和为1

#用之前最好的参数进行建模
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)
#print('y_pred_undersample:', y_pred_undersample)
#print('y_pred_undersample_proba:', y_pred_undersample_proba)
#指定不同的阈值
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 = j+1
    cnf_matrix = confusion_matrix(y_test_undersample, y_test_predictions_high_recall)
    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]
    plot_confusion_matrix(cnf_matrix,
                         classes=class_names,
                         title='Threshold >= %s'%i)

 结果如下:

下采样方法虽然能得到较高的召回率,但是误杀的样本太多了。下面来看一下过采样方法。

上文已提及过采样是通过生成一些负样本,使正负样本数量一致。生成的样本并不是通过简单的复制粘贴,因为一模一样的样本是没有用的,需要采取一些算法,生成类似的样本,最常用的是SMOTH算法,过程如下:

(1)对于少数类中每一个样本x,以欧氏距离为标准计算它到少数类样本集中所有样本的距离,得到其k近邻。

(2)根据样本不平衡比例设置一个采样比例以确定采样倍率N,对于每一个少数类样本x,从其k近邻中随机选择若干个样本,假设选择的近邻为o。

(3)对于每一个随机选出的近邻o,分别与原样本按照公式o(new)=o+rand(0,1)*(x-o)构建新的样本。

from imblearn.over_sampling import SMOTE

'''
credit_cards = pd.read_csv('')
columns = credit_cards.columns
features_columns = credit_cards
oversampler = SMOTE(random_state=0)
'''
os_features = X
os_labels = y

features_train,features_test,labels_train,labels_test = train_test_split(os_features, os_labels,
                                                                        test_size=0.3, 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)

结果如下:

------------------------------------
正则化惩罚力度: 0.01
------------------------------------
Iteration 1 召回率: 0.928571428571
Iteration 2 召回率: 0.912
Iteration 3 召回率: 0.912974203338
Iteration 4 召回率: 0.897270340548
Iteration 5 召回率: 0.89743364277

平均召回率: 0.909649923046

------------------------------------
正则化惩罚力度: 0.1
------------------------------------
Iteration 1 召回率: 0.928571428571
Iteration 2 召回率: 0.92
Iteration 3 召回率: 0.914466363177
Iteration 4 召回率: 0.898652128582
Iteration 5 召回率: 0.898853115932

平均召回率: 0.912108607252

------------------------------------
正则化惩罚力度: 1
------------------------------------
Iteration 1 召回率: 0.928571428571
Iteration 2 召回率: 0.92
Iteration 3 召回率: 0.9145928174
Iteration 4 召回率: 0.898790307385
Iteration 5 召回率: 0.899066664992

平均召回率: 0.91220424367

------------------------------------
正则化惩罚力度: 10
------------------------------------
Iteration 1 召回率: 0.928571428571
Iteration 2 召回率: 0.92
Iteration 3 召回率: 0.914668689934
Iteration 4 召回率: 0.898827992513
Iteration 5 召回率: 0.899079226701

平均召回率: 0.912229467544

------------------------------------
正则化惩罚力度: 100
------------------------------------
Iteration 1 召回率: 0.928571428571
Iteration 2 召回率: 0.92
Iteration 3 召回率: 0.914719271624
Iteration 4 召回率: 0.898840554223
Iteration 5 召回率: 0.899129473539

平均召回率: 0.912252145591

********************************************
效果最好的模型所选参数= 100.0
********************************************

绘制其混淆矩阵:

 结果表明,与下采样对比,误杀比例明显小得多,过采样策略的模型效果较好。

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值