Python中的欺诈检测
欺诈行为在许多交易中都很常见。我们可以应用机器学习算法来分析历史数据,并预测交易是欺诈交易的可能性。在我们的示例中,我们将采用信用卡交易,分析数据,创建特征和标签,最后应用一种机器学习算法来判断交易的性质是欺诈还是非欺诈。然后我们将找出我们选择的模型的准确率、精确率和F1值。
准备数据
在此步骤中,我们读取源数据,研究其中存在的变量,并查看一些样本数据。这将帮助我们了解数据集中存在的不同列及其特征。我们将使用Pandas库来创建将在后续步骤中使用的数据框。
示例
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\creditcard.csv')
#https://www.kaggle.com/mlg-ulb/creditcardfraud
# Print the top 5 records
print(datainput[0:5],"\n")
# Print the complete shape of the dataset
print("Shape of Complete Data Set")
print(datainput.shape,"\n")输出
运行以上代码将得到以下结果:
Time V1 V2 V3 ... V27 V28 Amount Class 0 0.0 -1.359807 -0.072781 2.536347 ... 0.133558 -0.021053 149.62 0 1 0.0 1.191857 0.266151 0.166480 ... -0.008983 0.014724 2.69 0 2 1.0 -1.358354 -1.340163 1.773209 ... -0.055353 -0.059752 378.66 0 3 1.0 -0.966272 -0.185226 1.792993 ... 0.062723 0.061458 123.50 0 4 2.0 -1.158233 0.877737 1.548718 ... 0.219422 0.215153 69.99 0 [5 rows x 31 columns] Shape of Complete Data Set (284807, 31)
检查数据中的不平衡
现在我们检查数据在欺诈交易和真实交易中的分布情况。这让我们了解预计有多少百分比的数据是欺诈性的。在机器学习算法中,这被称为数据不平衡。如果大多数交易都不是欺诈性的,那么很难判断少数交易是真实的还是欺诈的。我们使用class列来计算欺诈交易的数量,然后计算出欺诈交易的实际百分比。
示例
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\creditcard.csv')
false = datainput[datainput['Class'] == 1]
true = datainput[datainput['Class'] == 0]
n = len(false)/float(len(true))
print(n)
print('False Detection Cases: {}'.format(len(datainput[datainput['Class'] == 1])))
print('True Detection Cases: {}'.format(len(datainput[datainput['Class'] == 0])),"\n")输出
运行以上代码将得到以下结果:
0.0017304750013189597 False Detection Cases: 492 True Detection Cases: 284315
交易类型详情
我们进一步调查欺诈和非欺诈交易每个类别的交易性质。我们尝试统计估计各种参数,例如均值、标准差、最大值、最小值和不同的百分位数。这是通过使用所描述的方法实现的。
示例
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\creditcard.csv')
#Check for imbalance in data
false = datainput[datainput['Class'] == 1]
true = datainput[datainput['Class'] == 0]
#False Detection Cases
print("False Detection Cases")
print("----------------------")
print(false.Amount.describe(),"\n")
#True Detection Cases
print("True Detection Cases")
print("----------------------")
print(true.Amount.describe(),"\n")输出
运行以上代码将得到以下结果:
False Detection Cases ---------------------- 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 True Detection Cases ---------------------- 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
分离特征和标签
在实现机器学习算法之前,我们需要确定特征和标签。这基本上意味着对因变量和自变量进行分类。在我们的数据集中,class列取决于所有其他列。因此,我们为最后一列创建一个数据框,并为所有其他列创建另一个数据框。这些数据框将用于训练我们将创建的模型。
示例
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\creditcard.csv')
#separating features(X) and label(y)
# Select all columns except the last for all rows
X = datainput.iloc[:, :-1].values
# Select the last column of all rows
Y = datainput.iloc[:, -1].values
print(X.shape)
print(Y.shape)输出
运行以上代码将得到以下结果:
(284807, 30) (284807,)
训练模型
现在我们将数据集分成两部分。一部分用于训练,另一部分用于测试。test_size参数用于决定将使用多少百分比的数据集仅用于测试。此练习将帮助我们对正在创建的模型更有信心。
示例
import pandas as pd
from sklearn.model_selection import train_test_split
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\creditcard.csv')
#separating features(X) and label(y)
X = datainput.iloc[:, :-1].values
# Select the last column of all rows
Y = datainput.iloc[:, -1].values
#train_test_split method
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)应用决策树分类
有很多不同类型的算法可应用于这种情况。但我们选择决策树作为我们的分类算法。其最大树深度为4,并提供测试样本以预测值。最后,我们计算测试结果的准确性,以决定是否继续使用此算法。
示例
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\creditcard.csv')
#separating features(X) and label(y)
X = datainput.iloc[:, :-1].values
Y = datainput.iloc[:, -1].values
#train_test_split method
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
#DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
classifier=DecisionTreeClassifier(max_depth=4)
classifier.fit(X_train,Y_train)
predicted=classifier.predict(X_test)
print("\npredicted values :\n",predicted)
#Accuracy
DT = metrics.accuracy_score(Y_test, predicted) * 100
print("\nThe accuracy score using the DecisionTreeClassifier : ",DT)输出
运行以上代码将得到以下结果:
predicted values : [0 0 0 ... 0 0 0] The accuracy score using the DecisionTreeClassifier : 99.9367999719111
查找评估参数
一旦上述步骤中的准确度水平达到可接受的程度,我们就通过查找不同的参数来进一步评估模型。我们使用精确率、召回率和F1值作为我们的参数。精确率是在检索到的实例中相关实例的分数,而召回率是实际检索到的相关实例的总数的分数。F1值提供了一个单一分数,它在一个数字中平衡了精确率和召回率的考虑。
示例
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\creditcard.csv')
#separating features(X) and label(y)
X = datainput.iloc[:, :-1].values
Y = datainput.iloc[:, -1].values
#train_test_split method
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
#DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
classifier=DecisionTreeClassifier(max_depth=4)
classifier.fit(X_train,Y_train)
predicted=classifier.predict(X_test)
print("\npredicted values :\n",predicted)
#
# #Accuracy
DT = metrics.accuracy_score(Y_test, predicted) * 100
print("\nThe accuracy score using the DecisionTreeClassifier : ",DT)
#
# #Precision
print('precision')
# Precision = TP / (TP + FP) (Where TP = True Positive, TN = True Negative, FP = False Positive, FN = False Negative).
precision = precision_score(Y_test, predicted, pos_label=1)
print(precision_score(Y_test, predicted, pos_label=1))
#Recall
print('recall')
# Recall = TP / (TP + FN)
recall = recall_score(Y_test, predicted, pos_label=1)
print(recall_score(Y_test, predicted, pos_label=1))
#f1-score
print('f-Score')
# F - scores are a statistical method for determining accuracy accounting for both precision and recall.
fscore = f1_score(Y_test, predicted, pos_label=1)
print(f1_score(Y_test, predicted, pos_label=1))输出
运行以上代码将得到以下结果:
The accuracy score using the DecisionTreeClassifier : 99.9403110845827 precision 0.810126582278481 recall 0.7710843373493976 f-Score 0.7901234567901234
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP