用Scikit-learn实现分类指标评价

2020-09-15  本文已影响0人  ShowMeCoding

1 分类指标评价计算示例

1、混淆矩阵(Confuse Matrix)

# 混淆矩阵创建
import numpy as np
from sklearn.metrics import confusion_matrix
y_pred = [0,1,0,1]
y_true = [0,1,1,0]
print('混淆矩阵:\n',confusion_matrix(y_true,y_pred))
混淆矩阵:
 [[1 1]
 [1 1]]

1.1 Accuracy计算

2、准确率(Accuracy) 准确率是常用的一个评价指标,但是不适合样本不均衡的情况。

​```python
# Accuracy计算
from sklearn.metrics import accuracy_score
y_pred = [0,1,0,1]
y_true = [0,1,1,0]
print('ACC:',accuracy_score(y_true,y_pred))
ACC: 0.5

1.2 Precision,Recall,F1-score计算

3、精确率(Precision) 又称查准率,正确预测为正样本(TP)占预测为正样本(TP+FP)的百分比。

4、召回率(Recall) 又称为查全率,正确预测为正样本(TP)占正样本(TP+FN)的百分比。

5、F1 Score 精确率和召回率是相互影响的,精确率升高则召回率下降,召回率升高则精确率下降,如果需要兼顾二者,就需要精确率、召回率的结合F1_Score。
F1−Score=2/(1/Precision+1/Recall)

# Precision,Recall,F1-score计算
from sklearn import metrics
y_pred = [0,1,0,1]
y_true = [0,1,1,0]
print('Precision:',metrics.precision_score(y_true,y_pred))
print('Recall:',metrics.recall_score(y_true,y_pred))
print('F1-score:',metrics.f1_score(y_true,y_pred))
Precision: 0.5
Recall: 0.5
F1-score: 0.5

1.3 P-R曲线

6、P-R曲线(Precision-Recall Curve) P-R曲线是描述精确率和召回率变化的曲线

​```python
# P-R曲线
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve
y_pred = [0, 1, 1, 0, 1, 1, 0, 1, 1, 1]
y_true = [0, 1, 1, 0, 1, 0, 1, 1, 0, 1]
precision,recall,thresholds = precision_recall_curve(y_true,y_pred)
plt.title('P-R')
plt.plot(precision,recall)
plt.ylabel('recall')
plt.xlabel('precision')
output_27_1.png

1.4 ROC曲线

7、ROC(Receiver Operating Characteristic)
ROC空间将假正例率(FPR)定义为 X 轴,真正例率(TPR)定义为 Y 轴。
TPR:在所有实际为正例的样本中,被正确地判断为正例之比率。

FPR:在所有实际为负例的样本中,被错误地判断为正例之比率。

# ROC曲线
from sklearn.metrics import roc_curve
y_pred = [0, 1, 1, 0, 1, 1, 0, 1, 1, 1]
y_true = [0, 1, 1, 0, 1, 0, 1, 1, 0, 1]
FPR,TPR,thresholds=roc_curve(y_true, y_pred)
plt.title('ROC')
plt.plot(FPR, TPR,'b')
plt.plot([0,1],[0,1],'r--')
plt.ylabel('TPR')
plt.xlabel('FPR')
output_28_1.png

1.5 AUC计算

8、AUC(Area Under Curve)
AUC(Area Under Curve)被定义为 ROC曲线下与坐标轴围成的面积,显然这个面积的数值不会大于1。又由于ROC曲线一般都处于y=x这条直线的上方,所以AUC的取值范围在0.5和1之间。AUC越接近1.0,检测方法真实性越高;等于0.5时,则真实性最低,无应用价值。

# AUC
import numpy as np
from sklearn.metrics import roc_auc_score
y_true = np.array([0,0,1,1])
y_scores = np.array([0.1,0.4,0.35,0.8])
print('AUC score:',roc_auc_score(y_true,y_scores))
AUC score: 0.75

1.6 KS计算

1、KS(Kolmogorov-Smirnov) KS统计量由两位苏联数学家A.N. Kolmogorov和N.V. Smirnov提出。在风控中,KS常用于评估模型区分度。区分度越大,说明模型的风险排序能力(ranking ability)越强。 K-S曲线与ROC曲线类似,不同在于:

KS不同代表的不同情况,一般情况KS值越大,模型的区分能力越强,但是也不是越大模型效果就越好,如果KS过大,模型可能存在异常,所以当KS值过高可能需要检查模型是否过拟合。以下为KS值对应的模型情况,但此对应不是唯一的,只代表大致趋势。

KS(%) 好坏区分能力
20以下 不建议采用/
20-40 较好/
41-50 良好/
51-60 很强/
61-75 非常强/
大于75 过于高,疑似存在问题/

​```python
# KS计算,在实际操作时往往使用ROC曲线配合求出KS值
from sklearn.metrics import roc_curve
y_pred = [0, 1, 1, 0, 1, 1, 0, 1, 1, 1]
y_true = [0, 1, 1, 0, 1, 0, 1, 1, 1, 1]
FPR,TPR,thresholds=roc_curve(y_true, y_pred)
KS=abs(FPR-TPR).max()
print('KS值:',KS)
KS值: 0.5238095238095237
上一篇 下一篇

猜你喜欢

热点阅读