信用卡欺詐檢測(cè)(邏輯回歸項(xiàng)目)

  1. 導(dǎo)入模塊查看數(shù)據(jù)情況, 并繪類別的直方圖
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%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")
  1. 預(yù)處理, 標(biāo)準(zhǔn)化并去除沒(méi)用的特征
from sklearn.preprocessing import StandardScaler

data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1)) #  轉(zhuǎn)換成列向量賦值為新的特征
data = data.drop(['Time','Amount'],axis=1) # 取出兩個(gè)沒(méi)用的特征
data.head()

  1. 下采樣策略(因?yàn)?類別的數(shù)據(jù)非常少, 所以取少量0類別的數(shù)據(jù)與之對(duì)應(yīng))
# 下采樣策略
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']

# 計(jì)算class==1的樣本數(shù)量并取出對(duì)應(yīng)索引值
number_records_fraud = len(data[data.Class == 1])
fraud_indices = np.array(data[data.Class == 1].index)

# 取出class==0的索引值
normal_indices = data[data.Class == 0].index

# 在normal_indices中隨機(jī)選擇
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices) # 轉(zhuǎn)成array格式

# 合并
under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])

# iloc基于索引位來(lái)選取數(shù)據(jù)集
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))

由上可知, 通過(guò)下采樣之后, 取出984個(gè)樣本, 0,1的占比都為分別為0.5

  1. 交叉驗(yàn)證
# 交叉驗(yàn)證
from sklearn.cross_validation import train_test_split
# 對(duì)原始數(shù)據(jù)集也做交叉驗(yàn)證
# test_size:測(cè)試集的比例 random_state:隨機(jī)切分
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)

print("Number transactions train dataset: ", len(X_train))
print("Number transactions test dataset: ", len(X_test))
print("Total number of transactions: ", len(X_train)+len(X_test))

# 對(duì)下采樣數(shù)據(jù)集也做交叉驗(yàn)證
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("")
print("Number transactions train dataset: ", len(X_train_undersample))
print("Number transactions test dataset: ", len(X_test_undersample))
print("Total number of transactions: ", len(X_train_undersample)+len(X_test_undersample))
  1. 模型評(píng)估方法
# 模型評(píng)估方法
# 查全率 Recall = TP/(TP+FN)
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 
def printing_Kfold_scores(x_train_data,y_train_data):
    fold = KFold(len(y_train_data),5,shuffle=False) # 5折交叉驗(yàn)證

    # 正則化懲罰項(xiàng)
    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):

            #  實(shí)例化模型
            lr = LogisticRegression(C = c_param, penalty = 'l1')

            # Use the training data to fit the model. In this case, we use the portion of the fold to train the model
            # with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1]
            lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())

            # 使用訓(xùn)練數(shù)據(jù)中的測(cè)試集預(yù)測(cè)
            y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)

            # 計(jì)算查全率并將其加到表示當(dāng)前c_parameter的查全率列表中
            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
    best_c.dtypes.eq(object) # you can see the type of best_c
    new = best_c.columns[best_c.dtypes.eq(object)] #get the object column of the best_c
    best_c[new] = best_c[new].apply(pd.to_numeric, errors = 'coerce', axis=0) # change the type of object
    best_c
    best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']
    
    # 最后扎狱,我們可以檢查哪一個(gè)C參數(shù)(懲罰力度)是最好的選擇.
    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)



通過(guò)對(duì)比發(fā)現(xiàn), 當(dāng)懲罰項(xiàng)為0.01時(shí), recall值最大

  1. 混淆矩陣
