文章目录

  • 目录
    • 模型评估
    • 评价指标
    • 1.分类评价指标
      • acc、recall、F1、混淆矩阵、分类综合报告
        • 1.准确率
          • 方式一:accuracy_score
          • 方式二:metrics
        • 2.召回率
        • 3.F1分数
        • 4.混淆矩阵
        • 5.分类报告
        • 6.kappa score
      • ROC
        • 1.ROC计算
        • 2.ROC曲线
        • 3.具体实例
    • 2.回归评价指标
    • 3.聚类评价指标
      • 1.Adjusted Rand index 调整兰德系数
      • 2.Mutual Information based scores 互信息
      • 3.Homogeneity, completeness and V-measure
      • 4.Fowlkes-Mallows scores
      • 5.Silhouette Coefficient 轮廓系数
      • 6.Calinski-Harabaz Index
    • 4.其他

目录

模型评估

有三种不同的方法来评估一个模型的预测质量:

  • estimator的score方法:sklearn中的estimator都具有一个score方法,它提供了一个缺省的评估法则来解决问题。
  • Scoring参数:使用cross-validation的模型评估工具,依赖于内部的scoring策略。见下。
  • 通过测试集上评估预测误差:sklearn Metric函数用来评估预测误差。

评价指标

评价指标针对不同的机器学习任务有不同的指标,同一任务也有不同侧重点的评价指标。
主要有分类(classification)、回归(regression)、排序(ranking)、聚类(clustering)、热门主题模型(topic modeling)、推荐(recommendation)等。

1.分类评价指标

acc、recall、F1、混淆矩阵、分类综合报告

1.准确率

方式一:accuracy_score
# 准确率
import numpy as np
from sklearn.metrics import accuracy_score
y_pred = [0, 2, 1, 3,9,9,8,5,8]
y_true = [0, 1, 2, 3,2,6,3,5,9]accuracy_score(y_true, y_pred)
Out[127]: 0.33333333333333331accuracy_score(y_true, y_pred, normalize=False)  # 类似海明距离,每个类别求准确后,再求微平均
Out[128]: 3
方式二:metrics

宏平均比微平均更合理,但也不是说微平均一无是处,具体使用哪种评测机制,还是要取决于数据集中样本分布

宏平均(Macro-averaging),是先对每一个类统计指标值,然后在对所有类求算术平均值。
微平均(Micro-averaging),是对数据集中的每一个实例不分类别进行统计建立全局混淆矩阵,然后计算相应指标。参考博客

from sklearn import metrics
metrics.precision_score(y_true, y_pred, average='micro')  # 微平均,精确率
Out[130]: 0.33333333333333331metrics.precision_score(y_true, y_pred, average='macro')  # 宏平均,精确率
Out[131]: 0.375metrics.precision_score(y_true, y_pred, labels=[0, 1, 2, 3], average='macro')  # 指定特定分类标签的精确率
Out[133]: 0.5

其中average参数有五种:(None, ‘micro’, ‘macro’, ‘weighted’, ‘samples’)

2.召回率

metrics.recall_score(y_true, y_pred, average='micro')
Out[134]: 0.33333333333333331metrics.recall_score(y_true, y_pred, average='macro')
Out[135]: 0.3125

3.F1分数

metrics.f1_score(y_true, y_pred, average='weighted')
Out[136]: 0.37037037037037035

4.混淆矩阵

# 混淆矩阵
from sklearn.metrics import confusion_matrix
confusion_matrix(y_true, y_pred)Out[137]:
array([[1, 0, 0, ..., 0, 0, 0],[0, 0, 1, ..., 0, 0, 0],[0, 1, 0, ..., 0, 0, 1],..., [0, 0, 0, ..., 0, 0, 1],[0, 0, 0, ..., 0, 0, 0],[0, 0, 0, ..., 0, 1, 0]])

横为true label 竖为predict

5.分类报告

# 分类报告:precision/recall/fi-score/均值/分类个数from sklearn.metrics import classification_reporty_true = [0, 1, 2, 2, 0]y_pred = [0, 0, 2, 2, 0]target_names = ['class 0', 'class 1', 'class 2']print(classification_report(y_true, y_pred, target_names=target_names))

