60、AUC计算和ROC曲线画图

import random as rd
import matplotlib.pyplot as plt

def sample_generate(num_p, num_n):

    return [[rd.gauss(mu=0.6, sigma=0.2), 1] for _ in range(num_p)] + [[rd.gauss(mu=0.4, sigma=0.2), 0] for _ in range(num_n)]

def ROC_print(samples):

    samples.sort(key=lambda x: x[0], reverse=True)

    L_x = [0]
    L_y = [0]
    AUC = 0

    x, y = 0, 0
    for s in samples:
        if s[1] == 1:
            y += 1
        else:
            x += 1
            AUC += y
        L_x.append(x)
        L_y.append(y)

    L_x = [_/x for _ in L_x]
    L_y = [_ /y for _ in L_y]

    plt.step(L_x, L_y, c = "g")
    plt.plot([0,1], [0,1], c = "b")

    #坐标轴
    plt.grid(axis='x', color='0.95')
    plt.grid(axis='y', color='0.95')

    #title
    plt.title('ROC')
    plt.show()

    print("\nAUC:", AUC/x/y)


if __name__ == '__main__':

    samples = sample_generate(60, 40)
    ROC_print(samples)

 

你可能感兴趣的:(60、AUC计算和ROC曲线画图)