二分类
二分类比较简单,所以我们先来分析一下二分类的情况。
我们利用 sklearn中的 confusion_matrix 函数来得到混淆矩阵,函数原型为:
sklearn.metrics.confusion_matrix(y_true, y_pred, labels=None, sample_weight=None)
y_true:样本真实的分类标签列表
y_pred:样本预测的分类结果列表
labels:类别列表,可用于对类别重新排序或选择类别子集。默认,则将y_true 或y_pred 中至少出现一次的类别按排序顺序构成混淆矩阵。
sample_weight:样本权重
>>> from sklearn.metrics import confusion_matrix
>>> y_true = [0, 1, 0, 1]
>>> y_pred = [1, 1, 1, 0]
>>> confusion_matrix(y_true, y_pred)
[[0 2]
[1 1]]
TN | FP
FN | TP
可以通过ravel()来直接得到这四个值:
tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel()
如果知道 tn, fp, fn, tp 这四个值的含义,我们也可以自定义函数来获取它们:
def perf_measure(y_true, y_pred):
TP, FP, TN, FN = 0, 0, 0, 0
for i in range(len(y_true)):
if y_true[i] == 1 and y_pred[i] == 1:
TP += 1
if y_true[i] == 0 and y_pred[i] == 1:
FP += 1
if y_true[i] == 0 and y_pred[i] == 0:
TN += 1
if y_true[i] == 1 and y_pred[i] == 0:
FN += 1
return TP, FP, TN, FN
多分类
现在来看多分类模型,我们知道了求混淆矩阵的函数返回值是长宽为类别个数的二维矩阵,下面是个三分类的例子:
>>> 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)
array([[2, 0, 0],
[0, 0, 1],
[1, 0, 2]])
结果是一个3x3的二维矩阵,我们怎么求得tn, fp, fn, tp这四个值呢?
下面这张图可谓是说明得非常清晰了。
混淆矩阵M的每一行表示真实的类,每一列表示预测的类。即:M[i][j]表示真实类别为i的所有样本中被预测为类别j的样本数目。
我们重点关注混淆矩阵的对角线区域,它表示实际类别和预测类别相一致,即TP区域。
某类的FP:该列所有元素之和减去该列的TP
某类的FN:该行所有元素之和减去该行的TP
某类的TN:整个矩阵之和减去该类的(TP+FP+FN)
下面是得到tn, fp, fn, tp的方法,进而求得其他各项指标:
FP = cm.sum(axis=0) - np.diag(cm)
FN = cm.sum(axis=1) - np.diag(cm)
TP = np.diag(cm)
TN = cm.sum() - (FP + FN + TP)
#Sensitivity, hit rate, recall, or true positive rate
TPR = TP/(TP+FN)
#Specificity or true negative rate
TNR = TN/(TN+FP)
#Precision or positive predictive value
PPV = TP/(TP+FP)
#Negative predictive value
NPV = TN/(TN+FN)
#Fall out or false positive rate
FPR = FP/(FP+TN)
#False negative rate
FNR = FN/(TP+FN)
#False discovery rate
FDR = FP/(TP+FP)
precision = TP / (TP+FP) # 查准率
recall = TP / (TP+FN) # 查全率