python sklearn 计算混淆矩阵 confusion_matrix()函数

参考sklearn官方文档:sklearn.metrics.confusion_matrix

功能:

计算混淆矩阵,以评估分类的准确性。

(关于混淆矩阵的含义,见:混淆矩阵(Confusion Matrix)。)

语法:

from sklearn.metrics import confusion_matrix

输入和输出:

输入:
  • y_truearray类型, 维度shape = [n_samples] 。

    正确的真值(Ground truth (correct) target values)。

  • y_predarray类型, 维度shape = [n_samples]

    分类器返回的估计目标(Estimated targets as returned by a classifier)。

  • labelsarray类型, 维度shape = [n_classes], 为可选输入(optional )。

    索引矩阵的标签列表。这可用于重新排序或选择标签的子集。如果没有给出,那些至少出现一次y_truey_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 in y_true or y_pred are used in sorted order)。

  • sample_weight :array-like of shape = [n_samples], optional

    Sample weights.

输出:
  • confusion_matrixarray类型, 维度为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如下:

labels011
0200
1001
2102
>>> 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如下:

labelsantbirdcat
ant200
bird001
cat102
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