项目实战-交易数据异常检测

项目实战-交易数据异常检测

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

%matplotlib inline
data = pd.read_csv("creditcard.csv")
data.head()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LnRT9334-1641812668776)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\08项目实战-交易数据异常检测\笔记图片\image-20220110183127362.png)]

# value_counts计算当前数据的某一列有多少个不同的属性值
count_classes = pd.value_counts(data['Class'], sort = True).sort_index()
# kind = 'bar'条形图
count_classes.plot(kind = 'bar')
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JctHq3LZ-1641812668778)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\08项目实战-交易数据异常检测\笔记图片\image-20220110183224025.png)]

可以观察出样本分布很不规则。解决这种问题的两种方案就是:过采样,下采样 下采样:可以让0和1的数量一样少。 过采样:在1号样本的数据中进行生成,生成出的数据跟0号样本一样多。

# 预处理
from sklearn.preprocessing import StandardScaler

# reshape(-1, 1)这个-1是让编译器自动计算;这里不能直接reshape,应该是.values.reshape
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1))
# 去掉这两列
data = data.drop(['Time','Amount'],axis=1)
data.head()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IxPEdr3J-1641812668778)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\08项目实战-交易数据异常检测\笔记图片\image-20220110183302857.png)]

# 下采样
# 数据选择
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']

# Number of data points in the minority class
number_records_fraud = len(data[data.Class == 1])
fraud_indices = np.array(data[data.Class == 1].index)

# Picking the indices of the normal classes
normal_indices = data[data.Class == 0].index

# Out of the indices we picked, randomly select "x" number (number_records_fraud)
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices)

# Appending the 2 indices
under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])

# Under sample dataset
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']

# Showing ratio
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))

Percentage of normal transactions: 0.5
Percentage of fraud transactions: 0.5
Total number of transactions in resampled data: 984

# 交叉验证
#from sklearn.cross_validation import train_test_split 
# sklearn.cross_validation这个包已经不再使用了,被划分到model_selection这个包做交叉验证
from sklearn.model_selection import train_test_split


# Whole dataset
# 切分完整的数据集
# test_size指的是切分的比例,30%是测试集,70%是训练集;
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))

# 切分下采样数据集
# 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_test_undersample))
print("Total number of transactions: ", len(X_train_undersample)+len(X_test_undersample))

Number transactions train dataset: 199364
Number transactions test dataset: 85443
Total number of transactions: 284807

Number transactions train dataset: 688
Number transactions test dataset: 296
Total number of transactions: 984

#Recall = TP/(TP+FN)
# Recall召回率、查全率,检测模型的效果
from sklearn.linear_model import LogisticRegression
# 第一处报错修改成model_selection
from sklearn.model_selection 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):
    #第二处报错修改,去掉len(y_train_data)这个参数
    fold = KFold(5,shuffle=False) 

    # Different C parameters
    # 惩罚参数
    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 = []
        # 第三处报错,enumerate(fold,start=1)修改成如下
        for iteration, indices in enumerate(fold.split(y_train_data),start=1):

            # Call the logistic regression model with a certain C parameter
            # 第五处报错,添加solver='liblinear'
            lr = LogisticRegression(C = c_param, penalty = 'l1',solver='liblinear')

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

            # Predict values using the test indices in the training data
            y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)

            # Calculate the recall score and append it to a list for recall scores representing the current 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.ix[j,'Mean recall score'] = np.mean(recall_accs)
        j += 1
        print('')
        print('Mean recall score ', np.mean(recall_accs))
        print('')
    
    # 第四处报错,在.idxmax()的前面添加.astype("float64")
    best_c = results_table.loc[results_table['Mean recall score'].astype("float64").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)
-------------------------------------------
C parameter:  0.01
-------------------------------------------

Iteration  1 : recall score =  0.9315068493150684
Iteration  2 : recall score =  0.9178082191780822
Iteration  3 : recall score =  0.9830508474576272
Iteration  4 : recall score =  0.9594594594594594
Iteration  5 : recall score =  0.9545454545454546

Mean recall score  0.9492741659911385

-------------------------------------------
C parameter:  0.1
-------------------------------------------

