Sklearn对多分类的每个类别进行指标评(P R)


Sklearn中的召回度和精准度函数

  在上一篇博文中已经介绍过了精准度和召回度的定义,以及该如何利用混淆矩阵来进行计算。这一章节将会利用sklearn的包来直接计算出分类(多分类和二分类)的召回度和精准度。主要是采用sklearn.metrics中的classification_report, precision_score, confusion_matrix, recall_score这几个包。

 precision_score:精准度

from sklearn.metrics import precision_score y_true = [1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0] y_pre = [1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0] precision_score(y_true, y_pre)
0.42857142857142855
 

 recall_score:召回度

from sklearn.metrics import recall_score y_true = [1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0] y_pre = [1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0] recall_score(y_true, y_pre)
0.6666666666666666
 

confusion_matrix:混淆矩阵

from sklearn.metrics import confusion_matrix y_true = [1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0] y_pre = [1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0] confusion_matrix(y_true, y_pre)
array([[2, 4], [2, 4]])
 

  注意以上的三个函数,都是真实值arrary在第一个参数,预测值arrary在第二个参数。其中混淆矩阵没有行和列名,第一个参数表示的是行标,第二个参数表示的是列标,顺序是从小到大,字母的话就是字典序从小到大,这个例子中行名是真实值,列名是预测值。

  预测值
0 1
真实值 0 2 4
1 2 4

  以上的三种函数例子都是以二分类为例子的,下面将介绍多分类的情况,多分类的情况我非常推荐classification_report这个包,因为这个包可以非常好的展现出每一类单独的PR(精度和召回),而且也有平均之后(macro, weighted)的结果(具体的含义可以看看参考链接中的博文)。

classification_report:分类报告

from sklearn.metrics import classification_report y_true = [1, 2, 1, 1, 2, 0, 0, 2, 1, 1, 0, 2, 1, 2, 0, 1, 1, 2, 2, 1, 0] y_pre = [1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 2, 2, 1, 0, 0, 0] print(classification_report(y_true, y_pre, labels=[0,1,2]))
              precision    recall  f1-score support 0 0.12      0.20      0.15         5
           1       0.27      0.33      0.30         9
           2       0.00      0.00      0.00         7 accuracy 0.19        21 macro avg 0.13      0.18      0.15        21 weighted avg 0.15      0.19      0.17        21

  其实这种方法,也可以对字符串的分类来展示。

from sklearn.metrics import classification_report y_true = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] y_pre = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] print(classification_report(y_true, y_pre, labels=['','','']))
                precision    recall  f1-score support 多 0.12      0.20      0.15         50.27      0.33      0.30         90.00      0.00      0.00         7 accuracy 0.19        21 macro avg 0.13      0.18      0.15        21 weighted avg 0.15      0.19      0.17        21

  注意到使用这个函数的时候,参数labels非常重要,最好要赋值,虽然是可选参数,但是如果不给值,但最后的结果表格会比较难理解。

 

参考网址:

https://www.cnblogs.com/zhangxianrong/p/14884257.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM