Seaborn 混淆矩陣圖

Ammar Ali 2022年5月18日
Seaborn 混淆矩陣圖

本教程將討論在 Python 中使用 Seaborn 的 heatmap() 函式繪製混淆矩陣。

使用 Seaborn 繪製混淆矩陣

在分類問題中,預測結果的摘要儲存在混淆矩陣中。我們必須繪製混淆矩陣來檢視正確和錯誤預測的計數。

要繪製混淆矩陣,我們必須建立混淆矩陣的資料框,然後我們可以使用 Seaborn 的 heatmap() 函式在 Python 中繪製混淆矩陣。例如,讓我們建立一個隨機混淆矩陣並使用 heatmap() 函式繪製它。請參閱下面的程式碼。

import seaborn as snNew
import pandas as pdNew
import matplotlib.pyplot as pltNew

array = [
    [11, 1, 0, 2, 0],
    [3, 8, 0, 1, 0],
    [0, 16, 3, 0, 0],
    [0, 0, 12, 0, 0],
    [0, 0, 0, 13, 0],
    [0, 1, 0, 0, 16],
]

DetaFrame_cm = pdNew.DataFrame(array, range(6), range(5))
snNew.heatmap(DetaFrame_cm, annot=True)
pltNew.show()

輸出:

混淆矩陣圖

為了建立混淆矩陣的資料框,我們使用了 pandas 庫的 DataFrame() 函式。要建立資料框,我們必須傳遞陣列、行數和列數。

heatmap() 函式中的第二個引數用於在圖上顯示混淆矩陣值。如果我們不使用第二個引數 annot,矩陣值將不可見,我們只會看到顏色。

我們可以將繪圖的顏色圖更改為冬季、夏季、涼爽、銅和熱等功能支援的任何顏色圖。我們還可以使用 cbar 引數關閉繪圖右側顯示的顏色條並將其設定為 false。

我們還可以使用 linewidthslinecolor 引數指定每個單元格周圍線條的寬度和顏色。我們可以使用任何浮點值來設定線寬的值。我們可以使用顏色名稱或顏色的首字母來設定線條顏色的值。

我們可以使用 square 引數將每個單元格形狀設定為正方形並將其設定為 true。我們還可以使用用於 x 軸刻度標籤的 xticklabels 和用於 y 軸刻度標籤的 yticklabels 設定每個軸的刻度標籤。

我們可以將刻度標籤引數設定為與 x 軸單元格大小相同的列表。例如,讓我們更改上面提到的引數。請參閱下面的程式碼。

import seaborn as snNew
import pandas as pdNew
import matplotlib.pyplot as pltNew

array = [
    [11, 1, 0, 2, 0],
    [3, 8, 0, 1, 0],
    [0, 16, 3, 0, 0],
    [0, 0, 12, 0, 0],
    [0, 0, 0, 13, 0],
    [0, 1, 0, 0, 16],
]

DetaFrame_cm = pdNew.DataFrame(array, range(6), range(5))
snNew.heatmap(
    DetaFrame_cm,
    annot=True,
    cmap="summer",
    cbar=False,
    linewidths=3,
    linecolor="r",
    square=True,
    xticklabels=["a", "b", "c", "d", "e"],
)
pltNew.show()

輸出:

更改混淆矩陣圖的引數

我們還可以使用 Seaborn 的 set() 函式設定兩個軸的刻度標籤的字型大小。我們可以使用 set() 函式中的 font_scale 引數將字型值設定為任何浮點數。例如,要設定上圖的字型大小,我們可以使用下面的程式碼。

snNew.set(font_scale=1.9)

如果我們想減小字型大小,我們必須使用小於 1 的值。

作者: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

相關文章 - Seaborn Plot