Logistic Regression 信用卡交易異常檢測(cè)

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

%matplotlib inline
data = pd.read_scv("creditcard.csv")
data.head()
data
help(pd.value_counts) # 計(jì)算非空值計(jì)數(shù)的直方圖

value_counts(values, sort=True, ascending=False, normalize=False, bins=None, dropna=True) Compute a histogram of the counts of non-null values.

count_classes = pd.value_counts(data['Class'], sort = True).sort_index()
# obj.sort_index() 按行索引進(jìn)行排序
count_classes.plot(kind = 'bar')
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")
交易正常與異常的數(shù)量

針對(duì)不平衡樣本處理方法:過(guò)采樣和欠采樣

X=data.loc[:, data.columns != 'Class'] # 將不是class列的數(shù)據(jù)賦給X
y = data.loc[:, data.columns == 'Class'] 
# 計(jì)算交易異常的個(gè)數(shù)
number_records_fraud = len(data[data.Class == 1])
# data.Class ==1 返回的是布爾值,data[True]是返回Class列為1的整行數(shù)據(jù)
fraud_indices = np.array(data[data.Class == 1 ].index)
# 將Class為1的數(shù)據(jù)的索引生成一個(gè)數(shù)組峭范。
normal_indices = data[data.Class == 0].index
# 將Class = 0 的數(shù)據(jù)的索引賦給normal_indices
欠采樣
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
# 隨機(jī)選擇(從Class = 0 的索引里選擇,數(shù)量和class = 1 的一樣多,是否替換樣本為否)
random_normal_indices = np.array(random_normal_indices)

# Appending the 2 indices
under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])
## 將兩個(gè)索引數(shù)組拼接起來(lái)
# Under sample dataset
under_sample_data = data.iloc[under_sample_indices,:]
# 通過(guò)索引將每一行數(shù)據(jù)賦給欠采樣數(shù)據(jù)集
X_undersample = under_sample_data.loc[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.loc[:, under_sample_data.columns == 'Class']
# 將欠采樣數(shù)據(jù)集的X,y分開(kāi)

# Showing ratio 計(jì)算正常交易和異常交易的所占的比例
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))
欠采樣樣本

loc函數(shù)完全基于標(biāo)簽位置的索引器厘惦,所謂標(biāo)簽败富,位置就是定義的行標(biāo)題

iloc函數(shù)完全基于行號(hào)的索引器歹河,所謂的行號(hào)就是第0,1赖临,2行

from sklearn.model_selection import train_test_split  
#從sklearn庫(kù)調(diào)特征選擇將樣本分成為訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, random_state = 0) 
# 測(cè)試集占總樣本的0.3灾锯, 計(jì)算測(cè)試的個(gè)數(shù)兢榨。
# whole dataset
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))
# undersampled dataset
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_train_undersample))
print("Total number of transactions:", len(X_train_undersample) + len(X_test_undersample))
切分訓(xùn)練集和測(cè)試集

幾個(gè)評(píng)價(jià)指標(biāo)

評(píng)價(jià)指標(biāo)

錯(cuò)誤率

準(zhǔn)確度

精確度

召回率

F1_score

ROC曲線

以FPR為橫坐標(biāo),TPR為縱坐標(biāo)顺饮,那么ROC曲線就是改變各種閾值后得到的所有坐標(biāo)點(diǎn) (FPR,TPR) 的連線吵聪,畫出來(lái)如下。紅線是隨機(jī)亂猜情況下的ROC兼雄,曲線越靠左上角吟逝,分類器越佳。


ROC

AUC被定義為ROC曲線下的面積
在比較不同的分類模型時(shí)赦肋,可以將每個(gè)模型的ROC曲線都畫出來(lái)块攒,比較曲線下面積做為模型優(yōu)劣的指標(biāo)。
ROC曲線下方的面積(英語(yǔ):Area under the Curve of ROC (AUC ROC))佃乘,其意義是:
因?yàn)槭窃?x1的方格里求面積囱井,AUC必在0~1之間。
假設(shè)閾值以上是陽(yáng)性趣避,以下是陰性庞呕;
若隨機(jī)抽取一個(gè)陽(yáng)性樣本和一個(gè)陰性樣本,分類器正確判斷陽(yáng)性樣本的值高于陰性樣本之機(jī)率

簡(jiǎn)單說(shuō):AUC值越大的分類器鹅巍,正確率越高千扶。

