机器学习:基于Sklearn,使用随机森林分类器RandomForestClassifier检测信用卡欺诈

前言

系列专栏:【机器学习:算法项目实战】✨︎
本专栏涉及金融、医疗、电商、图像识别、自然语言处理等多个领域的真实案例,让读者从基础的监督学习(如线性回归、逻辑回归、决策树、随机森林)、无监督学习(聚类算法、降维技术)到进阶的深度学习(神经网络、卷积神经网络CNN、循环神经网络RNN等),都能够全面掌握机器学习领域的核心算法,了解不同行业背景下机器学习的应用。

本文旨在实现一个机器学习模型,该模型可以使信用卡公司能够识别欺诈性信用卡交易,这样客户就不会被收取未购买的物品的费用。

信用卡欺诈检测涉及的主要挑战是:

  1. 每天都要处理大量数据,模型构建必须足够快才能及时响应骗局。
  2. 数据不平衡,即大多数交易(99.8%)不是欺诈性的,这使得很难检测到欺诈交易。
  3. 数据可用性,因为数据大多是私有的。
  4. 错误分类的数据可能是另一个主要问题,因为并非每笔欺诈交易都会被发现并且报告。
  5. 诈骗者对模型使用的自适应技术。

如何应对这些挑战?

  1. 使用的模型必须足够简单和快速,以便尽快检测异常并将其归类为欺诈易。
  2. 不平衡可以通过正确使用一些方法来解决,我们将在下一段中讨论
  3. 为了保护用户的隐私,可以降低数据的维度。
  4. 必须采用更可靠的来源来仔细检查数据,至少对于训练模型是这样。
  5. 我们可以使模型简单且可解释,这样当骗子只需进行一些调整即可适应它时,我们就可以启动并运行一个新模型进行部署。

1. 相关库和数据集

1.1 相关库介绍

Python 库使我们能够非常轻松地处理数据并使用一行代码执行典型和复杂的任务。

  • Pandas – 该库有助于以 2D 数组格式加载数据框,并具有多种功能,可一次性执行分析任务。
  • Numpy – Numpy 数组速度非常快,可以在很短的时间内执行大型计算。
  • Matplotlib/Seaborn – 此库用于绘制可视化效果。
  • Sklearn – 包含多个库,这些库具有预实现的功能,用于执行从数据预处理到模型开发和评估的任务。
import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 
from matplotlib import gridspec 

from sklearn.model_selection import train_test_split 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.metrics import classification_report, accuracy_score 
from sklearn.metrics import precision_score, recall_score 
from sklearn.metrics import f1_score, matthews_corrcoef 
from sklearn.metrics import confusion_matrix 

import warnings
warnings.filterwarnings('ignore')

1.2 数据集介绍

数据集显示了两天内发生的交易,其中 284,807 笔交易中有 492 起欺诈。数据集高度不平衡,正类(欺诈)占所有交易的 0.172%。

它仅包含数值输入变量,这些变量是 PCA 转换的结果。很遗憾,由于保密问题,我们无法提供有关数据的原始特征和更多背景信息。特点 V1、V2、…V28 是使用 PCA 获得的主要组件,唯一未使用 PCA 转换的特征是“时间”和“数量”。特征“时间”包含数据集中每个事务与第一个事务之间经过的秒数。“金额”功能是交易金额,此功能可用于与成本相关的学习。特征“类”是响应变量,在欺诈的情况下取值 1,否则取值 0。

考虑到类别不平衡比,我们建议使用精度召回曲线下面积 (AUPRC) 测量准确度。混淆矩阵的准确性对于不平衡分类没有意义。

# Load the dataset from the csv file using pandas 
data = pd.read_csv("creditcard.csv") 
# Grab a peek at the data 
data.head() 

在这里插入图片描述

1.3 数据处理

确定数据集中的欺诈案件数量

# Determine number of fraud cases in dataset 
fraud = data[data['Class'] == 1] 
valid = data[data['Class'] == 0] 
outlierFraction = len(fraud)/float(len(valid)) 
print(outlierFraction) 
print('Fraud Cases: {}'.format(len(data[data['Class'] == 1]))) 
print('Valid Transactions: {}'.format(len(data[data['Class'] == 0]))) 

输出

0.0017304750013189597
Fraud Cases: 492
Valid Transactions: 284315

在所有交易中,只有0.17%的欺诈交易,数据高度不平衡。让我们首先在不平衡的情况下应用我们的模型,如果我们没有得到很好的准确性,那么我们可以找到一种方法来平衡这个数据集。

打印欺诈交易的金额明细

print('Amount details of the fraudulent transaction') 
fraud.Amount.describe() 

输出

Amount details of the fraudulent transaction
count     492.000000
mean      122.211321
std       256.683288
min         0.000000
25%         1.000000
50%         9.250000
75%       105.890000
max      2125.870000
Name: Amount, dtype: float64

打印正常交易的金额明细

print('details of valid transaction') 
valid.Amount.describe() 

输出

details of valid transaction
count    284315.000000
mean         88.291022
std         250.105092
min           0.000000
25%           5.650000
50%          22.000000
75%          77.050000
max       25691.160000
Name: Amount, dtype: float64

从中我们可以清楚地注意到,欺诈者的平均货币交易更多。这使得这个问题变得至关重要。

2. 数据探索分析(可视化)

2.1 绘制相关矩阵

相关矩阵以图形方式让我们了解特征如何相互关联,并可以帮助我们预测最相关的特征。

