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