分类评价指标: Confusion matrix, Accuracy, F1, AUC, PR曲线绘制, ROC曲线绘制 ...

1. 混淆矩阵(Confusion matrix)

定义: 混淆矩阵是数据科学、数据分析和机器学习中分类模型预测结果的统计局表,以矩阵形式将数据集中的记录按照真实类别与预测结果进行汇总。以二分类为例,混淆矩阵如图1所示。

其中,TRUE **:表示预测正确的实例,FALSE **:表示预测错误的实例。
Python中使用sklearn得到混淆矩阵:

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

2. 评价指标

  • A c c u r a c y : Accuracy: Accuracy表示模型将所有样本实例预测正确的比例。分子是所有预测正确的样本数量,分母是全部样本的数量。
    A c c u r a c y = T P s + T N s T P s + T N s + F P s + F N s Accuracy = \frac{{TPs +TNs}}{{TPs + TNs + FPs + FNs}} Accuracy=TPs+TNs+FPs+FNsTPs+TNs

  • T r u e   p o s i t i v e   r a t e : True \ positive \ rate: True positive rate表示为正例样本有多少被模型预测正确了。 T r u e   p o s i t i v e   r a t e = s e n s i t i v i t y = r e c a l l = True \ positive \ rate=sensitivity=recall= True positive rate=sensitivity=recall=查全率
    T r u e   p o s i t i v e   r a t e = T P s T P s + F N s True \ positive \ rate = \frac{{TPs}}{{TPs + FNs}} True positive rate=TPs+FNsTPs

  • T r u e   n e g e t i v a   r a t e : True \ negetiva \ rate: True negetiva rate表示为负例样本有多少被模型预测正确了。 T N R = S p e c i f i c i t y TNR=Specificity TNR=Specificity
    T r u e   n e g e t i v a   r a t e = T N s T N s + F P s True \ negetiva \ rate = \frac{{TNs}}{{TNs + FPs}} True negetiva rate=TNs+FPsTNs

  • P o s i t i v e   p r e d i c t i v e   v a l u e : Positive \ predictive \ value: Positive predictive value表示模型预测为正例样本中有多少预测正确了。 P P V = P r e c i s i o n = PPV=Precision= PPV=Precision=查准率
    P o s i t i v e   p r e d i c t i v e   v a l u e = T P s T P s + F P s Positive \ predictive \ value = \frac{{TPs}}{{TPs + FPs}} Positive predictive value=TPs+FPsTPs

  • F 1 − s c o r e : F1-score: F1score精确率和召回率的调和均值。这个指标同时考虑了样本实例的查全率和查准率,因此其中任何一个值都能影响 F 1 F1 F1的大小。
    F 1 = 2 × R e c a l l × P r e c i s i o n R e c a l l + P r e c i s i o n F1= \frac{{2 \times Recall \times Precision}}{{Recall + Precision}} F1=Recall+Precision2×Recall×Precision

宏平均(Macro-averaging)和微平均(Micro-averaging)
宏平均和微平均针对整体评价指标而言,宏平均(Macro-averaging)是先对每一个类统计相应指标值,然后在对所有类求算术平均值。微平均(Micro-averaging)是根据混淆矩阵,对所有样本实例进行统计,然后计算相应指标。

Python中使用sklearn得到分类报告:

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

3. PR曲线和ROC曲线

ROC曲线主要表现为一种真正例率和假正例率的权衡。ROC曲线的特点之一是具有鲁棒性,即正例或负例的比例发生了很大变化,ROC曲线也不会产生大的变化。而PR曲线主要表现为一种精确率和召回率的权衡。针对类别不平衡问题,我们主要关心正例,在这种情况下PR曲线被认为优于ROC曲线。

(1)Python绘制ROC曲线

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
from 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
from sklearn.metrics import roc_auc_score

# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Binarize the output
y = label_binarize(y, classes=[0, 1, 2])
n_classes = y.shape[1]

# Add noisy features to make the problem harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=0)

# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)

# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
    fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
    roc_auc[i] = auc(fpr[i], tpr[i])

# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

# First aggregate all false positive rates
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_classes

fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

# Plot all ROC curves
plt.figure()
lw = 2
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)Python绘制PR曲线

from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
import numpy as np
from  sklearn.metrics  import  average_precision_score
from  sklearn.metrics  import  precision_recall_curve
from  sklearn.metrics  import  plot_precision_recall_curve
import  matplotlib.pyplot  as  plt

iris = datasets.load_iris()
X = iris.data
y = iris.target

# Add noisy features
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

# Limit to the two first classes, and split into training and test
X_train, X_test, y_train, y_test = train_test_split(X[y < 2], y[y < 2], test_size=.5, random_state=random_state)

# Create a simple classifier
classifier = svm.LinearSVC(random_state=random_state)
classifier.fit(X_train, y_train)
y_score = classifier.decision_function(X_test)

average_precision  =  average_precision_score(y_test,  y_score)
disp  =  plot_precision_recall_curve(classifier,  X_test,  y_test)  
disp.ax_.set_title('2-class Precision-Recall curve: '  'AP={0:0.2f}'.format(average_precision))
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值