Python3入门机器学习 - 混淆矩阵、精准率、召回率

简介: 在分类问题中,预测准确度如果简单的用预测成功的概率来代表的话,有时候即使得到了99.9%的准确率,也不一定说明模型和算法就是好的,例如癌症问题,假如癌症的发病率只有0.

在分类问题中,预测准确度如果简单的用预测成功的概率来代表的话,有时候即使得到了99.9%的准确率,也不一定说明模型和算法就是好的,例如癌症问题,假如癌症的发病率只有0.01%,那么如果算法始终给出不得病的预测结果,也能达到很高的准确率

混淆矩阵


img_7af179ad667b5b395b64de7c007f4321.png
二分类问题的混淆矩阵

以癌症为例,0代表未患病,1代表患病,有10000个人:

img_28db30d9f8d221faf4ad8a829ad42aae.png
癌症问题的混淆矩阵


精准率和召唤率


img_823e86b38acaa22d1255385acf692d79.png

img_f73c02091f7f11e10880c19ad98a45e6.png
代码实现

#准备数据
import numpy as np
from sklearn import datasets

digits = datasets.load_digits()
X = digits['data']
y = digits['target'].copy()

#手动让digits数据集9的数据偏斜
y[digits['target']==9] = 1
y[digits['target']!=9] = 0

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=666)

log_reg = LogisticRegression()
log_reg.fit(X_train,y_train)
log_reg.score(X_test,y_test)

y_log_predict = log_reg.predict(X_test)
def TN(y_true,y_predict):
    return np.sum((y_true==0)&(y_predict==0))
TN(y_test,y_log_predict)

def FP(y_true,y_predict):
    return np.sum((y_true==0)&(y_predict==1))
FP(y_test,y_log_predict)

def FN(y_true,y_predict):
    return np.sum((y_true==1)&(y_predict==0))
FN(y_test,y_log_predict)

def TP(y_true,y_predict):
    return np.sum((y_true==1)&(y_predict==1))
TP(y_test,y_log_predict)

#构建混淆矩阵
def confusion_matrix(y_true,y_predict):
    return np.array([
        [TN(y_true,y_predict),FP(y_true,y_predict)],
        [FN(y_true,y_predict),TP(y_true,y_predict)]
    ])
confusion_matrix(y_test,y_log_predict)

#精准率
def precision_score(y_true,y_predict):
    tp = TP(y_true,y_predict)
    fp = FP(y_true,y_predict)
    try:
        return tp/(tp+fp)
    except:
        return 0.0
precision_score(y_test,y_log_predict)

#召回率
def recall_score(y_true,y_predict):
    tp = TP(y_true,y_predict)
    fn = FN(y_true,y_predict)
    try:
        return tp/(tp+fn)
    except:
        return 0.0
recall_score(y_test,y_log_predict)
scikitlearn中的精准率和召回率

#构建混淆矩阵
from sklearn.metrics import confusion_matrix
confusion_matrix(y_test,y_log_predict)

#精准率
from sklearn.metrics import precision_score
precision_score(y_test,y_log_predict)




调和平均值F1_score


调和平均数具有以下几个主要特点:
①调和平均数易受极端值的影响,且受极小值的影响比受极大值的影响更大。
②只要有一个标志值为0,就不能计算调和平均数。


img_aa33243819af23ec8567a61c5407e04f.png
调用sikit-learn中的f1_score
from sklearn.metrics import f1_score
f1_score(y_test,y_log_predict)
>>> 0.86






Precision-Recall的平衡


img_1819c424ff08d95f150ff13c622d29a1.png
一般来说,决策边界为theta.T*x_b=0,即计算出p>0.5时分类为1,如果我们手动改变这个threshold,就可以平移这个决策边界,改变精准率和召回率
#该函数可以得到log_reg的预测分数,未带入sigmoid
decsion_scores = log_reg.decision_function(X_test)

#将threshold由默认的0调为5
y_predict2 = decsion_scores>=5.0
precision_score(y_test,y_predict2)
>>> 0.96
recall_score(y_test,y_predict2)
>>> 0.5333333333333333

