การพลอต Confusion Matrix ที่แกนเป็นข้อความ (Class names) แทนตัวเลข ใน Matplotlib ทำได้โดยใช้ ax.matshow() แสดงเมทริกซ์ แล้วตั้งค่า tick labels ด้วย set_xticklabels() และ set_yticklabels()
ขั้นตอนการทำงาน
- นำเข้า
matplotlib.pyplotและsklearn.metrics.confusion_matrix - กำหนดรายการ Labels (ชื่อคลาส)
- คำนวณ Confusion Matrix ด้วย
confusion_matrix(y_true, y_pred) - สร้าง Figure และ Axes
- แสดงเมทริกซ์ด้วย
ax.matshow(cm) - เพิ่ม Colorbar ด้วย
fig.colorbar() - ตั้งค่า Tick Labels ให้เป็นชื่อคลาส (เพิ่มสตริงว่าง '' ตัวแรกสำหรับ origin)
- แสดงผลด้วย
plt.show()
ตัวอย่างโค้ด
from matplotlib import pyplot as plt
from sklearn.metrics import confusion_matrix
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
labels = ['business', 'health']
cm = confusion_matrix([3], [2]) # ตัวอย่างข้อมูลน้อย
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(cm)
fig.colorbar(cax)
# เพิ่ม '' ตัวแรกเพื่อให้ตรงกับ index 0
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
plt.show()
ตัวอย่างสมบูรณ์พร้อมข้อมูลจริง
from sklearn.metrics import confusion_matrix
import numpy as np
# ข้อมูลตัวอย่าง
y_true = ['cat', 'dog', 'cat', 'cat', 'dog', 'bird', 'bird', 'cat']
y_pred = ['cat', 'dog', 'cat', 'bird', 'dog', 'bird', 'cat', 'cat']
labels = ['bird', 'cat', 'dog']
cm = confusion_matrix(y_true, y_pred, labels=labels)
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.matshow(cm, cmap='Blues')
fig.colorbar(im, ax=ax)
# ตั้งค่า ticks และ labels
ax.set_xticks(range(len(labels)))
ax.set_yticks(range(len(labels)))
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
# เพิ่มตัวเลขในเซลล์
for i in range(len(labels)):
for j in range(len(labels)):
ax.text(j, i, str(cm[i, j]), ha='center', va='center',
color='white' if cm[i, j] > cm.max()/2 else 'black')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Confusion Matrix')
plt.show()
ทางเลือกที่ง่ายกว่า: ใช้ sklearn.metrics.ConfusionMatrixDisplay
from sklearn.metrics import ConfusionMatrixDisplay
ConfusionMatrixDisplay.from_predictions(y_true, y_pred, display_labels=labels,
cmap='Blues', xticks_rotation=45)
plt.show()
การประยุกต์ใช้
จำเป็นสำหรับการประเมินโมเดล Machine Learning Classification การรายงานผลการทดสอบ การวิเคราะห์ข้อผิดพลาดของโมเดล