sklearn.metrics.confusion_matrix?

sklearn.metrics.confusion_matrix(y_true, y_pred, *, labels=None, sample_weight=None, normalize=None)

計算混淆矩陣以評估分類的準確性。

根據定義,混淆矩陣使得等于已知在第i組中并且預計在第j組中的觀測次數。

因此,在二元分類中,真負例的計數為,假負例的計數為,真正例的計數為,假正例的計數為。

在用戶指南中閱讀更多內容。

參數 說明
y_true array-like of shape (n_samples,)
真實目標值。
y_pred array-like of shape (n_samples,)
分類器返回的估計目標。
labels array-like of shape (n_classes), default=None
索引矩陣的標簽列表。可用于重新排序或選擇標簽的子集。如果指定None,則那些在y_true或y_pred中至少出現一次的標簽將按照排序使用。
sample_weight array-like of shape (n_samples,), default=None
樣本權重。
版本0.18中的新功能。
normalize {‘true’, ‘pred’, ‘all’}, default=None
對真實(行),預測(列)條件或所有總體的混淆矩陣進行歸一化。 如果為None,則不會對混淆矩陣進行歸一化。
返回值 說明
C ndarray of shape (n_classes, n_classes)
混淆矩陣,其第i行和第j列條目指示真實標簽為第i類且預測標簽為第j類的樣本數。

參考

1 Wikipedia entry for the Confusion matrix (Wikipedia and other references may use a different convention for axes)

示例

>>> 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]])
>>> 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]])

在二進制情況下,我們可以提取真實的正例,如下所示:

>>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel()
>>> (tn, fp, fn, tp)
(0, 2, 1, 1)