# Correlation matrix 
corrmat = data.corr() 
fig = plt.figure(figsize = (12, 9)) 
sns.heatmap(corrmat, vmax = .8, square = True) 
plt.show() 

在这里插入图片描述
在热图中,我们可以清楚地看到,大多数特征与其他特征不相关,但有些特征彼此之间具有正相关或负相关。例如,V2V5 与名为 Amount 的特征高度负相关。我们还看到了与 V20Amount 的一些相关性。这使我们能够更深入地了解我们可用的数据。

3. 数据建模(RandomForestClassifier)

3.1 数据准备(拆分为训练集和测试集)

# dividing the X and the Y from the dataset 
X = data.drop(['Class'], axis = 1) 
Y = data["Class"] 
print(X.shape) 
print(Y.shape) 
# getting just the values for the sake of processing 
# (its a numpy array with no columns) 
xData = X.values 
yData = Y.values 

我们将数据集分为两大组。一个用于训练模型,另一个用于测试训练模型的性能。

# Split the data into training and testing sets 
xTrain, xTest, yTrain, yTest = train_test_split( 
		xData, yData, test_size = 0.2, random_state = 42) 

3.2 构建随机森林模型(RandomForestClassifier)

# random forest model creation 
rfc = RandomForestClassifier() 
rfc.fit(xTrain, yTrain) 
# predictions 
yPred = rfc.predict(xTest) 

3.3 构建各种评估参数

# Evaluating the classifier 
# printing every score of the classifier 
# scoring in anything 

n_outliers = len(fraud) 
n_errors = (yPred != yTest).sum() 
print("The model used is Random Forest classifier") 

acc = accuracy_score(yTest, yPred) 
print("The accuracy is {}".format(acc)) 

prec = precision_score(yTest, yPred) 
print("The precision is {}".format(prec)) 

rec = recall_score(yTest, yPred) 
print("The recall is {}".format(rec)) 

f1 = f1_score(yTest, yPred) 
print("The F1-Score is {}".format(f1)) 

MCC = matthews_corrcoef(yTest, yPred) 
print("The Matthews correlation coefficient is{}".format(MCC)) 

输出

The model used is Random Forest classifier
The accuracy is 0.9995962220427653
The precision is 0.9746835443037974
The recall is 0.7857142857142857
The F1-Score is 0.8700564971751412
The Matthews correlation coefficient is0.8749276812909632

3.4 模型评估(可视化混淆矩阵)

# printing the confusion matrix 
LABELS = ['Normal', 'Fraud'] 
conf_matrix = confusion_matrix(yTest, yPred) 
plt.figure(figsize =(7, 6)) 
sns.heatmap(conf_matrix, xticklabels = LABELS, 
			yticklabels = LABELS, annot = True, fmt ="d"); 
plt.title("Confusion matrix") 
plt.ylabel('True class') 
plt.xlabel('Predicted class') 
plt.show() 

在这里插入图片描述
与其他算法进行比较,而无需处理数据的不平衡。

以下是使用XGBoost实现随机森林信用卡欺诈预测的步骤: 1.导入必要的库和数据集 ```python import pandas as pd import numpy as np import xgboost as xgb from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, f1_score, confusion_matrix from imblearn.combine import SMOTEENN from imblearn.under_sampling import RandomUnderSampler # 导入数据集 data = pd.read_csv('creditcard.csv') ``` 2.数据预处理 ```python # 将Amount特征进行标准化处理 from sklearn.preprocessing import StandardScaler data['Amount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1)) # 将Time和Amount特征合并为一个特征,并删除原有的Time和Amount特征 data['Time_Amount'] = data['Time'] + data['Amount'] data.drop(['Time', 'Amount'], axis=1, inplace=True) # 将Class列移动到最后一列 cols = list(data.columns) cols.remove('Class') cols.append('Class') data = data[cols] # 将数据集分为特征和标签 X = data.iloc[:, :-1] y = data.iloc[:, -1] # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) ``` 3.使用SMOTEENN算法进行过采样和欠采样 ```python # 使用SMOTEENN算法进行过采样和欠采样 smote_enn = SMOTEENN(random_state=42) X_new_train, y_new_train = smote_enn.fit_resample(X_train, y_train) # 使用RandomUnderSampler算法进行欠采样 rus = RandomUnderSampler(random_state=42) X_new_2_train, y_new_2_train = rus.fit_resample(X_train, y_train) ``` 4.使用XGBoost算法进行模型训练和预测 ```python # 定义XGBoost模型 xgb_model = xgb.XGBRFClassifier(n_estimators=100, max_depth=3, random_state=42) # 使用SMOTEENN算法进行过采样和欠采样后的数据进行模型训练和预测 xgb_model.fit(X_new_train, y_new_train) y_pred = xgb_model.predict(X_test) # 输出模型评估指标 print('Accuracy:', accuracy_score(y_test, y_pred)) print('F1-score:', f1_score(y_test, y_pred)) print('Confusion matrix:', confusion_matrix(y_test, y_pred)) # 使用RandomUnderSampler算法进行欠采样后的数据进行模型训练和预测 xgb_model.fit(X_new_2_train, y_new_2_train) y_pred_2 = xgb_model.predict(X_test) # 输出模型评估指标 print('Accuracy with RandomUnderSampler:', accuracy_score(y_test, y_pred_2)) print('F1-score with RandomUnderSampler:', f1_score(y_test, y_pred_2)) print('Confusion matrix with RandomUnderSampler:', confusion_matrix(y_test, y_pred_2)) ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

矩阵猫咪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值