包含:precision/recall/fi-score/均值/分类个数

6.kappa score

kappa score是一个介于(-1, 1)之间的数. score>0.8意味着好的分类;0或更低意味着不好(实际是随机标签)

 from sklearn.metrics import cohen_kappa_scorey_true = [2, 0, 2, 2, 0, 1]y_pred = [0, 0, 2, 2, 0, 2]cohen_kappa_score(y_true, y_pred)

ROC

1.ROC计算

import numpy as npfrom sklearn.metrics import roc_auc_scorey_true = np.array([0, 0, 1, 1])y_scores = np.array([0.1, 0.4, 0.35, 0.8])roc_auc_score(y_true, y_scores)

2.ROC曲线

 y = np.array([1, 1, 2, 2])scores = np.array([0.1, 0.4, 0.35, 0.8])fpr, tpr, thresholds = roc_curve(y, scores, pos_label=2)

3.具体实例

import numpy as np
import matplotlib.pyplot as plt
from itertools import cyclefrom sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from scipy import interp# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target# 画图
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):mean_tpr += interp(all_fpr, fpr[i], tpr[i])# Finally average it and compute AUC
mean_tpr /= n_classesfpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])# Plot all ROC curves
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],label='micro-average ROC curve (area = {0:0.2f})'''.format(roc_auc["micro"]),color='deeppink', linestyle=':', linewidth=4)plt.plot(fpr["macro"], tpr["macro"],label='macro-average ROC curve (area = {0:0.2f})'''.format(roc_auc["macro"]),color='navy', linestyle=':', linewidth=4)colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i, color in zip(range(n_classes), colors):plt.plot(fpr[i], tpr[i], color=color, lw=lw,label='ROC curve of class {0} (area = {1:0.2f})'''.format(i, roc_auc[i]))plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()

2.回归评价指标

回归是对连续的实数值进行预测,而分类中是离散值。

3.聚类评价指标

参考博客

1.Adjusted Rand index 调整兰德系数


>>> from sklearn import metrics
>>> labels_true = [0, 0, 0, 1, 1, 1]
>>> labels_pred = [0, 0, 1, 1, 2, 2]>>> metrics.adjusted_rand_score(labels_true, labels_pred)  

2.Mutual Information based scores 互信息


>>> from sklearn import metrics
>>> labels_true = [0, 0, 0, 1, 1, 1]
>>> labels_pred = [0, 0, 1, 1, 2, 2]>>> metrics.adjusted_mutual_info_score(labels_true, labels_pred)
0.22504

3.Homogeneity, completeness and V-measure

同质性homogeneity:每个群集只包含单个类的成员。
完整性completeness:给定类的所有成员都分配给同一个群集。

>>> from sklearn import metrics
>>> labels_true = [0, 0, 0, 1, 1, 1]
>>> labels_pred = [0, 0, 1, 1, 2, 2]>>> metrics.homogeneity_score(labels_true, labels_pred)
0.66...>>> metrics.completeness_score(labels_true, labels_pred) 

4.Fowlkes-Mallows scores

5.Silhouette Coefficient 轮廓系数

6.Calinski-Harabaz Index

4.其他

