1. 程式人生 > >迴歸演算法的應用——信用卡欺詐檢測案例

迴歸演算法的應用——信用卡欺詐檢測案例

面對非平衡資料集時,有兩種解決方案:過取樣和下采樣。 
下采樣: 讓數量多的樣本減少到和數量少的樣本數量一樣多。 
過取樣:生成數量少的樣本,以平衡資料

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

data=pd.read_csv("creditcard.csv")
data.head()

#可以看到正負樣本分佈極不平衡,異常樣本很少
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")

#sklearn庫提供機器學習操作和預處理操作
#fit_transform將Amount特徵變換為一列資料
from sklearn.preprocessing import StandardScaler
data["normAmount"]=StandardScaler().fit_transform(data["Amount"].reshape(-1,1))
#刪除Time和Amount兩列
data=data.drop(["Time","Amount"],axis=1)

#下采樣
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, 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模組,隨機選擇和異常事件一樣多的正常資料
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.ix[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.ix[:, 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))

下采樣導致資料量變少。雖然召回率能達到要求,但是將正常類錯分為異常類的機率很高。如下圖混淆矩陣所示,誤分的有9895個,這就是下采樣的劣勢。 


交叉驗證:
切分資料為兩部分。80%訓練,20%測試。平均切分訓練集為三份1、2、3,分別用1、2來訓練,3來驗證;用1、3訓練,2來驗證;用2、3訓練、1來驗證。利用交叉驗證找到合適的模型引數。 
本案例採用邏輯斯特迴歸模型,在skleaarn庫中有。

#Recall=TP/(TP+FN)
#cross_val_score表示交叉驗證的結果
#混淆矩陣 confusion_matrix
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 

#5折交叉驗證
def printing_Kfold_scores(x_train_data,y_train_data):
    fold=KFold(len(y_train_data),5,shuffle=False)
    #C就是正則化懲罰項中的λ
    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=0
    for c_param in c_param_range:
        print('-----------------')
        print('C parameter:',c_param)
        print('-----------------')
        print('')

        recall_accs=[]
        #enumerate列舉型別,代表從1開始,在fold中迭代
        for iteration,indices in enumerate(fold,start=1):
            lr=LogisticRegression(C=c_param,penalty='l1')#選擇了L1懲罰,L1、L2均可以
            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)
            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)    
        # The mean value of those recall scores is the metric we want to save and get hold of.
        results_table.ix[j,'Mean recall score'] = np.mean(recall_accs)
        j += 1
        print('')
        print('Mean recall score ', np.mean(recall_accs))
        print('')

    best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']

    # Finally, we can check which C parameter is the best amongst the chosen.
    print('*********************************************************************************')
    print('Best model to choose from cross validation is with C parameter = ', best_c)
    print('*********************************************************************************')

    return best_c

best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)

##過取樣SMOTE策略
import pandas as pd
from imblearn.over_sampling import SMOTE
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split

credit_cards=pd.read_csv('creditcard.csv')

columns=credit_cards.columns
# The labels are in the last column ('Class'). Simply remove it to obtain features columns
features_columns=columns.delete(len(columns)-1)

features=credit_cards[features_columns]
labels=credit_cards['Class']

features_train, features_test, labels_train, labels_test = train_test_split(features, 
                                                                            labels, 
                                                                            test_size=0.2, 
                                                                            random_state=0)
#只對訓練進行樣本生成,另外的測試集不需要生成
oversampler=SMOTE(random_state=0)
os_features,os_labels=oversampler.fit_sample(features_train,labels_train)
os_features = pd.DataFrame(os_features)
os_labels = pd.DataFrame(os_labels)
best_c = printing_Kfold_scores(os_features,os_labels)

lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(os_features,os_labels.values.ravel())
y_pred = lr.predict(features_test.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(labels_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]))

# Plot non-normalized confusion matrix
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
                      , classes=class_names
                      , title='Confusion matrix')
plt.show()

 

參考:https://blog.csdn.net/ruosiliu_123/article/details/149