Iteration  1 : recall score =  0.8493150684931506
Iteration  2 : recall score =  0.863013698630137
Iteration  3 : recall score =  0.9152542372881356
Iteration  4 : recall score =  0.9324324324324325
Iteration  5 : recall score =  0.8939393939393939

Mean recall score  0.89079096615665

-------------------------------------------
C parameter:  1
-------------------------------------------

Iteration  1 : recall score =  0.863013698630137
Iteration  2 : recall score =  0.8904109589041096
Iteration  3 : recall score =  0.9661016949152542
Iteration  4 : recall score =  0.9324324324324325
Iteration  5 : recall score =  0.9090909090909091

Mean recall score  0.9122099387945685

-------------------------------------------
C parameter:  10
-------------------------------------------

Iteration  1 : recall score =  0.8767123287671232
Iteration  2 : recall score =  0.8904109589041096
Iteration  3 : recall score =  0.9661016949152542
Iteration  4 : recall score =  0.9459459459459459
Iteration  5 : recall score =  0.9393939393939394

Mean recall score  0.9237129735852745

-------------------------------------------
C parameter:  100
-------------------------------------------

Iteration  1 : recall score =  0.8767123287671232
Iteration  2 : recall score =  0.8904109589041096
Iteration  3 : recall score =  0.9661016949152542
Iteration  4 : recall score =  0.9459459459459459
Iteration  5 : recall score =  0.9242424242424242

Mean recall score  0.9206826705549714

*********************************************************************************
Best model to choose from cross validation is with C parameter =  0.01
*********************************************************************************
# 混淆矩阵
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',solver='liblinear')
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()

Recall metric in the testing dataset: 0.9251700680272109

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-D8pVrGrr-1641812668779)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\08项目实战-交易数据异常检测\笔记图片\image-20220110183522088.png)]

# 全部数据集
lr = LogisticRegression(C = best_c, penalty = 'l1',solver='liblinear')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred = lr.predict(X_test.values)

# Compute confusion matrix
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()

Recall metric in the testing dataset: 0.9115646258503401

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s7oHP1ei-1641812668780)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\08项目实战-交易数据异常检测\笔记图片\image-20220110183554549.png)]

# 如果原始数据没有采样操作,直接用最开始的样本不均衡的数据,实验的模型效果很差
best_c = printing_Kfold_scores(X_train,y_train)
-------------------------------------------
C parameter:  0.01
-------------------------------------------
Iteration  1 : recall score =  0.4925373134328358
Iteration  2 : recall score =  0.6027397260273972
Iteration  3 : recall score =  0.6833333333333333
Iteration  4 : recall score =  0.5692307692307692
Iteration  5 : recall score =  0.45

Mean recall score  0.5595682284048672

-------------------------------------------
C parameter:  0.1
-------------------------------------------
Iteration  1 : recall score =  0.5671641791044776
Iteration  2 : recall score =  0.6164383561643836
Iteration  3 : recall score =  0.6833333333333333
Iteration  4 : recall score =  0.5846153846153846
Iteration  5 : recall score =  0.525

Mean recall score  0.5953102506435158

-------------------------------------------
C parameter:  1
-------------------------------------------
Iteration  1 : recall score =  0.5522388059701493

Iteration  2 : recall score =  0.6164383561643836

Iteration  3 : recall score =  0.7166666666666667

Iteration  4 : recall score =  0.6153846153846154
Iteration  5 : recall score =  0.5625
Mean recall score  0.612645688837163

-------------------------------------------
C parameter:  10
-------------------------------------------
Iteration  1 : recall score =  0.5522388059701493
Iteration  2 : recall score =  0.6164383561643836
Iteration  3 : recall score =  0.7333333333333333
Iteration  4 : recall score =  0.6153846153846154
Iteration  5 : recall score =  0.575

Mean recall score  0.6184790221704963

-------------------------------------------
C parameter:  100
-------------------------------------------

Iteration  1 : recall score =  0.5522388059701493

Iteration  2 : recall score =  0.6164383561643836