y_predict2 = decsion_scores>=-5.0
precision_score(y_test,y_predict2)
>>> 0.7272727272727273
recall_score(y_test,y_predict2)
>>> 0.8888888888888888
精准率和召回率曲线

可以用precisions-recalls曲线与坐标轴围成的面积衡量模型的好坏

from sklearn.metrics import precision_score
from sklearn.metrics import recall_score

thresholds = np.arange(np.min(decsion_scores),np.max(decsion_scores))
precisions = []
recalls = []

for threshold in thresholds:
    y_predict = decsion_scores>=threshold
    precisions.append(precision_score(y_test,y_predict))
    recalls.append(recall_score(y_test,y_predict))
import matplotlib.pyplot as plt

plt.plot(thresholds,precisions)
plt.plot(thresholds,recalls)
plt.show()
img_dc576daf2244e3413f9ddd0c863502db.png
plt.plot(precisions,recalls)
plt.show()
img_28c3ee4e6c9fedbc52fb6ccd73d91c57.png


使用scikit-learn绘制Precision-Recall曲线
from sklearn.metrics import precision_recall_curve
precisions,recalls,thresholds = precision_recall_curve(y_test,decsion_scores)

#由于precisions和recalls中比thresholds多了一个元素,因此要绘制曲线,先去掉这个元素
plt.plot(thresholds,precisions[:-1])
plt.plot(thresholds,recalls[:-1])
plt.show()
img_9de61c8edfaa477c724f566916edf7c1.png
由于scikit-learn中对于shelods的取值和上面用到的不一样,因此曲线图像略有不同




ROC曲线


ROC曲线用于描述TPR和FPR之间的关系


img_1b72f2f1aa7741ff1458d3e98b661cae.png
TPR定义
img_bacee7f939bdc409bd015d0c4a5ffb68.png
FPR定义
使用sikit-learn绘制ROC
from sklearn.metrics import roc_curve

fprs,tprs,thresholds = roc_curve(y_test,decsion_scores)
plt.plot(fprs,tprs)
img_40121c85cca83b382f18a9b5fec04a1a.png
横轴fpr,纵轴tpr

ROC曲线围成的面积越大,说明模型越好,不过ROC曲线没有Precision-Recall曲线那样对偏斜的数据的敏感性






多分类问题


#这次我们使用所有数据来进行逻辑回归的多分类问题的处理。
X = digits['data']
y = digits['target']
X_train,X_test,y_train,y_test = train_test_split(X,y)

log_reg = LogisticRegression()
log_reg.fit(X_train,y_train)
log_reg.score(X_test,y_test)
>>> 0.9577777777777777
scikit-learn中处理多分类问题的准确率
from sklearn.metrics import precision_score

#precision_score函数本身不能计算多分类问题,需要修改average参数
precision_score(y_test,y_predict,average='micro')
>>> 0.9577777777777777
多分类问题的混淆矩阵

多分类问题的混淆矩阵解读方式与二分类问题一致,第i行第j列的值就是真值为i、预测值为j的元素的数量

from sklearn.metrics import confusion_matrix

confusion_matrix(y_test,y_predict)
>>> array([[30,  0,  0,  0,  0,  0,  0,  1,  0,  0],
       [ 0, 43,  0,  2,  0,  0,  1,  0,  4,  0],
       [ 0,  0, 41,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0, 47,  0,  0,  0,  0,  0,  1],
       [ 0,  0,  0,  0, 46,  0,  0,  0,  0,  2],
       [ 0,  0,  0,  0,  0, 51,  0,  0,  0,  1],
       [ 0,  0,  0,  0,  0,  0, 38,  0,  1,  0],
       [ 0,  0,  0,  0,  0,  0,  0, 58,  0,  0],
       [ 0,  1,  0,  1,  1,  0,  0,  0, 37,  0],
       [ 0,  1,  0,  1,  0,  0,  0,  0,  1, 40]], dtype=int64)