#Recall = TP/(TP+FN)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix, recall_score, classification_report
# 分類報(bào)告sklearn中的classification_report函數(shù)用于顯示主要分類指標(biāo)的文本報(bào)告.在報(bào)告中顯示每個(gè)類的精確度,召回率骆捧,F(xiàn)1值等信息澎羞。 
# 主要參數(shù): 
# y_true:1維數(shù)組,或標(biāo)簽指示器數(shù)組/稀疏矩陣敛苇,目標(biāo)值妆绞。 
# y_pred:1維數(shù)組顺呕,或標(biāo)簽指示器數(shù)組/稀疏矩陣,分類器返回的估計(jì)值括饶。 
# labels:array株茶,shape = [n_labels],報(bào)表中包含的標(biāo)簽索引的可選列表图焰。 
# target_names:字符串列表启盛,與標(biāo)簽匹配的可選顯示名稱(相同順序)。 
# sample_weight:類似于shape = [n_samples]的數(shù)組技羔,可選項(xiàng)僵闯,樣本權(quán)重。 
# digits:int藤滥,輸出浮點(diǎn)值的位數(shù).
def printing_Kfold_scores(x_train_data, y_train_data):
    fold = KFold(5, shuffle = False) #進(jìn)行k折交叉驗(yàn)證鳖粟,是否在將數(shù)據(jù)分成批之前進(jìn)行洗牌為否
# 不同的罰參數(shù)
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'])
    #          形成DataFrame結(jié)構(gòu)表  索引為五行兩列,列名為C_parameter , Mean recall score
    results_table['C_parameter'] = c_param_range  # 將罰參數(shù)賦給C_parameter這一列

    # 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.split(x_train_data)):

            # Call the logistic regression model with a certain C parameter
            lr = LogisticRegression(C = c_param, penalty = 'l1')  # 調(diào)用邏輯回歸拙绊,L1型罰函數(shù)

            # 利用訓(xùn)練數(shù)據(jù)擬合模型向图。在這種情況下,我們使用折疊部分來(lái)訓(xùn)練模型
            # 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())
            # rvavel(散開(kāi)标沪,解開(kāi))寿桨,flatten(變平)半火。兩者的區(qū)別在于返回拷貝(copy)還是返回視圖(view)微姊,
            #numpy.flatten()返回一份拷貝呕屎,對(duì)拷貝所做的修改不會(huì)影響(reflects)原始矩陣,
            # 而numpy.ravel()返回的是視圖趴梢,會(huì)影響(reflects)原始矩陣漠畜。
           
            # 使用訓(xùn)練數(shù)據(jù)中的測(cè)試指標(biāo)預(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)

        # The mean value of those recall scores is the metric we want to save and get hold of.
        results_table.loc[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'].astype('float64').idxmax()]['C_parameter']
     # 將召回率最大的罰參數(shù)輸出                                          
    # 最后坞靶,我們可以檢查選擇的C參數(shù)中哪個(gè)是最好的憔狞。
    print('*********************************************************************************')
    print('Best model to choose from cross validation is with C parameter = ', best_c)
    print('*********************************************************************************')
    
    return best_c

enumerate() 函數(shù)用于將一個(gè)可遍歷的數(shù)據(jù)對(duì)象(如列表、元組或字符串)組合為一個(gè)索引序列彰阴,同時(shí)列出數(shù)據(jù)和數(shù)據(jù)下標(biāo)瘾敢,

一般用在 for 循環(huán)當(dāng)中。
enumerate
import warnings
warnings.filterwarnings("ignore")  # 忽略警告
best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample) # 將欠采樣數(shù)據(jù)集傳入進(jìn)去
不同罰參數(shù)

不同罰參數(shù)

不同罰參數(shù)
def plot_confusion_matrix(cm, classes, title = "Confusion matrix", camp = plt.cm.Blues):     # 混淆矩陣
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], horizontalignment = "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ì)算混淆矩陣
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]))

# 繪制非標(biāo)準(zhǔn)化混淆矩陣
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cnf_matrix
                      , classes=class_names
                      , title='Confusion matrix')
plt.show()
Confusion matrix
best_c = printing_Kfold_scores(X_train,y_train)

C parameter: 0.01

Iteration 0 : recall score = 0.4925373134328358
Iteration 1 : recall score = 0.6027397260273972
Iteration 2 : recall score = 0.6833333333333333
Iteration 3 : recall score = 0.5692307692307692
Iteration 4 : recall score = 0.45

