อธิบายเมทริกซ์ความสับสน
ผู้เรียนจะสร้างเมทริกซ์ความสับสนจากผลการพยากรณ์และค่าจริง จากนั้นหาจำนวนผลบวกจริง ผลลบเท็จ และจำนวนที่เกี่ยวข้อง
อธิบายเมทริกซ์ความสับสน เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Beyond Accuracy: Understanding Errors
Accuracy tells you the percentage of correct predictions, but it treats all errors as equal. In reality, different types of errors have very different consequences. A spam filter that sends a legitimate email to the spam folder is annoying; a medical diagnosis model that misses a cancer case is life-threatening.
The confusion matrix is the tool that breaks down classifier performance into a 2×2 table (for binary classification) showing every possible combination of actual and predicted labels. It reveals not just how much the model is wrong but how it is wrong.
The Four Cells of the Confusion Matrix
For binary classification with classes Positive (1) and Negative (0), the confusion matrix has four cells:
- True Positive (TP) — actual positive, predicted positive. Correct detection.
- True Negative (TN) — actual negative, predicted negative. Correct rejection.
- False Positive (FP) — actual negative, predicted positive. Type I error; false alarm.
- False Negative (FN) — actual positive, predicted negative. Type II error; missed detection.
All four counts are needed to fully characterise a classifier's behaviour.
import numpy as np
# Medical test example:
# Positive = disease present, Negative = disease absent
y_true = np.array([1, 0, 1, 1, 0, 0, 1, 0, 1, 0])
y_pred = np.array([1, 0, 1, 0, 1, 0, 1, 0, 0, 0])
TP = ((y_pred == 1) & (y_true == 1)).sum()
TN = ((y_pred == 0) & (y_true == 0)).sum()
FP = ((y_pred == 1) & (y_true == 0)).sum()
FN = ((y_pred == 0) & (y_true == 1)).sum()
print(f'TP={TP} FP={FP}')
print(f'FN={FN} TN={TN}')
print(f'Total: {TP+TN+FP+FN}')Building the Confusion Matrix with scikit-learn
Scikit-learn's confusion_matrix() function takes the actual labels and predicted labels and returns the matrix as a NumPy array. The convention in scikit-learn is rows = actual class, columns = predicted class.
For binary classification with labels [0, 1], the matrix layout is:
- Row 0, Col 0 = TN (actual 0, predicted 0)
- Row 0, Col 1 = FP (actual 0, predicted 1)
- Row 1, Col 0 = FN (actual 1, predicted 0)
- Row 1, Col 1 = TP (actual 1, predicted 1)
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)
model = LogisticRegression(max_iter=1000)
model.fit(X_train_s, y_train)
y_pred = model.predict(X_test_s)
cm = confusion_matrix(y_test, y_pred)
print('Confusion matrix:')
print(cm)
print('\nRows=Actual, Cols=Predicted')Visualising the Confusion Matrix as a Heatmap
A confusion matrix visualised as a heatmap makes the counts immediately readable. Large numbers on the diagonal (top-left to bottom-right) indicate correct predictions. Large off-diagonal numbers indicate errors that need investigation.
Use seaborn's heatmap() with annot=True and fmt='d' to display integer counts inside each cell. Adding target class names makes the plot self-explanatory without needing to consult a key.
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
class_names = ['Malignant', 'Benign'] # breast cancer dataset
plt.figure(figsize=(7, 6))
sns.heatmap(
cm,
annot=True,
fmt='d',
cmap='Blues',
xticklabels=class_names,
yticklabels=class_names
)
plt.ylabel('Actual Label')
plt.xlabel('Predicted Label')
plt.title('Confusion Matrix — Breast Cancer Classifier')
plt.show()Deriving Accuracy from the Confusion Matrix
Every classification metric can be derived from the four confusion matrix cells. Accuracy is the simplest — it is the fraction of predictions that fall on the diagonal (TP + TN) out of all predictions:
Accuracy = (TP + TN) / (TP + TN + FP + FN)
All predictions are correct. All predictions = TP + TN + FP + FN. If your test set has 100 examples and you have TP=40, TN=50, FP=5, FN=5, then accuracy = 90/100 = 0.90. But the 5 FN errors (missed positives) may be far more consequential than the 5 FP errors.
from sklearn.metrics import confusion_matrix, accuracy_score
import numpy as np
y_true = np.array([1, 0, 1, 1, 0, 0, 1, 0, 1, 0])
y_pred = np.array([1, 0, 1, 0, 1, 0, 1, 0, 0, 0])
cm = confusion_matrix(y_true, y_pred)
TN, FP, FN, TP = cm.ravel() # for 2x2 matrix
# Manual accuracy
manual_acc = (TP + TN) / (TP + TN + FP + FN)
sklearn_acc = accuracy_score(y_true, y_pred)
print(f'TP={TP}, TN={TN}, FP={FP}, FN={FN}')
print(f'Manual accuracy: {manual_acc:.2f}')
print(f'sklearn accuracy: {sklearn_acc:.2f}')Type I and Type II Errors
In statistics and ML, errors have formal names that reflect their severity in different contexts:
- Type I error = False Positive. You raise the alarm when there is nothing to worry about. Example: flagging a legitimate transaction as fraud, sending someone to hospital unnecessarily.
- Type II error = False Negative. You miss a real event. Example: approving a fraudulent transaction, sending a cancer patient home as healthy.
In most real-world classification problems, Type I and Type II errors have very different costs, which is why a single accuracy number is insufficient for decision-making.
The Confusion Matrix for Multi-Class Problems
For a k-class problem, the confusion matrix is k×k. Each row represents an actual class and each column represents a predicted class. Diagonal elements are correct predictions; off-diagonal elements are misclassifications.
Multi-class confusion matrices reveal which classes the model confuses most. For example, a digit recogniser might frequently confuse 4s and 9s because they look similar. This insight guides targeted improvements: collect more training examples of confused classes, add features that distinguish them, or post-process predictions for those specific pairs.
from sklearn.metrics import confusion_matrix
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import seaborn as sns
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = DecisionTreeClassifier(max_depth=10)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(9, 7))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Digit Confusion Matrix (10 classes)')
plt.show()Normalised Confusion Matrix
When classes have different numbers of examples (class imbalance), absolute counts in the confusion matrix can be misleading. A normalised confusion matrix divides each row by the total number of actual examples in that class, converting raw counts to recall rates (proportion correctly identified).
A perfect classifier has 1.0 on every diagonal cell and 0.0 everywhere else. A normalised matrix makes it easy to compare per-class performance regardless of class size.
from sklearn.metrics import confusion_matrix
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
cm = confusion_matrix(y_test, y_pred)
# Normalise by row (actual class total)
cm_norm = cm.astype(float) / cm.sum(axis=1, keepdims=True)
plt.figure(figsize=(9, 7))
sns.heatmap(cm_norm, annot=True, fmt='.2f', cmap='Blues')
plt.ylabel('Actual Class')
plt.xlabel('Predicted Class')
plt.title('Normalised Confusion Matrix (row = recall per class)')
plt.show()
# Per-class recall from diagonal
print('Per-class recall:', np.diag(cm_norm).round(3))ConfusionMatrixDisplay: The Official scikit-learn Tool
Scikit-learn provides ConfusionMatrixDisplay as a high-level tool for plotting confusion matrices without needing seaborn. You can create it directly from the confusion matrix array or by calling from_estimator() which runs prediction internally.
Setting display_labels to your class names makes the plot immediately self-documenting. The display also includes an optional colour bar that helps readers estimate values before reading exact numbers.
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True)
class_names = load_breast_cancer().target_names # ['malignant', 'benign']
# Method 1: from_estimator (runs predict internally)
disp = ConfusionMatrixDisplay.from_estimator(
model,
X_test_s,
y_test,
display_labels=class_names,
cmap='Blues'
)
disp.ax_.set_title('Confusion Matrix')What the Confusion Matrix Tells You
A well-trained classifier should have most examples on the diagonal. When you see large off-diagonal numbers, diagnose the cause:
- Many FP (false positives): the model is too aggressive — lower the decision threshold or add regularisation.
- Many FN (false negatives): the model misses too many real positives — lower the threshold or improve recall.
- Symmetric errors between class A and B: the two classes are too similar in feature space — add distinguishing features.
- Errors concentrated in one actual class: that class is underrepresented or harder to learn — oversample it or collect more data.
Confusion Matrix to Full Classification Report
Every metric in the classification_report() is derived from the confusion matrix. Understanding the matrix is understanding all metrics at once. From TP, TN, FP, FN you can compute:
- Accuracy = (TP+TN)/N
- Precision = TP/(TP+FP)
- Recall = TP/(TP+FN)
- Specificity = TN/(TN+FP)
- F1 = 2×Precision×Recall/(Precision+Recall)
In the next lesson you will master all these derived metrics and learn when each one is the right choice.
from sklearn.metrics import classification_report, confusion_matrix
import numpy as np
y_true = np.array([1, 0, 1, 1, 0, 0, 1, 0, 1, 0])
y_pred = np.array([1, 0, 1, 0, 1, 0, 1, 0, 0, 0])
cm = confusion_matrix(y_true, y_pred)
TN, FP, FN, TP = cm.ravel()
# Compute all metrics from raw counts
precision = TP / (TP + FP) if (TP + FP) > 0 else 0
recall = TP / (TP + FN) if (TP + FN) > 0 else 0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
print(f'Precision: {precision:.2f}')
print(f'Recall: {recall:.2f}')
print(f'F1-Score: {f1:.2f}')
print('\nscikit-learn report:')
print(classification_report(y_true, y_pred))Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: the confusion matrix breaks down classifier errors into True Positives, True Negatives, False Positives, and False Negatives, False Negatives (Type II errors) and False Positives (Type I errors) have very different real-world consequences, and all classification metrics — accuracy, precision, recall, F1 — are derived from these four confusion matrix counts. Next up we master precision, recall, and F1-score in depth, and learn the critical trade-off between them that guides real-world classifier evaluation.
เรียนรู้ Python ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “อธิบายเมทริกซ์ความสับสน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “อธิบายเมทริกซ์ความสับสน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “อธิบายเมทริกซ์ความสับสน”
ผู้เรียนจะสร้างเมทริกซ์ความสับสนจากผลการพยากรณ์และค่าจริง จากนั้นหาจำนวนผลบวกจริง ผลลบเท็จ และจำนวนที่เกี่ยวข้อง คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “อธิบายเมทริกซ์ความสับสน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม
ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- จากการถดถอยสู่การจำแนก: การตัดสินใจด้วยค่าเกณฑ์
- การถดถอยลอจิสติกและฟังก์ชันซิกมอยด์
- อธิบายเมทริกซ์ความสับสน
- ความแม่นยำ การเรียกคืน และ F1-Score ในทางปฏิบัติ