代码之家  ›  专栏  ›  技术社区  ›  blue-sky

如何读取ROC曲线并设置自定义阈值?

  •  1
  • blue-sky  · 技术社区  · 7 年前

    from sklearn import metrics
    import numpy as np
    import matplotlib.pyplot as plt
    
    y_true = [1,0,0]
    y_predict = [.6,.1,.1]
    
    fpr, tpr, thresholds = metrics.roc_curve(y_true, y_predict , pos_label=1)
    
    print(fpr)
    print(tpr)
    print(thresholds)
    
    # Print ROC curve
    plt.plot(fpr,tpr)
    plt.show()
    
    
    y_true = [1,0,0]
    y_predict = [.6,.1,.6]
    
    fpr, tpr, thresholds = metrics.roc_curve(y_true, y_predict , pos_label=1)
    
    print(fpr)
    print(tpr)
    print(thresholds)
    
    # Print ROC curve
    plt.plot(fpr,tpr)
    plt.show()
    

    enter image description here

    例如,对于值:

    y_true = [1,0,0]
    y_predict = [.6,.1,.6]
    

    返回以下阈值:

    [1.6 0.6 0.1]
    

    更新:

    https://sachinkalsi.github.io/blog/category/ml/2018/08/20/top-8-performance-metrics-one-should-know.html#receiver-operating-characteristic-curve-roc

    from sklearn import metrics
    import numpy as np
    import matplotlib.pyplot as plt
    
    y_true = [1,1,1,0]
    y_predict = [.94,.87,.83,.80]
    
    fpr, tpr, thresholds = metrics.roc_curve(y_true, y_predict , pos_label=1)
    
    print('false positive rate:', fpr)
    print('true positive rate:', tpr)
    print('thresholds:', thresholds)
    
    # Print ROC curve
    plt.plot(fpr,tpr)
    plt.show()
    

    它产生了这个图:

    enter image description here

    绘图与博客中引用的绘图不同,阈值也不同:

    enter image description here

    另外,使用scikit返回的阈值 metrics.roc_curve 实施内容包括: thresholds: [0.94 0.83 0.8 ] . scikit是否应该返回与使用相同点时相似的roc曲线?我应该自己实现roc曲线,而不是依赖scikit实现,因为结果是不同的?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Kalsi    7 年前

    阈值不会出现在ROC曲线中。scikit learn文档说:

    thresholds[0]表示没有被预测的实例,并且被任意设置为max(y\u score)+1

    如果 y_predict 0.3, 0.5, 0.7 ,则这些阈值将由 metrics.roc_curve

    通常在计算时遵循这些步骤 ROC 曲线

    1.排序 你能预测吗 按降序排列。

    你能预测吗 ,如果 你能预测吗

    附笔: 如果我们有N个数据点,那么我们将有N个阈值(如果 y_true 你能预测吗 是独一无二的)

    y_predicted

    N (数据点数量)TPR、FPR对

    this blog 有关详细信息