欺诈确实涉及许多交易。我们可以将机器学习算法应用于过去的数据,并预测交易是欺诈交易的可能性。在我们的示例中,我们将进行信用卡交易,分析数据,创建功能和标签,最后应用一种机器学习算法来判断交易的性质是否为欺诈。然后,我们将找出所选择模型的准确性,精度和f分数。
在这一步中,我们读取源数据,研究其中存在的变量,并查看一些示例数据。这将帮助我们了解数据集中存在的不同列并研究其功能。我们将使用Pandas is library创建数据框,该数据框将在后续步骤中使用。
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)
现在,我们检查数据如何在欺诈性交易和真实交易之间分配。这使我们对预期有百分之几的数据被欺诈的想法。在ml算法中,这称为数据不平衡。如果大多数交易不是欺诈性的,则很难判断很少的交易是真实交易。我们使用类列来计算交易中欺诈引擎的数量,然后计算出欺诈交易的实际百分比。
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
在实施ML算法之前,我们需要确定功能和标签。这基本上意味着对因变量和独立变量进行分类。在我们的数据集中,类列取决于所有其他列的其余部分。因此,我们为最后一列创建一个数据框,并为所有其他列的其余部分创建另一个数据框。这些数据框将用于训练我们将要创建的模型。
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
一旦上述步骤中的精度水平可以接受,我们将通过找出不同的参数对模型进行进一步评估。其中使用精度,召回值和F得分作为我们的参数。精度是相关实例在检索到的实例中所占的比例,而召回率是实际检索到的相关实例的总量中所占的比例。F得分提供了一个单一得分,可以在一个数字中兼顾精度和召回率。
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