Mean recall score 0.5595682284048672


C parameter: 0.1

Iteration 0 : recall score = 0.5671641791044776
Iteration 1 : recall score = 0.6164383561643836
Iteration 2 : recall score = 0.6833333333333333
Iteration 3 : recall score = 0.5846153846153846
Iteration 4 : recall score = 0.525

Mean recall score 0.5953102506435158


C parameter: 1

Iteration 0 : recall score = 0.5522388059701493
Iteration 1 : recall score = 0.6164383561643836
Iteration 2 : recall score = 0.7166666666666667
Iteration 3 : recall score = 0.6153846153846154
Iteration 4 : recall score = 0.5625

Mean recall score 0.612645688837163


C parameter: 10

Iteration 0 : recall score = 0.5522388059701493
Iteration 1 : recall score = 0.6164383561643836
Iteration 2 : recall score = 0.7333333333333333
Iteration 3 : recall score = 0.6153846153846154
Iteration 4 : recall score = 0.575

Mean recall score 0.6184790221704963


C parameter: 100

Iteration 0 : recall score = 0.5522388059701493
Iteration 1 : recall score = 0.6164383561643836
Iteration 2 : recall score = 0.7333333333333333
Iteration 3 : recall score = 0.6153846153846154
Iteration 4 : recall score = 0.575

Mean recall score 0.6184790221704963


Best model to choose from cross validation is with C parameter = 10.0


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()

Recall metric in the testing dataset: 0.6190476190476191


image.png
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))

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 metric in the testing dataset: 1.0
Recall metric in the testing dataset: 1.0
Recall metric in the testing dataset: 1.0
Recall metric in the testing dataset: 0.9727891156462585
Recall metric in the testing dataset: 0.9387755102040817
Recall metric in the testing dataset: 0.8979591836734694
Recall metric in the testing dataset: 0.8367346938775511
Recall metric in the testing dataset: 0.782312925170068
Recall metric in the testing dataset: 0.5986394557823129


untitled.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末尿这,一起剝皮案震驚了整個(gè)濱河市簇抵,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌射众,老刑警劉巖碟摆,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異叨橱,居然都是意外死亡典蜕,警方通過(guò)查閱死者的電腦和手機(jī)断盛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)愉舔,“玉大人钢猛,你說(shuō)我怎么就攤上這事⌒停” “怎么了命迈?”我有些...
    開(kāi)封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)典奉。 經(jīng)常有香客問(wèn)我躺翻,道長(zhǎng),這世上最難降的妖魔是什么卫玖? 我笑而不...
    開(kāi)封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮踊淳,結(jié)果婚禮上假瞬,老公的妹妹穿的比我還像新娘。我一直安慰自己迂尝,他們只是感情好脱茉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著垄开,像睡著了一般琴许。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上溉躲,一...
    開(kāi)封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天榜田,我揣著相機(jī)與錄音,去河邊找鬼锻梳。 笑死箭券,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的疑枯。 我是一名探鬼主播辩块,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼荆永!你這毒婦竟也來(lái)了废亭?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤具钥,失蹤者是張志新(化名)和其女友劉穎豆村,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體氓拼,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡你画,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年抵碟,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坏匪。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡拟逮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出适滓,到底是詐尸還是另有隱情敦迄,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布凭迹,位于F島的核電站罚屋,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏嗅绸。R本人自食惡果不足惜脾猛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鱼鸠。 院中可真熱鬧猛拴,春花似錦、人聲如沸蚀狰。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)麻蹋。三九已至跛溉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間扮授,已是汗流浹背芳室。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留糙箍,地道東北人渤愁。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像深夯,于是被迫代替她去往敵國(guó)和親抖格。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

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

  • 錢咕晋,錢雹拄,錢,人人都要用到錢掌呜;錢滓玖,錢,錢质蕉,人人為了錢势篡,都努力向前翩肌;錢,錢禁悠,錢念祭,你有沒(méi)有賺到錢;錢碍侦,錢粱坤,錢,每天都要錢...
    沈姐說(shuō)說(shuō)閱讀 397評(píng)論 7 5
  • 【轉(zhuǎn)】正確使用 Android 性能分析工具——TraceView
    七點(diǎn)水Plus閱讀 148評(píng)論 0 0
  • 面對(duì)快速的知識(shí)迭代瓷产,我們要具備怎樣的學(xué)習(xí)能力站玄?
    德性826閱讀 128評(píng)論 0 0