python sklearn 计算混淆矩阵 confusion_matrix()函数
参考sklearn
官方文档:sklearn.metrics.confusion_matrix。
功能:
计算混淆矩阵,以评估分类的准确性。
(关于混淆矩阵的含义,见:混淆矩阵(Confusion Matrix)。)
语法:
from sklearn.metrics import confusion_matrix
输入和输出:
输入:
-
y_true
:array
类型, 维度shape
= [n_samples] 。正确的真值(Ground truth (correct) target values)。
-
y_pred
:array
类型, 维度shape
= [n_samples]分类器返回的估计目标(Estimated targets as returned by a classifier)。
-
labels
:array
类型, 维度shape
= [n_classes], 为可选输入(optional )。索引矩阵的标签列表。这可用于重新排序或选择标签的子集。如果没有给出,那些至少出现一次
y_true
或y_pred
按排序顺序使用的那些。 (List of labels to index the matrix. This may be used to reorder or select a subset of labels. If none is given, those that appear at least once iny_true
ory_pred
are used in sorted order)。 -
sample_weight
:array-like of shape = [n_samples], optionalSample weights.
输出:
confusion_matrix
:array
类型, 维度为n_classes × n_classes
(shape = [n_classes, n_classes] )
示例:
>>> 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]])
confusion_matrix
如下:
labels | 0 | 1 | 1 |
---|---|---|---|
0 | 2 | 0 | 0 |
1 | 0 | 0 | 1 |
2 | 1 | 0 | 2 |
>>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
>>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
>>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"])
array([[2, 0, 0],
[0, 0, 1],
[1, 0, 2]])
confusion_matrix
如下:
labels | ant | bird | cat |
---|---|---|---|
ant | 2 | 0 | 0 |
bird | 0 | 0 | 1 |
cat | 1 | 0 | 2 |