绘制混淆矩阵
cfm = confusion_matrix(y_test,y_predict)
#cmap参数为绘制矩阵的颜色集合,这里使用灰度
plt.matshow(cfm,cmap=plt.cm.gray)
plt.show()
img_ab66431594470afbc9a10cc9534d7429.png
颜色越亮的地方代表数值越高
绘制错误率矩阵
#计算每一行的总值
row_sums = np.sum(cfm,axis=1)
err_matrix = cfm/row_sums
#对err_matrix矩阵的对角线置0,因为这是预测正确的部分,不关心
np.fill_diagonal(err_matrix,0)
err_matrix
>>> array([[0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.01724138, 0.        , 0.        ],
       [0.        , 0.        , 0.        , 0.04166667, 0.        ,
        0.        , 0.02564103, 0.        , 0.1       , 0.        ],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.02325581],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.04651163],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.02325581],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.025     , 0.        ],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.02      , 0.        , 0.02083333, 0.02083333,
        0.        , 0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.02      , 0.        , 0.02083333, 0.        ,
        0.        , 0.        , 0.        , 0.025     , 0.        ]])
plt.matshow(err_matrix,cmap=plt.cm.gray)
plt.show()
img_33627163cb4d93a85a9c62bfc57b717d.png
亮度越高的地方代表错误率越高
目录
相关文章
|
15天前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
124 1
|
2月前
|
API 数据安全/隐私保护 开发者
Python自定义异常:从入门到实践的轻松指南
在Python开发中,自定义异常能提升错误处理的精准度与代码可维护性。本文通过银行系统、电商库存等实例,详解如何创建和使用自定义异常,涵盖异常基础、进阶技巧、最佳实践与真实场景应用,助你写出更专业、易调试的代码。
105 0
|
2月前
|
IDE 开发工具 数据安全/隐私保护
Python循环嵌套:从入门到实战的完整指南
循环嵌套是Python中处理多维数据和复杂逻辑的重要工具。本文通过实例讲解嵌套循环的基本用法、常见组合、性能优化技巧及实战应用,帮助开发者掌握其核心思想,避免常见错误,并探索替代方案与进阶方向。
112 0
|
20天前
|
调度 数据库 Python
Python异步编程入门:asyncio让并发变得更简单
Python异步编程入门:asyncio让并发变得更简单
96 5
|
1月前
|
数据采集 存储 XML
Python爬虫入门(1)
在互联网时代,数据成为宝贵资源,Python凭借简洁语法和丰富库支持,成为编写网络爬虫的首选。本文介绍Python爬虫基础,涵盖请求发送、内容解析、数据存储等核心环节,并提供环境配置及实战示例,助你快速入门并掌握数据抓取技巧。
|
1月前
|
大数据 数据处理 数据安全/隐私保护
Python3 迭代器与生成器详解:从入门到实践
简介:本文深入解析Python中处理数据序列的利器——迭代器与生成器。通过通俗语言与实战案例,讲解其核心原理、自定义实现及大数据处理中的高效应用。
77 0
|
1月前
|
存储 缓存 安全
Python字典:从入门到精通的实用指南
Python字典如瑞士军刀般强大,以键值对实现高效数据存储与查找,广泛应用于配置管理、缓存、统计等场景。本文详解字典基础、进阶技巧、实战应用与常见陷阱,助你掌握这一核心数据结构,写出更高效、优雅的Python代码。
44 0
|
2月前
|
数据挖掘 数据处理 C++
Python Lambda:从入门到实战的轻量级函数指南
本文通过10个典型场景,详解Python中Lambda匿名函数的用法。Lambda适用于数据处理、排序、条件筛选、事件绑定等简洁逻辑,能提升代码简洁性和开发效率。同时提醒避免在复杂逻辑中过度使用。掌握Lambda,助你写出更高效的Python代码。
124 0
|
2月前
|
数据采集 Web App开发 JSON
Python爬虫基本原理与HTTP协议详解:从入门到实践
本文介绍了Python爬虫的核心知识,涵盖HTTP协议基础、请求与响应流程、常用库(如requests、BeautifulSoup)、反爬应对策略及实战案例(如爬取豆瓣电影Top250),帮助读者系统掌握数据采集技能。
196 0

热门文章

最新文章

推荐镜像

更多