资讯专栏INFORMATION COLUMN

机器学习之分类结果的评价

zhaot / 1985人阅读

摘要:的实现如下表示真实分类,表示预测结果混淆矩阵的结果为中封装了混淆矩阵方法精准率和召回率及实现有了混淆矩阵,精准率和召回率久很好表示了。就是召回率,即表示真实分类偏斜数据中占优势的分类中被预测错误的数量的占比,即。

以逻辑回归为例,介绍分类结果的评价方式。

精准率和召回率

对于极度偏斜的数据,使用分类准确度来评判模型的好坏是不恰当的,精确度和召回率是两个更好的指标来帮助我们判定模型的好快。

二分类的混淆矩阵

精准率和召回率是存在于混淆矩阵之上的,以二分类为例,分类0是偏斜数据中占优势的一方,将关注的重点放在分类为1上,其混淆矩阵如下:

真实值预测值 0 1
0 9978(TN) 12(FP)
1 2(FN) 8(TP)

TN 的含义是预测 negative 正确的数量,即真实分类为0预测的分类结果也为0的共有9978个;

FN 的含义是预测 negative 错误的数量,即真实分类为1预测的分类结果为0的共有2个;

FP 的含义是预测 positive 错误的数量,即真实分类为0预测的分类结果为1的共有12个;

TP 的含义是预测 positive 正确的数量,即真实分类为1预测的分类结果也为1的共有8个。

TN、FN、FP、TP 的实现如下(y_true 表示真实分类, y_predict 表示预测结果):

</>复制代码

  1. import numpy as np
  2. def TN(y_true, y_predict):
  3. return np.sum((y_true == 0) & (y_predict == 0))
  4. def FP(y_true, y_predict):
  5. return np.sum((y_true == 0) & (y_predict == 1))
  6. def FN(y_true, y_predict):
  7. return np.sum((y_true == 1) & (y_predict == 0))
  8. def TP(y_true, y_predict):
  9. return np.sum((y_true == 1) & (y_predict == 1))

混淆矩阵的结果为:

</>复制代码

  1. def confusion_matrix(y_test, y_predict):
  2. return np.array([
  3. [TN(y_test, y_log_predict), FP(y_test, y_log_predict)],
  4. [FN(y_test, y_log_predict), TP(y_test, y_log_predict)]
  5. ])

Scikit Learn 中封装了混淆矩阵方法 confusion_matrix()

</>复制代码

  1. from sklearn.metrics import confusion_matrix
  2. confusion_matrix(y_true, y_predict)
精准率和召回率及实现

有了混淆矩阵,精准率和召回率久很好表示了。

精准率表示预测分类结果中预测正确的数量的占比,即:

$$ precision=frac{TP}{TP+FP} $$

将其用代码表示为:

</>复制代码

  1. def precision_score(y_true, y_predict):
  2. tp = TP(y_true, y_predict)
  3. fp = FP(y_true, y_predict)
  4. try:
  5. return tp / (tp + fp)
  6. except:
  7. return 0.0

召回率表示真实分类中被预测正确的数量的占比,即:

$$ recall=frac{TP}{TP+FN} $$

将其用代码表示为:

</>复制代码

  1. def recall_score(y_true, y_predict):
  2. tp = TP(y_true, y_predict)
  3. fn = FN(y_true, y_predict)
  4. try:
  5. return tp / (tp + fn)
  6. except:
  7. return 0.0

Scikit Learn 中也封装了计算精准率的方法 precision_score() 和计算召回率的方法 recall_score()

</>复制代码

  1. from sklearn.metrics import precision_score
  2. precision_score(y_true, y_predict)
  3. from sklearn.metrics import recall_score
  4. recall_score(y_true, y_predict)
F1 Score

精准率和召回率这两个指标的侧重点不同,有的时候我们注重精准率(如股票预测),有的时候我们注重召回率(病人诊断)。但有时候又需要把两者都考虑进行,此后就可以使用 F1 Score 指标。

F1 Score 是精准率和召回率的调和平均值,公式为:

$$ frac{1}{F1}=frac{1}{2}(frac{1}{precision}+frac{1}{recall}) $$

即:$F1=frac{2·precision·recall}{precesion+recall}$,并且 F1 Score 的取值是在区间 $[0, 1]$ 之中的。

代码实现为:

</>复制代码

  1. def f1_score(y_true, y_predict):
  2. precision = precision_score(y_true, y_predict)
  3. recall = recall_score(y_true, y_predict)
  4. try:
  5. return 2 * precision * recall / (precision + recall)
  6. except:
  7. return 0.0

Scikit Learn 中封装了方法 f1_score() 来计算 F1 Score:

</>复制代码

  1. from sklearn.metrics import f1_score
  2. f1_score(y_true, y_predict)
Precision-Recall 曲线

Scikit Learn 的逻辑回归中的概率公式为 $hat p=sigma( heta^T·x_b)$ ,其决策边界为 $ heta^T·x_b=0$,但是如果决策边界不为0会如何呢?

假定决策边界为 $ heta^T·x_b=threshold$,当 threshold 的取值不同(0、大于0的某个值、小于0的某个值),对应的精确度和召回率也不同。如图:

圆形和星形是不同的的分类,并且重点放在星形的分类上,可以看出,threshold 的取值越大时,精确率越高,而召回率越低。

