1.数据读取

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inlinedata = pd.read_csv("creditcard.csv")
data.head()

展示数据基本信息,如缺失值,字段类型等等

data.info()

2.数据预处理

#统计不同标签对应的样本数
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")

通过条形图显示,正负样本(class分别为1和0的样本)比例失调,通常解决这一问题的方法有:

  • 调整正负样本的权重
  • 上采样
  • 下采样
#对样本的Amount列进行归一化处理
from sklearn import preprocessing
data['normAmount'] = preprocessing.scale(data['Amount'])
#删除无关列
data = data.drop(['Time', 'Amount'], axis=1)
data.head()

生成下采样样本数据集

#筛选出训练数据与相应的分类标签
X = data.loc[:, data.columns != 'Class']
y = data.loc[:, 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_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.loc[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.loc[:, 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))

3.训练模型——交叉验证、参数选择以及模型评价

训练集及测试集形成:

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)print("Number transactions train dataset: ", len(X_train))
print("Number transactions test dataset: ", len(X_test))
print("Total number of transactions: ", len(X_train)+len(X_test))# 预处理后的下采样数据集
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("")
print("Number transactions train dataset: ", len(X_train_undersample))
print("Number transactions test dataset: ", len(X_test_undersample))
print("Total number of transactions: ", len(X_train_undersample)+len(X_test_undersample))

C参数值的完整调优过程,比较原始样本集与下采样样本集的召回率的大小

#召回率计算公式:Recall = TP/(TP+FN)
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 def printing_Kfold_scores(x_train_data,y_train_data):fold = KFold(len(y_train_data), 5, shuffle=False) # C parameters 取值集合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 = 0for c_param in c_param_range:print('-------------------------------------------')print('C parameter: ', c_param)print('-------------------------------------------')print('')recall_accs = []for iteration, indices in enumerate(fold,start=1):# 在特定参数C下的逻辑回归模型lr = LogisticRegression(C = c_param, penalty = 'l1')#取出训练集训练模型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)# 计算当前c参数值下的召回率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)# 计算不同c参数值下逻辑回归模型的召回率的均值results_table.loc[j, 'Mean recall score'] = np.mean(recall_accs)j += 1print('')print('Mean recall score ', np.mean(recall_accs))print('')best_c = results_table.loc[pd.Series(results_table['Mean recall score']).values.argmax()]['C_parameter']# 选择逻辑回归模型召回率最高时对应的参数c值,即为参数c的最优取值print('*********************************************************************************')print('Best model to choose from cross validation is with C parameter = ', best_c)print('*********************************************************************************')return best_c
#展示下采样数据集在不同参数c下逻辑回归模型的召回率,并选择召回率最高时对应的参数c值
best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)#函数功能:可视化混淆矩阵
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()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()#展示原始数据集在不同参数c下逻辑回归模型的召回率,并选择召回率最高时对应的参数c值
best_c = printing_Kfold_scores(X_train,y_train)lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train, y_train.values.ravel())
y_pred_undersample = lr.predict(X_test.values)# 计算原始数据集召回率
cnf_matrix = confusion_matrix(y_test,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()

阈值的参数选择过程

#可视化参数阈值(thresholds)在取不同值时测试集对应的召回率
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] > iplt.subplot(3,3,j)j += 1# Compute confusion matrixcnf_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]))# Plot non-normalized confusion matrixclass_names = [0,1]plot_confusion_matrix(cnf_matrix, classes=class_names, title='Threshold >= %s'%i)

