美文网首页python数据分析与机器学习实战机器学习与数据挖掘
(二十八)项目实战|交易数据异常检测(三)-python数据分析

(二十八)项目实战|交易数据异常检测(三)-python数据分析

作者: 努力奋斗的durian | 来源:发表于2018-06-04 14:23 被阅读135次

    文章原创,最近更新:2018-06-4

    1.混淆矩阵

    课程来源: python数据分析与机器学习实战-唐宇迪

    课程资料:这里所涉及到的练习资料creditcard.csv相关的链接以及密码如下:
    链接: https://pan.baidu.com/s/1APgU4cTAaM9zb8_xAIc41Q 密码: xgg7

    这节课主要介绍什么叫混淆矩阵?


    混淆矩阵是由一个坐标系组成的,有x轴以及y轴,在x轴里面有0和1,在y轴里面有0和1.x轴表达的是预测的值,y轴表达的是真实的值.可以对比真实值与预测值之间的差异,可以计算当前模型衡量的指标值.

    之前有提到recall=TP/(TP+FN),在这里的表示具体如下:



    这里也可以衡量精度等于多少?
    真实是0,预测也是0,等到的结果是129;真实是1,预测也是1,等到的结果是137.精确度=(129+137)/(129+20+10+137)

    从上面可以看出,混淆矩阵可以看出一些指标.比如精确值以及recall值.

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

    输出结果为:

    Recall metric in the testing dataset:  0.931972789116
    

    混淆矩阵是在什么样的条件下进行计算的呢?在下采样数据集,样本数量比较小,大概有200多个样本,进行小规模的测试,还没有在大规模的数据进行测试.

    其实之前有提到,数据衡量的时候应该在原始的数据集上,所以不光只在下采样数据集进行测试,还要在原始的数据集进行测试.原始的数据大概有8万多条数据,因此还要在原始的数据集进行操作.


    首先我们计算原始数据的recall值,

    recall=TP/(TP+FN)=135/(135+12)=91%,recall值比较偏高.

    这里的recall值偏高,那这里的数据有没有什么问题呢?对角线的数据76715以及135都是预测对的数据.这里的8581指的是本来没有异常发生的,然后误抓出来了,为了检测到135个样本,把额外的8581个样本也抓出来了,说它也是异常的.这种情况下,显然不会影响我们的recall值,但是会使精度偏低,从实际的角度来看,使我们的工作量也增大了,虽然找出了135个欺诈行为的样本,但是也找出了8581个无辜的样本.

    找出样本之后,需要对实际进行分析,确保确实是异常的,但是有8581个无辜的样本,那应该怎么办呢?因此下采样数据,虽然recall值能够达到标准,但是误杀有点太多.这个误杀已经超过容忍范围,那应该怎么解决这个问题呢?下采样会出现这样的问题,那么过采样是否效果会更好一些呢?

    刚才用了下采样数据集进行了建模的操作,然后得到一些recall的结果值.如果对一个数据集的0和1什么都不做,直接拿出来模型的建立,效果到底会有多差呢?效果到底是怎么样的呢?如果不用过采样以及下采样,直接拿原始的数据集进行交叉验证.

    从输出结果可以看出,在样本数据不均衡的情况下,如果什么都不做,模型的效果是不如下采样的模型数据集.这里的recall值只有62%,模型效果并不好.

    lr = LogisticRegression(C = best_c, penalty = 'l1')
    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.918367346939
    
    best_c = printing_Kfold_scores(X_train,y_train)
    

    输出结果为:

    -------------------------------------------
    C parameter:  0.01
    -------------------------------------------
    
    Iteration  1 : recall score =  0.492537313433
    Iteration  2 : recall score =  0.602739726027
    Iteration  3 : recall score =  0.683333333333
    Iteration  4 : recall score =  0.569230769231
    Iteration  5 : recall score =  0.45
    
    Mean recall score  0.559568228405
    
    -------------------------------------------
    C parameter:  0.1
    -------------------------------------------
    
    Iteration  1 : recall score =  0.567164179104
    Iteration  2 : recall score =  0.616438356164
    Iteration  3 : recall score =  0.683333333333
    Iteration  4 : recall score =  0.584615384615
    Iteration  5 : recall score =  0.525
    
    Mean recall score  0.595310250644
    
    -------------------------------------------
    C parameter:  1
    -------------------------------------------
    
    Iteration  1 : recall score =  0.55223880597
    Iteration  2 : recall score =  0.616438356164
    Iteration  3 : recall score =  0.716666666667
    Iteration  4 : recall score =  0.615384615385
    Iteration  5 : recall score =  0.5625
    
    Mean recall score  0.612645688837
    
    -------------------------------------------
    C parameter:  10
    -------------------------------------------
    
    Iteration  1 : recall score =  0.55223880597
    Iteration  2 : recall score =  0.616438356164
    Iteration  3 : recall score =  0.733333333333
    Iteration  4 : recall score =  0.615384615385
    Iteration  5 : recall score =  0.575
    
    Mean recall score  0.61847902217
    
    -------------------------------------------
    C parameter:  100
    -------------------------------------------
    
    Iteration  1 : recall score =  0.55223880597
    Iteration  2 : recall score =  0.616438356164
    Iteration  3 : recall score =  0.733333333333
    Iteration  4 : recall score =  0.615384615385
    Iteration  5 : recall score =  0.575
    
    Mean recall score  0.61847902217
    
    *********************************************************************************
    Best model to choose from cross validation is with C parameter =  10.0
    *********************************************************************************
    

    相关文章

      网友评论

      • 知识学者:好厉害,给大佬跪了.
        努力奋斗的durian:@东风冷雪 我也是看得超级痛苦的:fearful:,但是坚持看下去,等过了一段时间熟悉了,就会好很多的。当时学python 也是这样过来的。加油,无论如何都要坚持下去,久了,就会熟悉的:smile:

      本文标题:(二十八)项目实战|交易数据异常检测(三)-python数据分析

      本文链接:https://www.haomeiwen.com/subject/shwesftx.html