Iteration  3 : recall score =  0.7333333333333333
Iteration  4 : recall score =  0.6153846153846154
Iteration  5 : 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 = 0.01, penalty = 'l1',solver='liblinear')
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.9251700680272109
Recall metric in the testing dataset: 0.8639455782312925
Recall metric in the testing dataset: 0.8163265306122449
Recall metric in the testing dataset: 0.7687074829931972
Recall metric in the testing dataset: 0.5782312925170068

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7hCZJefN-1641812668780)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\08项目实战-交易数据异常检测\笔记图片\QQ图片20220110185820.png)]

# SMOTE样本生成策略(过采样)
import pandas as pd
# 这里会报错,需要安装,执行命令pip install imblearn
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)
# 会出错,将fit_sample改为fit_resample
# 传入训练集的x,y,自动平衡
os_features,os_labels=oversampler.fit_resample(features_train,labels_train)
len(os_labels[os_labels==1])

227454

os_features = pd.DataFrame(os_features)
os_labels = pd.DataFrame(os_labels)
best_c = printing_Kfold_scores(os_features,os_labels)
-------------------------------------------
C parameter:  0.01
-------------------------------------------

Iteration  1 : recall score =  0.8903225806451613

Iteration  2 : recall score =  0.8947368421052632

Iteration  3 : recall score =  0.9688170853159235

Iteration  4 : recall score =  0.9578483419615085

Iteration  5 : recall score =  0.9585407942317626

Mean recall score  0.9340531288519237

-------------------------------------------
C parameter:  0.1
-------------------------------------------

Iteration  1 : recall score =  0.8903225806451613

Iteration  2 : recall score =  0.8947368421052632

Iteration  3 : recall score =  0.9704105344694036

Iteration  4 : recall score =  0.9596728987370989

Iteration  5 : recall score =  0.9604752640661237

Mean recall score  0.93512362400461

-------------------------------------------
C parameter:  1
-------------------------------------------

Iteration  1 : recall score =  0.8903225806451613

Iteration  2 : recall score =  0.8947368421052632

Iteration  3 : recall score =  0.9704769281841319

Iteration  4 : recall score =  0.9600356118310417

Iteration  5 : recall score =  0.9607940119365582

Mean recall score  0.9352731949404312

-------------------------------------------
C parameter:  10
-------------------------------------------

Iteration  1 : recall score =  0.8903225806451613

Iteration  2 : recall score =  0.8947368421052632

Iteration  3 : recall score =  0.9705654531371031

Iteration  4 : recall score =  0.9541332805750651

Iteration  5 : recall score =  0.9607170727954188

Mean recall score  0.9340950458516023

-------------------------------------------
C parameter:  100
-------------------------------------------

Iteration  1 : recall score =  0.8903225806451613

Iteration  2 : recall score =  0.8947368421052632

Iteration  3 : recall score =  0.9705433218988603

Iteration  4 : recall score =  0.9585627768435168
Iteration  5 : recall score =  0.9608599597718205

Mean recall score  0.9350050962529244

*********************************************************************************
Best model to choose from cross validation is with C parameter =  1.0
*********************************************************************************
lr = LogisticRegression(C = best_c, penalty = 'l1',solver='liblinear')
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()

Recall metric in the testing dataset: 0.9108910891089109

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GBSQ8JfO-1641812668781)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\08项目实战-交易数据异常检测\笔记图片\image-20220110190221462.png)]

问题解决

做这个项目的时候遇到几个问题,以下是解决方案
ModuleNotFoundError: No module named 'sklearn.cross_validation’
https://blog.csdn.net/weixin_40283816/article/details/83242777
TypeError: init() got multiple values for argument 'shuffle’
https://blog.csdn.net/weixin_40283816/article/details/83242777
TypeError:‘KFold’ object is not iterable
https://blog.csdn.net/weixin_40283816/article/details/83242777
ValueError: Solver lbfgs supports only ‘l2’ or ‘none’ penalties, got l1 pena https://www.cnblogs.com/peijz/p/13611602.html
TypeError: reduction operation ‘argmax’ not allowed for this dtype
https://www.cnblogs.com/hum0ro/p/9696418.html

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值