python實現信用卡欺詐檢測 logistic迴歸邏輯迴歸演算法
阿新 • • 發佈:2019-01-06
1.資料集下載 :連結: https://pan.baidu.com/s/1zUxSxwiProvfmAAWjyYb4w 密碼: 6eai
程式碼下載 :連結: https://pan.baidu.com/s/1KyVOEU3p-sfCQIauCXGWIA 密碼: tgrh
2.程式碼的實現:
#新增宣告
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#讀資料並顯示前五行 data = pd.read_csv('creditcard.csv') data.head()
#假設 class=0表示正常 class=1表示異常 用柱狀圖顯示出樣本的分佈
count_classes = pd.value_counts(data['Class'], sort = True).sort_index()
count_classes.plot(kind = 'bar')
plt.title('Fraud class histofram')
plt.xlabel('Class')
plt.ylabel('Frequence')
plt.show()
from sklearn.preprocessing import StandardScaler #裡面的資料進行操作對Amount的數值進行操作得到normAmount 刪除Amount和Time列。由於Amount的數值比較大,對其標準化操作一下。 #reshape中的-1表示 我的資料是1列 多少行你程式自己看著辦。 data['normAmount'] = StandardScaler().fit_transform(data['Amount'].reshape(-1,1)) data = data.drop(['Time','Amount'],axis=1) data.head()
#下采樣,0和1的樣本資料數量一樣少
#本資料集中class=1的樣本很少,我們取0的樣本數和1的樣本數一樣多。 組成一個下采樣集。
X = data.ix[:,data.columns !='Class'] #除了Class列的值 所有列的值都輸入進去 y= data.ix[:,data.columns =='Class'] print(len(y)) print(len(X)) number_records_fraud = len(data[data.Class==1]) #取calss=1的數量 fraud_indices = np.array(data[data.Class==1].index) #將class=1的索引儲存到fraud_indices normal_indices = data[data.Class==0].index #索引隨機選擇 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 和y_undersample標籤 X_undersample = under_sample_data.ix[:,under_sample_data.columns!='Class'] y_undersample = under_sample_data.ix[:,under_sample_data.columns=='Class'] print(len(under_sample_data[under_sample_data.Class==1])/len(under_sample_data),len(under_sample_data[under_sample_data.Class==1])) print(len(under_sample_data[under_sample_data.Class==0])/len(under_sample_data),len(under_sample_data[under_sample_data.Class==0])) print(len(under_sample_data))
#交叉驗證 資料切分成訓練集和測試集 假設訓練集平均分三份 1,2訓練 3來驗證 | 1,3訓練 2驗證 | 2,3訓練 1驗證
from sklearn.cross_validation import train_test_split
#所有資料集切分 7成的訓練 3成的測試
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)
print(len(X_train))
print(len(X_test))
print(len(y_train))
print(len(y_test))
#y_undersample 下采樣資料集切分
X_train_undersample,X_test_undersample,y_train_undersample,y_test_undersample = train_test_split(X_undersample,y_undersample,test_size = 0.3, random_state = 0)
print(len(X_train_undersample))
print(len(X_test_undersample))
print(len(y_train_undersample))
print(len(y_test_undersample))
#模型建立
#recall召回率 作為模型評估標準 Recall = TP/(FP+TP)
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold,cross_val_score #KFold 幾倍的交叉驗證
from sklearn.metrics import confusion_matrix,recall_score,classification_report
def printing_Kfold_scores(x_train_data,y_train_data):
fold = KFold(len(y_train_data),5,shuffle=False) #將訓練集分成5分 交叉驗證
# 懲罰項的懲罰力度
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
# the k-fold will give 2 lists: train_indices = indices[0], test_indices = indices[1]
j = 0
for c_param in c_param_range:
print('-------------------------------------------')
print('C parameter: ', c_param)
print('-------------------------------------------')
print('')
recall_accs = []
for iteration, indices in enumerate(fold,start=1):
# L1正則懲罰 + 懲罰發力度
lr = LogisticRegression(C = c_param, penalty = 'l1')
#用訓練資料中的訓練資料去 訓練模型。
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)
# 求平均召回率
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) #用下采樣樣本訓練模型
#混淆矩陣的生成。
def plot_confusion_matrix(cm, classes,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=0)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
import itertools #用測試資料上面跑的結果。
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample = lr.predict(X_test_undersample.values)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test_undersample,y_pred_undersample)
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()
#圖中可以看出來 召喚率為 136/(136+11) = 0.92517召喚率比較高 但是存在很高的誤殺率:7263個樣本。 # 採用L1正則懲罰 C表示懲罰的力度 lr = LogisticRegression(C = best_c, penalty = 'l1') lr.fit(X_train_undersample,y_train_undersample.values.ravel()) y_pred = lr.predict(X_test.values) # 計算混淆矩陣 cnf_matrix = confusion_matrix(y_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()
best_c = printing_Kfold_scores(X_train,y_train) #用所有資料訓練模型
#誤殺率比較低只有 12的樣本誤殺,但是 召喚率低。
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train,y_train.values.ravel())
y_pred_undersample = lr.predict(X_test.values)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test,y_pred_undersample)
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()
#採用不同的閾值
lr = LogisticRegression(C = 0.01, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values) #設定不同的閾值的測試結果
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
plt.figure(figsize=(10,10))
#當閾值為0.5和0.6的時候整體結果是比較好的。當閾值為0.1,0.2,0.3的時候召喚率是100%但是誤殺率也是100% 當閾值是0.8,0.9的時候召喚率低但是誤殺率也低。
j = 1
for i in thresholds:
y_test_predictions_high_recall = y_pred_undersample_proba[:,1] > i
plt.subplot(3,3,j)
j += 1
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
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]
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Threshold >= %s'%i)
plt.show()
#增加負樣本數量 像本次的測試資料一樣 負樣本太少,導致訓練的不是很理想。我們要自動生成一些負樣本。
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)
#用SMOTE生成負樣本,數量和正樣本差不多。
oversampler=SMOTE(random_state=0)
os_features,os_labels=oversampler.fit_sample(features_train,labels_train)
#生成的負樣本的數量
len(os_labels[os_labels==1])
#生成負樣本之後在進行訓練。 得到的結果比之前要好很多
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()