数据挖掘

Python画CAP曲线,计算AR值

2020-08-19  本文已影响0人  xiaogp

听别人分享提到了CAP曲线,网上资料比较少,自己动手实践一发

CAP曲线和AR值的含义

cap曲线.png

数据输入

输入:predictions, labels,cut_point

predictions: 为每条样本的预测值组成的集合,预测概率在0-1之间
labels: 为每条样本的真实值(0, 1)组成的集合,本例中1是坏客户
cut_point: KS的阈值分割点的数量

数据预览,左列labels,右列predictions

head -4 test_predict_res.txt
0.0 0.831193
0.0 0.088209815
1.0 0.93411493
0.0 0.022157196

python代码实现

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

matplotlib.rcParams["font.sans-serif"] = ["SimHei"]

def cap_plot(predictions, labels, cut_point=100):
    sample_size = len(labels)
    bad_label_size = len([i for i in labels if i == 1])
    score_thres = np.linspace(1, 0, cut_point)
    x_list = []
    y_list = []
    for thres in score_thres:
        # 阈值以上的样本数 / 总样本数
        x = len([i for i in predictions if i >= thres])
        x_list.append(x / sample_size)
        # 阈值以上的样本真实为坏客户的样本数 / 总坏客户样本数
        y = len([(i, j) for i, j in zip(predictions, labels) if i >= thres and j == 1])
        y_list.append(y / bad_label_size)

    # 绘制实际曲线
    plt.plot(x_list, y_list, color="green", label="实际曲线")
    
    # 绘制最优曲线
    best_point = [bad_label_size / sample_size, 1]
    plt.plot([0, best_point[0], 1], [0, best_point[1], 1], color="red", label="最优曲线", zorder=10)
    # 增加最优情况的点的坐标
    plt.scatter(best_point[0], 1, color="white", edgecolors="red", s=30, zorder=30)
    plt.text(best_point[0] + 0.1, 0.95, "{}/{},{}".format(bad_label_size, sample_size, 1), ha="center", va="center")
    
    # 随机曲线
    plt.plot([0, 1], [0, 1], color="gray", linestyle="--", label="随机曲线")
    
    # 颜色填充
    plt.fill_between(x_list, y_list, x_list, color="yellow", alpha=0.3)
    plt.fill_between(x_list, [1 if i * sample_size / bad_label_size >= 1 else i * sample_size / bad_label_size for i in x_list], y_list, color="gray", alpha=0.3)

    # 计算AR值
    # 实际曲线下面积
    actual_area = np.trapz(y_list, x_list) - 1 * 1 / 2
    best_area = 1 * 1 / 2 - 1 * bad_label_size / sample_size / 2
    ar_value = actual_area / best_area
    plt.title("CAP曲线 AR={:.3f}".format(ar_value))

    plt.legend(loc=4)
    plt.grid()
    plt.show()

if __name__ == "__main__":
    # 读取预测数据和真实标签
    labels = []
    predictions = []
    with open("test_predict_res.txt", "r", encoding="utf8") as f:
        for line in f.readlines()
            labels.append(float(line.strip().split()[0]))
            predictions.append(float(line.strip().split()[1]))

    cap_plot(predictions, labels)

python画cap曲线,计算AR值.png

cap曲线和AR值的解释

模型预测坏客户/企业的能力较好,和最优模型的接近程度为0.81

上一篇 下一篇

猜你喜欢

热点阅读