机器学习模型评分总结(sklearn)相关推荐

  1. sklearn库安装_没有依赖库也能跑机器学习模型!推荐一个强大工具m2cgen

    晓查 发自 凹非寺 量子位 报道 | 公众号 QbitAI m2cgen(Model 2 Code Generator)是一个轻量级代码生成器,它可以将训练好的机器学习模型转换成无需依赖库的本地代码. ...

  2. 机器学习模型评估指标总结!

    ↑↑↑关注后"星标"Datawhale 每日干货 & 每月组队学习,不错过 Datawhale干货 作者:太子长琴,Datawhale优秀学习者 本文对机器学习模型评估指标 ...

  3. 独家 | 机器学习模型应用方法综述

    作者:Julien Kervizic 翻译:陈之炎 校对:李海明 本文约5700字,建议阅读10+分钟. 本文整理比较模型部署到生产中使用的不同部署模型方式.生命周期管理方法及数据存储格式. Mant ...

  4. Python 3 利用机器学习模型 进行手写体数字检测

    0.引言 介绍了如何生成手写体数字的数据,提取特征,借助 sklearn 机器学习模型建模,进行识别手写体数字 1-9 模型的建立和测试. 用到的几种模型: 1. LR,Logistic Regres ...

  5. 机器学习模型可解释性的6种Python工具包,总有一款适合你!

    开发一个机器学习模型是任何数据科学家都期待的事情.我遇到过许多数据科学研究,只关注建模方面和评估,而没有解释. 然而,许多人还没有意识到机器学习可解释性在业务过程中的重要性.以我的经验,商业人士希望知 ...

  6. 【机器学习基础】非常详细!机器学习模型评估指标总结!

    作者:太子长琴,Datawhale优秀学习者 本文对机器学习模型评估指标进行了完整总结.机器学习的数据集一般被划分为训练集和测试集,训练集用于训练模型,测试集则用于评估模型.针对不同的机器学习问题(分 ...

  7. 机器学习结构化学习模型_生产化机器学习模型

    机器学习结构化学习模型 The biggest issue in the life-cycle of ML project isn't to create a good algorithm or to ...

  8. 机器学习方法_机器学习模型应用方法综述

    文章发布于公号[数智物语] (ID:decision_engine),关注公号不错过每一篇干货. 来源 | 数据派THU(id:DatapiTHU) 作者:Julien Kervizic 翻译:陈之炎 ...

  9. 还在随缘炼丹?一文带你详尽了解机器学习模型可解释性的奥秘

    一只小狐狸带你解锁NLP/ML/DL秘籍 正文来源:腾讯技术工程 所谓炼丹,就是将大量灵材使用丹炉将其凝炼成丹.练成的灵丹蕴含灵材的大部分特性,方便携带,容易吸收.高级仙丹在炼制中更是能吸收天地灵气从 ...

最新文章

  1. 如何快速判断某 URL 是否在 20 亿的网址 URL 集合中?
  2. 工厂模式IDAL具体解释
  3. Java实现插入排序及其优化 Shell Sort
  4. golang函数入门示例
  5. angularjs教程网址
  6. WM_USER和WM_APP[转]
  7. 对require四种引入方式的认识
  8. 《C++ Primer 5th》笔记(5 / 19):语句
  9. Django中Settings中Templates的路径设置
  10. 活动现场控制管理利器--节目文件,会议文件,PowerPoint文件,多媒体文件编辑组织管理播放平台--双屏版软件,欢迎下载使用.
  11. 小程序源码:独立后台带分销功能月老办事处交友盲盒
  12. 未联网环境下:离线安装Zsh和Oh My Zsh
  13. 电脑里删除的文件怎么恢复,数据恢复方法大全
  14. 海康相机RTSP连接代码分析
  15. 马来西亚吉隆坡召开的2010OpenWebAsia大会
  16. 计算机表格常用根式,常用平方根表.doc
  17. 106短信平台多少钱一条比较合理?
  18. Mac和Ubuntu系统下.bash_profile和.bashrc文件
  19. 数据分析利器之Excel功能篇
  20. 初识NK-RTU980开发板

热门文章

  1. Asterisk学习进阶-3
  2. vb访问mysql容易死机_VB访问MySQL
  3. android 中radiogroup滑动切换,巧妙实现缺角radiogroup控制多个fragment切换和滑动
  4. 通达oa 不允许从该ip登陆_通达OA-命令执行漏洞复现
  5. arcgis创建剖面线execl文件
  6. 【转】使用IIS做HTTP和WebSocket服务的反向代理
  7. ABP入门系列(18)—— 使用领域服务
  8. 第十一节:基于MVC5+Spring.Net+EF+Log4net 传统的一种搭建模式
  9. 【转】OneDrive开发入门
  10. 【Python CheckiO 题解】Secret Message