如果要更改决策边界,逻辑回归的 decision_function() 返回传入数据的 $ heta^T·x_b$ 计算结果 decision_scores,接着再构建一个新的预测结果;如代码所示,设定 decision_scores >= 5(默认decision_scores >= 0 ) 的预测结果才为1,其余为0:

</>复制代码

  1. from sklearn.linear_model import LogisticRegression
  2. log_reg = LogisticRegression()
  3. # X_train, y_train 为训练数据集
  4. log_reg.fit(X_train, y_train)
  5. # X_test,y_test 为测试数据集
  6. decision_scores = log_reg.decision_function(X_test)
  7. y_log_predict_threshold = np.array(decision_scores >= 5, dtype="int")

如此可以得到不同的 y_log_predict_threshold,进而得到不同的精准率和召回率。

以手写数字识别数据为例,将标记为9的数据分类为1,其余分类为0:

</>复制代码

  1. from sklearn import datasets
  2. digits = datasets.load_digits()
  3. X = digits.data
  4. y = digits.target.copy()
  5. y[digits.target==9] = 1
  6. y[digits.target!=9] = 0
  7. from sklearn.model_selection import train_test_split
  8. X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=500)

接着训练逻辑回归模型:

</>复制代码

  1. from sklearn.linear_model import LogisticRegression
  2. log_reg = LogisticRegression()
  3. log_reg.fit(X_train, y_train)

获取测试数据集 X_test 对应的 $ heta^T·x_b$ 取值:

</>复制代码

  1. decision_scores = log_reg.decision_function(X_test)

在 decision_scores 的取值区间划分为一系列值 thresholds ,并将其中的值依次作为决策边界,进而得到不同的精确率和召回率

</>复制代码

  1. from sklearn.metrics import precision_score
  2. from sklearn.metrics import recall_score
  3. precisions = []
  4. recalls = []
  5. thresholds = np.arange(np.min(decision_scores), np.max(decision_scores), 0.1)
  6. for threshold in thresholds:
  7. y_predict = np.array(decision_scores >= threshold, dtype="int")
  8. precisions.append(precision_score(y_test, y_predict))
  9. recalls.append(recall_score(y_test, y_predict))

将精确率、召回率与决策边界的关系绘制如图:

精确度与召回率的关系,即 Precision-Recall 曲线则为:

Scikit Learn 中提供的 precision_recall_curve() 方法传入真实分类结果和 decision_scores,返回 precisions、recalls 和 thresholds:

</>复制代码

  1. from sklearn.metrics import precision_recall_curve
  2. precisions, recalls, thresholds = precision_recall_curve(y_test, decision_scores)

Precision-Recall 曲线越靠外(即面积越大)则表示模型越好。

多分类中的精确率和召回率

在过分类中,Sckit Learn 提供的 confusion_matrix() 可以直接返回多分类的混淆矩阵,而对于精确率和召回率,则要在 Sckit Learn 提供的方法中指定 average 参数值为 micro,如:

</>复制代码

  1. from sklearn.metrics import precision_score
  2. precision_score(y_test, y_predict, average="micro")
ROC 曲线

对于用图形面积判断模型好快,ROC 曲线比 Precision-Recall 曲线要好。

ROC 曲线涉及两个指标,TPR 和 FPR。TPR 就是召回率,即:$TPR=frac{TP}{TP+FN}$;FPR 表示真实分类(偏斜数据中占优势的分类)中被预测错误的数量的占比,即:$FPR=frac{FP}{TN+FP}$。实现代码为:

</>复制代码

  1. def TPR(y_true, y_predict):
  2. tp = TP(y_true, y_predict)
  3. fn = FN(y_true, y_predict)
  4. try:
  5. return tp / (tp + fn)
  6. except:
  7. return 0.0
  8. def FPR(y_true, y_predict):
  9. fp = FP(y_true, y_predict)
  10. tn = TN(y_true, y_predict)
  11. try:
  12. return fp / (fp + tn)
  13. except:
  14. return 0.0

对于决策边界的不同,这两个指标的变化趋势是一致的。还是以上面的手写数字识别数据为例,计算不同决策边界下的两指标的值为:

</>复制代码

  1. fprs = []
  2. tprs = []
  3. for threshold in thresholds:
  4. y_predict = np.array(decision_scores >= threshold, dtype="int")
  5. fprs.append(FPR(y_test, y_predict))
  6. tprs.append(TPR(y_test, y_predict))

作出的 TPR 和 FPR 的关系图(即 ROC 曲线)为:

Scikit Learn 中提供的 roc_curve() 方法传入真实分类结果和 decision_scores,返回 TPR、FPR 和 thresholds:

</>复制代码

  1. from sklearn.metrics import roc_curve
  2. fprs, tprs, thresholds = roc_curve(y_test, decision_scores)

roc_auc_score() 方法传入真实分类结果和 decision_scores,返回 ROC 曲线表示的面积。

</>复制代码

  1. from sklearn.metrics import roc_auc_score
  2. roc_auc_score(y_test, decision_scores)

面积越大,则模型越好。

源码地址

Github | ML-Algorithms-Action

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/42791.html

相关文章

发表评论

0条评论

zhaot

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<