#  混淆矩陣
def plot_confusion_matrix(cm, classes,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    此函數(shù)打印并繪制混淆矩陣.
    """
    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)

# 計(jì)算混淆矩陣(下采樣數(shù)據(jù)集)
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()
下采樣數(shù)據(jù)集的混淆矩陣
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred = lr.predict(X_test.values)

# 計(jì)算混淆矩陣(原始數(shù)據(jù)集)
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()

原數(shù)據(jù)集的混淆矩陣

對(duì)比發(fā)現(xiàn)下采樣建立的模型雖然查全率較好, 但是在原始中發(fā)現(xiàn)誤殺的比例較多, 也就是精度大大降低了

  1. 如果不做下采樣, 直接對(duì)原始數(shù)據(jù)進(jìn)行驗(yàn)證, 看看查全率如何
best_c = printing_Kfold_scores(X_train,y_train)



明顯發(fā)現(xiàn)recall值不如下采樣之后的值

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()
  1. 改變閾值來(lái)觀察效果(sogmoid一般是0.5)
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)

#  一般默認(rèn)使用的閾值是0.5, 現(xiàn)在手動(dòng)指定閾值
thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]

plt.figure(figsize=(10,10))

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) 

不同閾值得到的recall值

不同閾值對(duì)應(yīng)的混淆矩陣

由此發(fā)現(xiàn), 隨著閾值的上升, recall值在降低, 也就是判斷信用卡欺詐的條件越來(lái)越嚴(yán)格.并且閾值取0.5,0.6時(shí)相對(duì)效果較好

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末峦朗,一起剝皮案震驚了整個(gè)濱河市榛斯,隨后出現(xiàn)的幾起案子娇掏,更是在濱河造成了極大的恐慌仿吞,老刑警劉巖志珍,帶你破解...
    沈念sama閱讀 221,820評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件给涕,死亡現(xiàn)場(chǎng)離奇詭異鬼佣,居然都是意外死亡驶拱,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門晶衷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蓝纲,“玉大人阴孟,你說(shuō)我怎么就攤上這事∷懊裕” “怎么了永丝?”我有些...
    開封第一講書人閱讀 168,324評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)箭养。 經(jīng)常有香客問(wèn)我慕嚷,道長(zhǎng),這世上最難降的妖魔是什么毕泌? 我笑而不...
    開封第一講書人閱讀 59,714評(píng)論 1 297
  • 正文 為了忘掉前任闯冷,我火速辦了婚禮,結(jié)果婚禮上懈词,老公的妹妹穿的比我還像新娘蛇耀。我一直安慰自己,他們只是感情好坎弯,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,724評(píng)論 6 397
  • 文/花漫 我一把揭開白布纺涤。 她就那樣靜靜地躺著,像睡著了一般抠忘。 火紅的嫁衣襯著肌膚如雪撩炊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,328評(píng)論 1 310
  • 那天崎脉,我揣著相機(jī)與錄音拧咳,去河邊找鬼。 笑死囚灼,一個(gè)胖子當(dāng)著我的面吹牛骆膝,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播灶体,決...
    沈念sama閱讀 40,897評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼阅签,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了蝎抽?” 一聲冷哼從身側(cè)響起政钟,我...
    開封第一講書人閱讀 39,804評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎樟结,沒(méi)想到半個(gè)月后养交,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,345評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡瓢宦,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,431評(píng)論 3 340
  • 正文 我和宋清朗相戀三年碎连,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片刁笙。...
    茶點(diǎn)故事閱讀 40,561評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡破花,死狀恐怖谦趣,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情座每,我是刑警寧澤前鹅,帶...
    沈念sama閱讀 36,238評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站峭梳,受9級(jí)特大地震影響舰绘,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜葱椭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,928評(píng)論 3 334
  • 文/蒙蒙 一捂寿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧孵运,春花似錦秦陋、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至旷赖,卻和暖如春顺又,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背等孵。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工稚照, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人俯萌。 一個(gè)月前我還...
    沈念sama閱讀 48,983評(píng)論 3 376
  • 正文 我出身青樓果录,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親绳瘟。 傳聞我的和親對(duì)象是個(gè)殘疾皇子雕憔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,573評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容