Python | CAP - 累积精度曲线分析案例

CAP通常被称为"累积精度曲线",用于分类模型的性能评估。它有助于我们理解和总结分类模型的鲁棒性。为了直观地显示这一点,我们在图中绘制了三条不同的曲线:

  1. 一个随机的曲线(random)
  2. 通过使用随机森林分类器获得的曲线(forest)
  3. 理论上完美的曲线(perfect)

案例分析

加载数据集

python 复制代码
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
 
# loading dataset
data = pd.read_csv('Social_Network_Ads.csv')
 
print ("Data Head : \n\n", data.head())

输出

python 复制代码
Data Head : 

     User ID  Gender  Age  EstimatedSalary  Purchased
0  15624510    Male   19            19000          0
1  15810944    Male   35            20000          0
2  15668575  Female   26            43000          0
3  15603246  Female   27            57000          0
4  15804002    Male   19            76000          0

数据输入输出

python 复制代码
# Input and Output
x = data.iloc[:, 2:4]
y = data.iloc[:, 4]
 
print ("Input : \n", x.iloc[0:10, :])

输出

python 复制代码
Input : 
    Age  EstimatedSalary
0   19            19000
1   35            20000
2   26            43000
3   27            57000
4   19            76000
5   27            58000
6   27            84000
7   32           150000
8   25            33000
9   35            65000

划分训练和测试数据集

python 复制代码
# splitting data
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(
        x, y, test_size = 0.3, random_state = 0)

随机森林分类器

python 复制代码
# classifier
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 400)
 
# training
classifier.fit(x_train, y_train)
 
# predicting
pred = classifier.predict(x_test)

分类器性能评估

python 复制代码
# Model Performance
from sklearn.metrics import accuracy_score
print("Accuracy : ", accuracy_score(y_test, pred) *  100)

输出

python 复制代码
Accuracy :  91.66666666666666

随机模型

随机图是在假设我们已经绘制了从0到数据集中数据点总数的点的情况下绘制的。y轴保持为数据集中因变量结果为1的点的总数。随机图可以理解为线性增加的关系。举个例子,一个模型,预测是否购买产品(积极的结果)的每个人从一组人(分类参数)的因素,如他们的性别,年龄,收入等,如果组成员将被随机联系,销售的产品的累计数量将线性上升到最大值对应的总人数在组内的买家。这种分布称为"随机"CAP。

代码示例

python 复制代码
# code for the random plot
import matplotlib.pyplot as plt
import numpy as np
 
# length of the test data
total = len(y_test)
 
# Counting '1' labels in test data
one_count = np.sum(y_test)
 
# counting '0' labels in test data 
zero_count = total - one_count
 
plt.figure(figsize = (10, 6))
 
# x-axis ranges from 0 to total people contacted 
# y-axis ranges from 0 to the total positive outcomes.
 
plt.plot([0, total], [0, one_count], c = 'b', 
         linestyle = '--', label = 'Random Model')
plt.legend()

输出

随机森林分类器

代码:随机森林分类算法应用于数据集,并绘图。

python 复制代码
lm = [y for _, y in sorted(zip(pred, y_test), reverse = True)]
x = np.arange(0, total + 1)
y = np.append([0], np.cumsum(lm))
plt.plot(x, y, c = 'b', label = 'Random classifier', linewidth = 2)

输出

说明:pred是随机分类器做出的预测。我们压缩预测值和测试值,并以相反的顺序对其进行排序,以便先出现较高的值,然后是较低值。我们只提取数组中的y_test值并将其存储在lm中。np.cumsum()创建一个值数组,同时将数组中以前的所有值累积添加到当前值。x值的范围将从0到总和+1。我们在总数上加1,因为arange()不包含数组中的1,我们希望x轴的范围从0到总数。

完美模型

然后我们绘制完美的图(或理想的曲线)。一个完美的预测准确地确定了哪些组成员将购买产品,这样,最大数量的产品销售将达到最低数量的呼叫。这会在CAP曲线上产生一条陡峭的线,一旦达到最大值(联系所有其他组成员不会导致更多产品销售),这就是"完美"CAP。

python 复制代码
plt.plot([0, one_count, total], [0, one_count, one_count],
         c = 'grey', linewidth = 2, label = 'Perfect Model')

说明:一个完美的模型会在相同的尝试次数中找到积极的结果。在我们的数据集中,我们总共有41个积极的结果,所以在41个时,达到了最大值。

最终分析

在任何情况下,我们的分类器算法都不应该产生一条位于随机线下面的线。在这种情况下,它被认为是一个非常糟糕的模型。由于绘制的分类器线接近理想线,我们可以说我们的模型非常适合。取完美图下的面积,称之为aP。取预测模型下的面积,称之为aR。然后将比率取为aR/aP。这个比率称为准确率。值越接近1,模型越好。这是一种分析方法。

另一种分析方法是从预测模型上的轴的大约50%投影一条线,并将其投影到y轴上。假设我们得到的投影值为X%。

-> 60% :这是一个非常糟糕的模型

-> 60%<X<70%:这仍然是一个糟糕的模型,但明显优于第一种情况

-> 70%<X<80%:这是一个很好的模型

-> 80%<X<90%:这是一个非常好的模型

-> 90%<X<100%:非常好,可能是过拟合的情况之一。

因此,根据这个分析,我们可以确定我们的模型有多准确。

相关推荐
思则变1 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络1 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find3 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取4 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector5 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习5 小时前
Python入门Day2
开发语言·python
Vertira6 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉6 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗6 小时前
黑马python(二十四)
开发语言·python
晓13137 小时前
OpenCV篇——项目(二)OCR文档扫描
人工智能·python·opencv·pycharm·ocr