信用卡欺诈案例数据分析——利用逻辑回归进行分类相关推荐

  1. 利用逻辑回归进行简单的人群分类解决广告推荐问题

    利用逻辑回归进行简单的人群分类解决广告推荐问题 参考文章: (1)利用逻辑回归进行简单的人群分类解决广告推荐问题 (2)https://www.cnblogs.com/songyifan427/p/1 ...

  2. python利用什么写模板_Python利用逻辑回归分类实现模板

    Logistic Regression Classifier逻辑回归主要思想就是用最大似然概率方法构建出方程,为最大化方程,利用牛顿梯度上升求解方程参数. 优点:计算代价不高,易于理解和实现. 缺点: ...

  3. TF之LoR:基于tensorflow利用逻辑回归算LoR法实现手写数字图片识别提高准确率

    TF之LoR:基于tensorflow利用逻辑回归算LoR法实现手写数字图片识别提高准确率 目录 输出结果 设计代码 输出结果 设计代码 #TF之LoR:基于tensorflow实现手写数字图片识别准 ...

  4. ML之mlxtend:基于iris鸢尾花数据集利用逻辑回归LoR/随机森林RF/支持向量机SVM/集成学习算法结合mlxtend库实现模型可解释性(决策边界可视化)

    ML之mlxtend:基于iris鸢尾花数据集利用逻辑回归LoR/随机森林RF/支持向量机SVM/集成学习算法结合mlxtend库实现模型可解释性(决策边界可视化) 目录 相关文章 ML之mlxten ...

  5. NO.62——100天机器学习实践第五天:用逻辑回归模型分析信用卡欺诈案例

    import pandas as pd import matplotlib.pyplot as plt import numpy as np%matplotlib inline #分类计数 count ...

  6. 贝叶斯分析之利用逻辑回归对数据进行分类

    这一节主要将逻辑回归模型应用到莺尾花数据集进行分类 our features were measured from each sample: the length and the width of t ...

  7. 利用逻辑回归进行用户流失预测分析

    1.项目背景 客户流失是所有与消费者挂钩行业都会关注的点.因为发展一个新客户是需要一定成本的,一旦客户流失,除了浪费拉新成本,还需要花费更多的用户召回成本. 所以,电信行业在竞争日益激烈当下,如何挽留 ...

  8. 二元logistic模型案例_二元逻辑回归的简介与操作演示

    二元逻辑回归介绍 定义 Logistic回归主要用于因变量为分类变量(如是否等)的回归分析,自变量可以为分类变量,也可以为连续变量.它可以从多个自变量中选出对因变量有影响的自变量,并可以给出预测公式用 ...

  9. 【Pytorch神经网络实战案例】06 逻辑回归拟合二维数据

    1 逻辑回归与拟合过程 1.1 准备数据-code_01_moons.py(第1部分) import sklearn.datasets import torch import numpy as np ...

最新文章

  1. 如果你在2018面试前端,那这篇文章最好看一看!
  2. 我说分布式事务之消息最终一致性事务(二):RocketMQ的实现
  3. 机器学习笔记:岭回归(L2正则化)
  4. Silverlight MMORPG网页游戏开发课程[一期] 第九课:HUD与背景音乐
  5. Log4net PatternLayout 参数
  6. 一款基于SpringBoot + Spring Security的后台管理系统,强烈推荐,直接用
  7. 发现同构:Gartner曲线、达克效应 与 跨越鸿沟
  8. mos管h桥电机驱动电路与设计原理图-KIA
  9. 【考研】计算机考研复试之智力题测试
  10. 怎样做文献综述:六步走向成功-读书笔记
  11. 2的20次方怎么用计算机计算,2的20次方(2的20次方简便方法)
  12. Python零基础学习笔记(三十三)—— 窗体的控制
  13. 2012成都之行----幺祖祖
  14. 【MES】MES的另一视角
  15. 自动驾驶专题介绍 ———— 转向系统
  16. 『关于摄影的前后期』
  17. 矩阵的行列式、秩的意义
  18. 登录功能图片验证码的实现
  19. 印度的“健康码”:Aarogya Setu为何会失败?
  20. fbx模型导入unity,绑了骨骼加蒙皮法线就反

热门文章

  1. R语言数据框data.frame行和列求和方法
  2. 计算机一级题在哪里练习,计算机一级操作练习题.doc
  3. Secure Copy Protocol(SCP)简介
  4. 微信推文属性的关联分析 by Apriori算法
  5. 2022-2028全球及中国先进超高频系统行业研究及十四五规划分析报告
  6. log4j的配置和使用详解
  7. IntelliJ IDEA运行JDK 19-ea问题
  8. 考研数据结构——必看链表真题(常规套路)
  9. LEC对ASIC的重要性
  10. 凌恩生物资讯|细菌完成图,坑多专家少——请收下这份避坑指南